blob: a0e9192329686cc3e8a3b96e3e3948b07abb82ce [file] [log] [blame]
Thomas Gleixner5b497af2019-05-29 07:18:09 -07001// SPDX-License-Identifier: GPL-2.0-only
Alexei Starovoitov51580e72014-09-26 00:17:02 -07002/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003 * Copyright (c) 2016 Facebook
Joe Stringerfd978bf72018-10-02 13:35:35 -07004 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
Alexei Starovoitov51580e72014-09-26 00:17:02 -07005 */
Yonghong Song838e9692018-11-19 15:29:11 -08006#include <uapi/linux/btf.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -07007#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
Yonghong Song838e9692018-11-19 15:29:11 -080011#include <linux/btf.h>
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012#include <linux/bpf_verifier.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
Thomas Grafebb676d2016-10-27 11:23:51 +020017#include <linux/stringify.h>
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080018#include <linux/bsearch.h>
19#include <linux/sort.h>
Yonghong Songc195651e2018-04-28 22:28:08 -070020#include <linux/perf_event.h>
Martin KaFai Laud9762e82018-12-13 10:41:48 -080021#include <linux/ctype.h>
KP Singh6ba43b72020-03-04 20:18:50 +010022#include <linux/error-injection.h>
KP Singh9e4e01d2020-03-29 01:43:52 +010023#include <linux/bpf_lsm.h>
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070024#include <linux/btf_ids.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -070025
Jakub Kicinskif4ac7e02017-10-09 10:30:12 -070026#include "disasm.h"
27
Jakub Kicinski00176a32017-10-16 16:40:54 -070028static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
Alexei Starovoitov91cc1a92019-11-14 10:57:15 -080029#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
Jakub Kicinski00176a32017-10-16 16:40:54 -070030 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
Andrii Nakryikof2e10bf2020-04-28 17:16:08 -070032#define BPF_LINK_TYPE(_id, _name)
Jakub Kicinski00176a32017-10-16 16:40:54 -070033#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
Andrii Nakryikof2e10bf2020-04-28 17:16:08 -070036#undef BPF_LINK_TYPE
Jakub Kicinski00176a32017-10-16 16:40:54 -070037};
38
Alexei Starovoitov51580e72014-09-26 00:17:02 -070039/* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 *
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
Gary Lineba38a92017-03-01 16:25:51 +080051 * analysis is limited to 64k insn, which may be hit even if total number of
Alexei Starovoitov51580e72014-09-26 00:17:02 -070052 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
54 *
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * copied to R1.
59 *
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 *
Edward Creef1174f72017-08-07 15:26:19 +010079 * Most of the time the registers have SCALAR_VALUE type, which
Alexei Starovoitov51580e72014-09-26 00:17:02 -070080 * means the register has some value, but it's not a valid pointer.
Edward Creef1174f72017-08-07 15:26:19 +010081 * (like pointer plus pointer becomes SCALAR_VALUE type)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070082 *
83 * When verifier sees load or store instructions the type of base register
Joe Stringerc64b7982018-10-02 13:35:33 -070084 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
Alexei Starovoitov51580e72014-09-26 00:17:02 -070086 *
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
97 *
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 *
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
107 *
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
118 * }
119 *
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 *
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
136 *
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
141 *
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
Joe Stringerfd978bf72018-10-02 13:35:35 -0700144 *
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
Joe Stringer6acc9b42018-10-02 13:35:36 -0700156 *
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
Alexei Starovoitov51580e72014-09-26 00:17:02 -0700162 */
163
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100165struct bpf_verifier_stack_elem {
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100170 struct bpf_verifier_state st;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700171 int insn_idx;
172 int prev_insn_idx;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100173 struct bpf_verifier_stack_elem *next;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700176};
177
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
Alexei Starovoitovceefbc92018-12-03 22:46:06 -0800179#define BPF_COMPLEXITY_LIMIT_STATES 64
Daniel Borkmann07016152016-04-05 22:33:17 +0200180
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200184#define BPF_MAP_PTR_UNPRIV 1UL
185#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200197}
198
199static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201{
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206}
207
208static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209{
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211}
212
213static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214{
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216}
217
218static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221}
222
223static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224{
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200229}
Martin KaFai Laufad73a12017-03-22 10:00:32 -0700230
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200231struct bpf_call_arg_meta {
232 struct bpf_map *map_ptr;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200233 bool raw_mode;
Daniel Borkmann36bbef52016-09-20 00:26:13 +0200234 bool pkt_access;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200235 int regno;
236 int access_size;
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700237 int mem_size;
John Fastabend10060502020-03-30 14:36:19 -0700238 u64 msize_max_value;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700239 int ref_obj_id;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800240 int func_id;
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200241};
242
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700243struct btf *btf_vmlinux;
244
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700245static DEFINE_MUTEX(bpf_verifier_lock);
246
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800247static const struct bpf_line_info *
248find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
249{
250 const struct bpf_line_info *linfo;
251 const struct bpf_prog *prog;
252 u32 i, nr_linfo;
253
254 prog = env->prog;
255 nr_linfo = prog->aux->nr_linfo;
256
257 if (!nr_linfo || insn_off >= prog->len)
258 return NULL;
259
260 linfo = prog->aux->linfo;
261 for (i = 1; i < nr_linfo; i++)
262 if (insn_off < linfo[i].insn_off)
263 break;
264
265 return &linfo[i - 1];
266}
267
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700268void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
269 va_list args)
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700270{
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700271 unsigned int n;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700272
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700273 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700274
275 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
276 "verifier log line truncated - local buffer too short\n");
277
278 n = min(log->len_total - log->len_used - 1, n);
279 log->kbuf[n] = '\0';
280
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700281 if (log->level == BPF_LOG_KERNEL) {
282 pr_err("BPF:%s\n", log->kbuf);
283 return;
284 }
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700285 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
286 log->len_used += n;
287 else
288 log->ubuf = NULL;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700289}
Jiri Olsaabe08842018-03-23 11:41:28 +0100290
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700291static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
292{
293 char zero = 0;
294
295 if (!bpf_verifier_log_needed(log))
296 return;
297
298 log->len_used = new_pos;
299 if (put_user(zero, log->ubuf + new_pos))
300 log->ubuf = NULL;
301}
302
Jiri Olsaabe08842018-03-23 11:41:28 +0100303/* log_level controls verbosity level of eBPF verifier.
304 * bpf_verifier_log_write() is used to dump the verification trace to the log,
305 * so the user can figure out what's wrong with the program
Quentin Monnet430e68d2018-01-10 12:26:06 +0000306 */
Jiri Olsaabe08842018-03-23 11:41:28 +0100307__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
308 const char *fmt, ...)
309{
310 va_list args;
311
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700312 if (!bpf_verifier_log_needed(&env->log))
313 return;
314
Jiri Olsaabe08842018-03-23 11:41:28 +0100315 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700316 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100317 va_end(args);
318}
319EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
320
321__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
322{
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700323 struct bpf_verifier_env *env = private_data;
Jiri Olsaabe08842018-03-23 11:41:28 +0100324 va_list args;
325
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700326 if (!bpf_verifier_log_needed(&env->log))
327 return;
328
Jiri Olsaabe08842018-03-23 11:41:28 +0100329 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700330 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100331 va_end(args);
332}
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700333
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700334__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
335 const char *fmt, ...)
336{
337 va_list args;
338
339 if (!bpf_verifier_log_needed(log))
340 return;
341
342 va_start(args, fmt);
343 bpf_verifier_vlog(log, fmt, args);
344 va_end(args);
345}
346
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800347static const char *ltrim(const char *s)
348{
349 while (isspace(*s))
350 s++;
351
352 return s;
353}
354
355__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
356 u32 insn_off,
357 const char *prefix_fmt, ...)
358{
359 const struct bpf_line_info *linfo;
360
361 if (!bpf_verifier_log_needed(&env->log))
362 return;
363
364 linfo = find_linfo(env, insn_off);
365 if (!linfo || linfo == env->prev_linfo)
366 return;
367
368 if (prefix_fmt) {
369 va_list args;
370
371 va_start(args, prefix_fmt);
372 bpf_verifier_vlog(&env->log, prefix_fmt, args);
373 va_end(args);
374 }
375
376 verbose(env, "%s\n",
377 ltrim(btf_name_by_offset(env->prog->aux->btf,
378 linfo->line_off)));
379
380 env->prev_linfo = linfo;
381}
382
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200383static bool type_is_pkt_pointer(enum bpf_reg_type type)
384{
385 return type == PTR_TO_PACKET ||
386 type == PTR_TO_PACKET_META;
387}
388
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800389static bool type_is_sk_pointer(enum bpf_reg_type type)
390{
391 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800392 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700393 type == PTR_TO_TCP_SOCK ||
394 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800395}
396
John Fastabendcac616d2020-05-21 13:07:26 -0700397static bool reg_type_not_null(enum bpf_reg_type type)
398{
399 return type == PTR_TO_SOCKET ||
400 type == PTR_TO_TCP_SOCK ||
401 type == PTR_TO_MAP_VALUE ||
Yonghong Song01c66c42020-06-30 10:12:40 -0700402 type == PTR_TO_SOCK_COMMON;
John Fastabendcac616d2020-05-21 13:07:26 -0700403}
404
Joe Stringer840b9612018-10-02 13:35:32 -0700405static bool reg_type_may_be_null(enum bpf_reg_type type)
406{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700407 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800408 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800409 type == PTR_TO_SOCK_COMMON_OR_NULL ||
Yonghong Songb121b342020-05-09 10:59:12 -0700410 type == PTR_TO_TCP_SOCK_OR_NULL ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700411 type == PTR_TO_BTF_ID_OR_NULL ||
Yonghong Songafbf21d2020-07-23 11:41:11 -0700412 type == PTR_TO_MEM_OR_NULL ||
413 type == PTR_TO_RDONLY_BUF_OR_NULL ||
414 type == PTR_TO_RDWR_BUF_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700415}
416
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800417static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
418{
419 return reg->type == PTR_TO_MAP_VALUE &&
420 map_value_has_spin_lock(reg->map_ptr);
421}
422
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700423static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
424{
425 return type == PTR_TO_SOCKET ||
426 type == PTR_TO_SOCKET_OR_NULL ||
427 type == PTR_TO_TCP_SOCK ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700428 type == PTR_TO_TCP_SOCK_OR_NULL ||
429 type == PTR_TO_MEM ||
430 type == PTR_TO_MEM_OR_NULL;
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700431}
432
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700433static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700434{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700435 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700436}
437
438/* Determine whether the function releases some resources allocated by another
439 * function call. The first reference type argument will be assumed to be
440 * released by release_reference().
441 */
442static bool is_release_function(enum bpf_func_id func_id)
443{
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700444 return func_id == BPF_FUNC_sk_release ||
445 func_id == BPF_FUNC_ringbuf_submit ||
446 func_id == BPF_FUNC_ringbuf_discard;
Joe Stringer840b9612018-10-02 13:35:32 -0700447}
448
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200449static bool may_be_acquire_function(enum bpf_func_id func_id)
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800450{
451 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800452 func_id == BPF_FUNC_sk_lookup_udp ||
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200453 func_id == BPF_FUNC_skc_lookup_tcp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700454 func_id == BPF_FUNC_map_lookup_elem ||
455 func_id == BPF_FUNC_ringbuf_reserve;
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200456}
457
458static bool is_acquire_function(enum bpf_func_id func_id,
459 const struct bpf_map *map)
460{
461 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
462
463 if (func_id == BPF_FUNC_sk_lookup_tcp ||
464 func_id == BPF_FUNC_sk_lookup_udp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700465 func_id == BPF_FUNC_skc_lookup_tcp ||
466 func_id == BPF_FUNC_ringbuf_reserve)
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200467 return true;
468
469 if (func_id == BPF_FUNC_map_lookup_elem &&
470 (map_type == BPF_MAP_TYPE_SOCKMAP ||
471 map_type == BPF_MAP_TYPE_SOCKHASH))
472 return true;
473
474 return false;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800475}
476
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700477static bool is_ptr_cast_function(enum bpf_func_id func_id)
478{
479 return func_id == BPF_FUNC_tcp_sock ||
480 func_id == BPF_FUNC_sk_fullsock;
481}
482
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700483/* string representation of 'enum bpf_reg_type' */
484static const char * const reg_type_str[] = {
485 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100486 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700487 [PTR_TO_CTX] = "ctx",
488 [CONST_PTR_TO_MAP] = "map_ptr",
489 [PTR_TO_MAP_VALUE] = "map_value",
490 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700491 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700492 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200493 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700494 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700495 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700496 [PTR_TO_SOCKET] = "sock",
497 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800498 [PTR_TO_SOCK_COMMON] = "sock_common",
499 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800500 [PTR_TO_TCP_SOCK] = "tcp_sock",
501 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700502 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700503 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700504 [PTR_TO_BTF_ID] = "ptr_",
Yonghong Songb121b342020-05-09 10:59:12 -0700505 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700506 [PTR_TO_MEM] = "mem",
507 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
Yonghong Songafbf21d2020-07-23 11:41:11 -0700508 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
509 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
510 [PTR_TO_RDWR_BUF] = "rdwr_buf",
511 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700512};
513
Edward Cree8efea212018-08-22 20:02:44 +0100514static char slot_type_char[] = {
515 [STACK_INVALID] = '?',
516 [STACK_SPILL] = 'r',
517 [STACK_MISC] = 'm',
518 [STACK_ZERO] = '0',
519};
520
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800521static void print_liveness(struct bpf_verifier_env *env,
522 enum bpf_reg_liveness live)
523{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800524 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800525 verbose(env, "_");
526 if (live & REG_LIVE_READ)
527 verbose(env, "r");
528 if (live & REG_LIVE_WRITTEN)
529 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800530 if (live & REG_LIVE_DONE)
531 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800532}
533
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800534static struct bpf_func_state *func(struct bpf_verifier_env *env,
535 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700536{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800537 struct bpf_verifier_state *cur = env->cur_state;
538
539 return cur->frame[reg->frameno];
540}
541
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700542const char *kernel_type_name(u32 id)
543{
544 return btf_name_by_offset(btf_vmlinux,
545 btf_type_by_id(btf_vmlinux, id)->name_off);
546}
547
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800548static void print_verifier_state(struct bpf_verifier_env *env,
549 const struct bpf_func_state *state)
550{
551 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700552 enum bpf_reg_type t;
553 int i;
554
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800555 if (state->frameno)
556 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700557 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700558 reg = &state->regs[i];
559 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700560 if (t == NOT_INIT)
561 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800562 verbose(env, " R%d", i);
563 print_liveness(env, reg->live);
564 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700565 if (t == SCALAR_VALUE && reg->precise)
566 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100567 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
568 tnum_is_const(reg->var_off)) {
569 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700570 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100571 } else {
Yonghong Songb121b342020-05-09 10:59:12 -0700572 if (t == PTR_TO_BTF_ID || t == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700573 verbose(env, "%s", kernel_type_name(reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700574 verbose(env, "(id=%d", reg->id);
575 if (reg_type_may_be_refcounted_or_null(t))
576 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100577 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700578 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200579 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700580 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100581 else if (t == CONST_PTR_TO_MAP ||
582 t == PTR_TO_MAP_VALUE ||
583 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700584 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100585 reg->map_ptr->key_size,
586 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100587 if (tnum_is_const(reg->var_off)) {
588 /* Typically an immediate SCALAR_VALUE, but
589 * could be a pointer whose offset is too big
590 * for reg->off
591 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700592 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100593 } else {
594 if (reg->smin_value != reg->umin_value &&
595 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700596 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100597 (long long)reg->smin_value);
598 if (reg->smax_value != reg->umax_value &&
599 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700600 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100601 (long long)reg->smax_value);
602 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700603 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100604 (unsigned long long)reg->umin_value);
605 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700606 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100607 (unsigned long long)reg->umax_value);
608 if (!tnum_is_unknown(reg->var_off)) {
609 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100610
Edward Cree7d1238f2017-08-07 15:26:56 +0100611 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700612 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100613 }
John Fastabend3f50f132020-03-30 14:36:39 -0700614 if (reg->s32_min_value != reg->smin_value &&
615 reg->s32_min_value != S32_MIN)
616 verbose(env, ",s32_min_value=%d",
617 (int)(reg->s32_min_value));
618 if (reg->s32_max_value != reg->smax_value &&
619 reg->s32_max_value != S32_MAX)
620 verbose(env, ",s32_max_value=%d",
621 (int)(reg->s32_max_value));
622 if (reg->u32_min_value != reg->umin_value &&
623 reg->u32_min_value != U32_MIN)
624 verbose(env, ",u32_min_value=%d",
625 (int)(reg->u32_min_value));
626 if (reg->u32_max_value != reg->umax_value &&
627 reg->u32_max_value != U32_MAX)
628 verbose(env, ",u32_max_value=%d",
629 (int)(reg->u32_max_value));
Edward Creef1174f72017-08-07 15:26:19 +0100630 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700631 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100632 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700633 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700634 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100635 char types_buf[BPF_REG_SIZE + 1];
636 bool valid = false;
637 int j;
638
639 for (j = 0; j < BPF_REG_SIZE; j++) {
640 if (state->stack[i].slot_type[j] != STACK_INVALID)
641 valid = true;
642 types_buf[j] = slot_type_char[
643 state->stack[i].slot_type[j]];
644 }
645 types_buf[BPF_REG_SIZE] = 0;
646 if (!valid)
647 continue;
648 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
649 print_liveness(env, state->stack[i].spilled_ptr.live);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700650 if (state->stack[i].slot_type[0] == STACK_SPILL) {
651 reg = &state->stack[i].spilled_ptr;
652 t = reg->type;
653 verbose(env, "=%s", reg_type_str[t]);
654 if (t == SCALAR_VALUE && reg->precise)
655 verbose(env, "P");
656 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
657 verbose(env, "%lld", reg->var_off.value + reg->off);
658 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100659 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700660 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700661 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700662 if (state->acquired_refs && state->refs[0].id) {
663 verbose(env, " refs=%d", state->refs[0].id);
664 for (i = 1; i < state->acquired_refs; i++)
665 if (state->refs[i].id)
666 verbose(env, ",%d", state->refs[i].id);
667 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700668 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700669}
670
Joe Stringer84dbf352018-10-02 13:35:34 -0700671#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
672static int copy_##NAME##_state(struct bpf_func_state *dst, \
673 const struct bpf_func_state *src) \
674{ \
675 if (!src->FIELD) \
676 return 0; \
677 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
678 /* internal bug, make state invalid to reject the program */ \
679 memset(dst, 0, sizeof(*dst)); \
680 return -EFAULT; \
681 } \
682 memcpy(dst->FIELD, src->FIELD, \
683 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
684 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700685}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700686/* copy_reference_state() */
687COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700688/* copy_stack_state() */
689COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
690#undef COPY_STATE_FN
691
692#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
693static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
694 bool copy_old) \
695{ \
696 u32 old_size = state->COUNT; \
697 struct bpf_##NAME##_state *new_##FIELD; \
698 int slot = size / SIZE; \
699 \
700 if (size <= old_size || !size) { \
701 if (copy_old) \
702 return 0; \
703 state->COUNT = slot * SIZE; \
704 if (!size && old_size) { \
705 kfree(state->FIELD); \
706 state->FIELD = NULL; \
707 } \
708 return 0; \
709 } \
710 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
711 GFP_KERNEL); \
712 if (!new_##FIELD) \
713 return -ENOMEM; \
714 if (copy_old) { \
715 if (state->FIELD) \
716 memcpy(new_##FIELD, state->FIELD, \
717 sizeof(*new_##FIELD) * (old_size / SIZE)); \
718 memset(new_##FIELD + old_size / SIZE, 0, \
719 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
720 } \
721 state->COUNT = slot * SIZE; \
722 kfree(state->FIELD); \
723 state->FIELD = new_##FIELD; \
724 return 0; \
725}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700726/* realloc_reference_state() */
727REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700728/* realloc_stack_state() */
729REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
730#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700731
732/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
733 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800734 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700735 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
736 * which realloc_stack_state() copies over. It points to previous
737 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700738 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700739static int realloc_func_state(struct bpf_func_state *state, int stack_size,
740 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700741{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700742 int err = realloc_reference_state(state, refs_size, copy_old);
743 if (err)
744 return err;
745 return realloc_stack_state(state, stack_size, copy_old);
746}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700747
Joe Stringerfd978bf72018-10-02 13:35:35 -0700748/* Acquire a pointer id from the env and update the state->refs to include
749 * this new pointer reference.
750 * On success, returns a valid pointer id to associate with the register
751 * On failure, returns a negative errno.
752 */
753static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
754{
755 struct bpf_func_state *state = cur_func(env);
756 int new_ofs = state->acquired_refs;
757 int id, err;
758
759 err = realloc_reference_state(state, state->acquired_refs + 1, true);
760 if (err)
761 return err;
762 id = ++env->id_gen;
763 state->refs[new_ofs].id = id;
764 state->refs[new_ofs].insn_idx = insn_idx;
765
766 return id;
767}
768
769/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800770static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700771{
772 int i, last_idx;
773
Joe Stringerfd978bf72018-10-02 13:35:35 -0700774 last_idx = state->acquired_refs - 1;
775 for (i = 0; i < state->acquired_refs; i++) {
776 if (state->refs[i].id == ptr_id) {
777 if (last_idx && i != last_idx)
778 memcpy(&state->refs[i], &state->refs[last_idx],
779 sizeof(*state->refs));
780 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
781 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700782 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700783 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700784 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800785 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700786}
787
788static int transfer_reference_state(struct bpf_func_state *dst,
789 struct bpf_func_state *src)
790{
791 int err = realloc_reference_state(dst, src->acquired_refs, false);
792 if (err)
793 return err;
794 err = copy_reference_state(dst, src);
795 if (err)
796 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700797 return 0;
798}
799
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800800static void free_func_state(struct bpf_func_state *state)
801{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800802 if (!state)
803 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700804 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800805 kfree(state->stack);
806 kfree(state);
807}
808
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700809static void clear_jmp_history(struct bpf_verifier_state *state)
810{
811 kfree(state->jmp_history);
812 state->jmp_history = NULL;
813 state->jmp_history_cnt = 0;
814}
815
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700816static void free_verifier_state(struct bpf_verifier_state *state,
817 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700818{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800819 int i;
820
821 for (i = 0; i <= state->curframe; i++) {
822 free_func_state(state->frame[i]);
823 state->frame[i] = NULL;
824 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700825 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700826 if (free_self)
827 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700828}
829
830/* copy verifier state from src to dst growing dst stack space
831 * when necessary to accommodate larger src stack
832 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800833static int copy_func_state(struct bpf_func_state *dst,
834 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700835{
836 int err;
837
Joe Stringerfd978bf72018-10-02 13:35:35 -0700838 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
839 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700840 if (err)
841 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700842 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
843 err = copy_reference_state(dst, src);
844 if (err)
845 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700846 return copy_stack_state(dst, src);
847}
848
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800849static int copy_verifier_state(struct bpf_verifier_state *dst_state,
850 const struct bpf_verifier_state *src)
851{
852 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700853 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800854 int i, err;
855
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700856 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
857 kfree(dst_state->jmp_history);
858 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
859 if (!dst_state->jmp_history)
860 return -ENOMEM;
861 }
862 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
863 dst_state->jmp_history_cnt = src->jmp_history_cnt;
864
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800865 /* if dst has more stack frames then src frame, free them */
866 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
867 free_func_state(dst_state->frame[i]);
868 dst_state->frame[i] = NULL;
869 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100870 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800871 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800872 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700873 dst_state->branches = src->branches;
874 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700875 dst_state->first_insn_idx = src->first_insn_idx;
876 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800877 for (i = 0; i <= src->curframe; i++) {
878 dst = dst_state->frame[i];
879 if (!dst) {
880 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
881 if (!dst)
882 return -ENOMEM;
883 dst_state->frame[i] = dst;
884 }
885 err = copy_func_state(dst, src->frame[i]);
886 if (err)
887 return err;
888 }
889 return 0;
890}
891
Alexei Starovoitov25897262019-06-15 12:12:20 -0700892static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
893{
894 while (st) {
895 u32 br = --st->branches;
896
897 /* WARN_ON(br > 1) technically makes sense here,
898 * but see comment in push_stack(), hence:
899 */
900 WARN_ONCE((int)br < 0,
901 "BUG update_branch_counts:branches_to_explore=%d\n",
902 br);
903 if (br)
904 break;
905 st = st->parent;
906 }
907}
908
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700909static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700910 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700911{
912 struct bpf_verifier_state *cur = env->cur_state;
913 struct bpf_verifier_stack_elem *elem, *head = env->head;
914 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700915
916 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700917 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700918
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700919 if (cur) {
920 err = copy_verifier_state(cur, &head->st);
921 if (err)
922 return err;
923 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700924 if (pop_log)
925 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700926 if (insn_idx)
927 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700928 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700929 *prev_insn_idx = head->prev_insn_idx;
930 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700931 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700932 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700933 env->head = elem;
934 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700935 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700936}
937
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100938static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100939 int insn_idx, int prev_insn_idx,
940 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700941{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700942 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100943 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700944 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700945
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700946 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700947 if (!elem)
948 goto err;
949
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700950 elem->insn_idx = insn_idx;
951 elem->prev_insn_idx = prev_insn_idx;
952 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700953 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700954 env->head = elem;
955 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700956 err = copy_verifier_state(&elem->st, cur);
957 if (err)
958 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100959 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700960 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
961 verbose(env, "The sequence of %d jumps is too complex.\n",
962 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700963 goto err;
964 }
Alexei Starovoitov25897262019-06-15 12:12:20 -0700965 if (elem->st.parent) {
966 ++elem->st.parent->branches;
967 /* WARN_ON(branches > 2) technically makes sense here,
968 * but
969 * 1. speculative states will bump 'branches' for non-branch
970 * instructions
971 * 2. is_state_visited() heuristics may decide not to create
972 * a new state for a sequence of branches and all such current
973 * and cloned states will be pointing to a single parent state
974 * which might have large 'branches' count.
975 */
976 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700977 return &elem->st;
978err:
Alexei Starovoitov58963512018-01-08 07:51:17 -0800979 free_verifier_state(env->cur_state, true);
980 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700981 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700982 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700983 return NULL;
984}
985
986#define CALLER_SAVED_REGS 6
987static const int caller_saved[CALLER_SAVED_REGS] = {
988 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
989};
990
Daniel Borkmannf54c7892019-12-22 23:37:40 +0100991static void __mark_reg_not_init(const struct bpf_verifier_env *env,
992 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +0100993
Edward Creeb03c9f92017-08-07 15:26:36 +0100994/* Mark the unknown part of a register (variable offset or scalar value) as
995 * known to have the value @imm.
996 */
997static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
998{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -0700999 /* Clear id, off, and union(map_ptr, range) */
1000 memset(((u8 *)reg) + sizeof(reg->type), 0,
1001 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
Edward Creeb03c9f92017-08-07 15:26:36 +01001002 reg->var_off = tnum_const(imm);
1003 reg->smin_value = (s64)imm;
1004 reg->smax_value = (s64)imm;
1005 reg->umin_value = imm;
1006 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001007
1008 reg->s32_min_value = (s32)imm;
1009 reg->s32_max_value = (s32)imm;
1010 reg->u32_min_value = (u32)imm;
1011 reg->u32_max_value = (u32)imm;
1012}
1013
1014static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1015{
1016 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1017 reg->s32_min_value = (s32)imm;
1018 reg->s32_max_value = (s32)imm;
1019 reg->u32_min_value = (u32)imm;
1020 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001021}
1022
Edward Creef1174f72017-08-07 15:26:19 +01001023/* Mark the 'variable offset' part of a register as zero. This should be
1024 * used only on registers holding a pointer type.
1025 */
1026static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1027{
Edward Creeb03c9f92017-08-07 15:26:36 +01001028 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001029}
1030
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001031static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1032{
1033 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001034 reg->type = SCALAR_VALUE;
1035}
1036
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001037static void mark_reg_known_zero(struct bpf_verifier_env *env,
1038 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001039{
1040 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001041 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001042 /* Something bad happened, let's kill all regs */
1043 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001044 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001045 return;
1046 }
1047 __mark_reg_known_zero(regs + regno);
1048}
1049
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001050static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1051{
1052 return type_is_pkt_pointer(reg->type);
1053}
1054
1055static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1056{
1057 return reg_is_pkt_pointer(reg) ||
1058 reg->type == PTR_TO_PACKET_END;
1059}
1060
1061/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1062static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1063 enum bpf_reg_type which)
1064{
1065 /* The register can already have a range from prior markings.
1066 * This is fine as long as it hasn't been advanced from its
1067 * origin.
1068 */
1069 return reg->type == which &&
1070 reg->id == 0 &&
1071 reg->off == 0 &&
1072 tnum_equals_const(reg->var_off, 0);
1073}
1074
John Fastabend3f50f132020-03-30 14:36:39 -07001075/* Reset the min/max bounds of a register */
1076static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1077{
1078 reg->smin_value = S64_MIN;
1079 reg->smax_value = S64_MAX;
1080 reg->umin_value = 0;
1081 reg->umax_value = U64_MAX;
1082
1083 reg->s32_min_value = S32_MIN;
1084 reg->s32_max_value = S32_MAX;
1085 reg->u32_min_value = 0;
1086 reg->u32_max_value = U32_MAX;
1087}
1088
1089static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1090{
1091 reg->smin_value = S64_MIN;
1092 reg->smax_value = S64_MAX;
1093 reg->umin_value = 0;
1094 reg->umax_value = U64_MAX;
1095}
1096
1097static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1098{
1099 reg->s32_min_value = S32_MIN;
1100 reg->s32_max_value = S32_MAX;
1101 reg->u32_min_value = 0;
1102 reg->u32_max_value = U32_MAX;
1103}
1104
1105static void __update_reg32_bounds(struct bpf_reg_state *reg)
1106{
1107 struct tnum var32_off = tnum_subreg(reg->var_off);
1108
1109 /* min signed is max(sign bit) | min(other bits) */
1110 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1111 var32_off.value | (var32_off.mask & S32_MIN));
1112 /* max signed is min(sign bit) | max(other bits) */
1113 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1114 var32_off.value | (var32_off.mask & S32_MAX));
1115 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1116 reg->u32_max_value = min(reg->u32_max_value,
1117 (u32)(var32_off.value | var32_off.mask));
1118}
1119
1120static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001121{
1122 /* min signed is max(sign bit) | min(other bits) */
1123 reg->smin_value = max_t(s64, reg->smin_value,
1124 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1125 /* max signed is min(sign bit) | max(other bits) */
1126 reg->smax_value = min_t(s64, reg->smax_value,
1127 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1128 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1129 reg->umax_value = min(reg->umax_value,
1130 reg->var_off.value | reg->var_off.mask);
1131}
1132
John Fastabend3f50f132020-03-30 14:36:39 -07001133static void __update_reg_bounds(struct bpf_reg_state *reg)
1134{
1135 __update_reg32_bounds(reg);
1136 __update_reg64_bounds(reg);
1137}
1138
Edward Creeb03c9f92017-08-07 15:26:36 +01001139/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001140static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1141{
1142 /* Learn sign from signed bounds.
1143 * If we cannot cross the sign boundary, then signed and unsigned bounds
1144 * are the same, so combine. This works even in the negative case, e.g.
1145 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1146 */
1147 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1148 reg->s32_min_value = reg->u32_min_value =
1149 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1150 reg->s32_max_value = reg->u32_max_value =
1151 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1152 return;
1153 }
1154 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1155 * boundary, so we must be careful.
1156 */
1157 if ((s32)reg->u32_max_value >= 0) {
1158 /* Positive. We can't learn anything from the smin, but smax
1159 * is positive, hence safe.
1160 */
1161 reg->s32_min_value = reg->u32_min_value;
1162 reg->s32_max_value = reg->u32_max_value =
1163 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1164 } else if ((s32)reg->u32_min_value < 0) {
1165 /* Negative. We can't learn anything from the smax, but smin
1166 * is negative, hence safe.
1167 */
1168 reg->s32_min_value = reg->u32_min_value =
1169 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1170 reg->s32_max_value = reg->u32_max_value;
1171 }
1172}
1173
1174static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001175{
1176 /* Learn sign from signed bounds.
1177 * If we cannot cross the sign boundary, then signed and unsigned bounds
1178 * are the same, so combine. This works even in the negative case, e.g.
1179 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1180 */
1181 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1182 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1183 reg->umin_value);
1184 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1185 reg->umax_value);
1186 return;
1187 }
1188 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1189 * boundary, so we must be careful.
1190 */
1191 if ((s64)reg->umax_value >= 0) {
1192 /* Positive. We can't learn anything from the smin, but smax
1193 * is positive, hence safe.
1194 */
1195 reg->smin_value = reg->umin_value;
1196 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1197 reg->umax_value);
1198 } else if ((s64)reg->umin_value < 0) {
1199 /* Negative. We can't learn anything from the smax, but smin
1200 * is negative, hence safe.
1201 */
1202 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1203 reg->umin_value);
1204 reg->smax_value = reg->umax_value;
1205 }
1206}
1207
John Fastabend3f50f132020-03-30 14:36:39 -07001208static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1209{
1210 __reg32_deduce_bounds(reg);
1211 __reg64_deduce_bounds(reg);
1212}
1213
Edward Creeb03c9f92017-08-07 15:26:36 +01001214/* Attempts to improve var_off based on unsigned min/max information */
1215static void __reg_bound_offset(struct bpf_reg_state *reg)
1216{
John Fastabend3f50f132020-03-30 14:36:39 -07001217 struct tnum var64_off = tnum_intersect(reg->var_off,
1218 tnum_range(reg->umin_value,
1219 reg->umax_value));
1220 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1221 tnum_range(reg->u32_min_value,
1222 reg->u32_max_value));
1223
1224 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001225}
1226
John Fastabend3f50f132020-03-30 14:36:39 -07001227static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001228{
John Fastabend3f50f132020-03-30 14:36:39 -07001229 reg->umin_value = reg->u32_min_value;
1230 reg->umax_value = reg->u32_max_value;
1231 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1232 * but must be positive otherwise set to worse case bounds
1233 * and refine later from tnum.
1234 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001235 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001236 reg->smax_value = reg->s32_max_value;
1237 else
1238 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001239 if (reg->s32_min_value >= 0)
1240 reg->smin_value = reg->s32_min_value;
1241 else
1242 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001243}
1244
1245static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1246{
1247 /* special case when 64-bit register has upper 32-bit register
1248 * zeroed. Typically happens after zext or <<32, >>32 sequence
1249 * allowing us to use 32-bit bounds directly,
1250 */
1251 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1252 __reg_assign_32_into_64(reg);
1253 } else {
1254 /* Otherwise the best we can do is push lower 32bit known and
1255 * unknown bits into register (var_off set from jmp logic)
1256 * then learn as much as possible from the 64-bit tnum
1257 * known and unknown bits. The previous smin/smax bounds are
1258 * invalid here because of jmp32 compare so mark them unknown
1259 * so they do not impact tnum bounds calculation.
1260 */
1261 __mark_reg64_unbounded(reg);
1262 __update_reg_bounds(reg);
1263 }
1264
1265 /* Intersecting with the old var_off might have improved our bounds
1266 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1267 * then new var_off is (0; 0x7f...fc) which improves our umax.
1268 */
1269 __reg_deduce_bounds(reg);
1270 __reg_bound_offset(reg);
1271 __update_reg_bounds(reg);
1272}
1273
1274static bool __reg64_bound_s32(s64 a)
1275{
1276 if (a > S32_MIN && a < S32_MAX)
1277 return true;
1278 return false;
1279}
1280
1281static bool __reg64_bound_u32(u64 a)
1282{
1283 if (a > U32_MIN && a < U32_MAX)
1284 return true;
1285 return false;
1286}
1287
1288static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1289{
1290 __mark_reg32_unbounded(reg);
1291
1292 if (__reg64_bound_s32(reg->smin_value))
1293 reg->s32_min_value = (s32)reg->smin_value;
1294 if (__reg64_bound_s32(reg->smax_value))
1295 reg->s32_max_value = (s32)reg->smax_value;
1296 if (__reg64_bound_u32(reg->umin_value))
1297 reg->u32_min_value = (u32)reg->umin_value;
1298 if (__reg64_bound_u32(reg->umax_value))
1299 reg->u32_max_value = (u32)reg->umax_value;
1300
1301 /* Intersecting with the old var_off might have improved our bounds
1302 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1303 * then new var_off is (0; 0x7f...fc) which improves our umax.
1304 */
1305 __reg_deduce_bounds(reg);
1306 __reg_bound_offset(reg);
1307 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001308}
1309
Edward Creef1174f72017-08-07 15:26:19 +01001310/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001311static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1312 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001313{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001314 /*
1315 * Clear type, id, off, and union(map_ptr, range) and
1316 * padding between 'type' and union
1317 */
1318 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001319 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001320 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001321 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001322 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001323 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001324}
1325
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001326static void mark_reg_unknown(struct bpf_verifier_env *env,
1327 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001328{
1329 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001330 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001331 /* Something bad happened, let's kill all regs except FP */
1332 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001333 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001334 return;
1335 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001336 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001337}
1338
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001339static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1340 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001341{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001342 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001343 reg->type = NOT_INIT;
1344}
1345
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001346static void mark_reg_not_init(struct bpf_verifier_env *env,
1347 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001348{
Edward Creef1174f72017-08-07 15:26:19 +01001349 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001350 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001351 /* Something bad happened, let's kill all regs except FP */
1352 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001353 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001354 return;
1355 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001356 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001357}
1358
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001359static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1360 struct bpf_reg_state *regs, u32 regno,
1361 enum bpf_reg_type reg_type, u32 btf_id)
1362{
1363 if (reg_type == SCALAR_VALUE) {
1364 mark_reg_unknown(env, regs, regno);
1365 return;
1366 }
1367 mark_reg_known_zero(env, regs, regno);
1368 regs[regno].type = PTR_TO_BTF_ID;
1369 regs[regno].btf_id = btf_id;
1370}
1371
Jiong Wang5327ed32019-05-24 23:25:12 +01001372#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001373static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001374 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001375{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001376 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001377 int i;
1378
Edward Creedc503a82017-08-15 20:34:35 +01001379 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001380 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001381 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001382 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001383 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001384 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001385
1386 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001387 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001388 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001389 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001390}
1391
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001392#define BPF_MAIN_FUNC (-1)
1393static void init_func_state(struct bpf_verifier_env *env,
1394 struct bpf_func_state *state,
1395 int callsite, int frameno, int subprogno)
1396{
1397 state->callsite = callsite;
1398 state->frameno = frameno;
1399 state->subprogno = subprogno;
1400 init_reg_state(env, state);
1401}
1402
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001403enum reg_arg_type {
1404 SRC_OP, /* register is used as source operand */
1405 DST_OP, /* register is used as destination operand */
1406 DST_OP_NO_MARK /* same as above, check only, don't mark */
1407};
1408
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001409static int cmp_subprogs(const void *a, const void *b)
1410{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001411 return ((struct bpf_subprog_info *)a)->start -
1412 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001413}
1414
1415static int find_subprog(struct bpf_verifier_env *env, int off)
1416{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001417 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001418
Jiong Wang9c8105b2018-05-02 16:17:18 -04001419 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1420 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001421 if (!p)
1422 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001423 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001424
1425}
1426
1427static int add_subprog(struct bpf_verifier_env *env, int off)
1428{
1429 int insn_cnt = env->prog->len;
1430 int ret;
1431
1432 if (off >= insn_cnt || off < 0) {
1433 verbose(env, "call to invalid destination\n");
1434 return -EINVAL;
1435 }
1436 ret = find_subprog(env, off);
1437 if (ret >= 0)
1438 return 0;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001439 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001440 verbose(env, "too many subprograms\n");
1441 return -E2BIG;
1442 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04001443 env->subprog_info[env->subprog_cnt++].start = off;
1444 sort(env->subprog_info, env->subprog_cnt,
1445 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001446 return 0;
1447}
1448
1449static int check_subprogs(struct bpf_verifier_env *env)
1450{
1451 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001452 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001453 struct bpf_insn *insn = env->prog->insnsi;
1454 int insn_cnt = env->prog->len;
1455
Jiong Wangf910cef2018-05-02 16:17:17 -04001456 /* Add entry function. */
1457 ret = add_subprog(env, 0);
1458 if (ret < 0)
1459 return ret;
1460
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001461 /* determine subprog starts. The end is one before the next starts */
1462 for (i = 0; i < insn_cnt; i++) {
1463 if (insn[i].code != (BPF_JMP | BPF_CALL))
1464 continue;
1465 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1466 continue;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001467 if (!env->bpf_capable) {
1468 verbose(env,
1469 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001470 return -EPERM;
1471 }
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001472 ret = add_subprog(env, i + insn[i].imm + 1);
1473 if (ret < 0)
1474 return ret;
1475 }
1476
Jiong Wang4cb3d992018-05-02 16:17:19 -04001477 /* Add a fake 'exit' subprog which could simplify subprog iteration
1478 * logic. 'subprog_cnt' should not be increased.
1479 */
1480 subprog[env->subprog_cnt].start = insn_cnt;
1481
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001482 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001483 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001484 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001485
1486 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001487 subprog_start = subprog[cur_subprog].start;
1488 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001489 for (i = 0; i < insn_cnt; i++) {
1490 u8 code = insn[i].code;
1491
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02001492 if (code == (BPF_JMP | BPF_CALL) &&
1493 insn[i].imm == BPF_FUNC_tail_call &&
1494 insn[i].src_reg != BPF_PSEUDO_CALL)
1495 subprog[cur_subprog].has_tail_call = true;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07001496 if (BPF_CLASS(code) == BPF_LD &&
1497 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1498 subprog[cur_subprog].has_ld_abs = true;
Jiong Wang092ed092019-01-26 12:26:01 -05001499 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001500 goto next;
1501 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1502 goto next;
1503 off = i + insn[i].off + 1;
1504 if (off < subprog_start || off >= subprog_end) {
1505 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1506 return -EINVAL;
1507 }
1508next:
1509 if (i == subprog_end - 1) {
1510 /* to avoid fall-through from one subprog into another
1511 * the last insn of the subprog should be either exit
1512 * or unconditional jump back
1513 */
1514 if (code != (BPF_JMP | BPF_EXIT) &&
1515 code != (BPF_JMP | BPF_JA)) {
1516 verbose(env, "last insn is not an exit or jmp\n");
1517 return -EINVAL;
1518 }
1519 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001520 cur_subprog++;
1521 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001522 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001523 }
1524 }
1525 return 0;
1526}
1527
Edward Cree679c7822018-08-22 20:02:19 +01001528/* Parentage chain of this register (or stack slot) should take care of all
1529 * issues like callee-saved registers, stack slot allocation time, etc.
1530 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001531static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001532 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001533 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001534{
1535 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001536 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001537
1538 while (parent) {
1539 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001540 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001541 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001542 if (parent->live & REG_LIVE_DONE) {
1543 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1544 reg_type_str[parent->type],
1545 parent->var_off.value, parent->off);
1546 return -EFAULT;
1547 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001548 /* The first condition is more likely to be true than the
1549 * second, checked it first.
1550 */
1551 if ((parent->live & REG_LIVE_READ) == flag ||
1552 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001553 /* The parentage chain never changes and
1554 * this parent was already marked as LIVE_READ.
1555 * There is no need to keep walking the chain again and
1556 * keep re-marking all parents as LIVE_READ.
1557 * This case happens when the same register is read
1558 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001559 * Also, if parent has the stronger REG_LIVE_READ64 set,
1560 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001561 */
1562 break;
Edward Creedc503a82017-08-15 20:34:35 +01001563 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001564 parent->live |= flag;
1565 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1566 if (flag == REG_LIVE_READ64)
1567 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001568 state = parent;
1569 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001570 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001571 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001572 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001573
1574 if (env->longest_mark_read_walk < cnt)
1575 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001576 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001577}
1578
Jiong Wang5327ed32019-05-24 23:25:12 +01001579/* This function is supposed to be used by the following 32-bit optimization
1580 * code only. It returns TRUE if the source or destination register operates
1581 * on 64-bit, otherwise return FALSE.
1582 */
1583static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1584 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1585{
1586 u8 code, class, op;
1587
1588 code = insn->code;
1589 class = BPF_CLASS(code);
1590 op = BPF_OP(code);
1591 if (class == BPF_JMP) {
1592 /* BPF_EXIT for "main" will reach here. Return TRUE
1593 * conservatively.
1594 */
1595 if (op == BPF_EXIT)
1596 return true;
1597 if (op == BPF_CALL) {
1598 /* BPF to BPF call will reach here because of marking
1599 * caller saved clobber with DST_OP_NO_MARK for which we
1600 * don't care the register def because they are anyway
1601 * marked as NOT_INIT already.
1602 */
1603 if (insn->src_reg == BPF_PSEUDO_CALL)
1604 return false;
1605 /* Helper call will reach here because of arg type
1606 * check, conservatively return TRUE.
1607 */
1608 if (t == SRC_OP)
1609 return true;
1610
1611 return false;
1612 }
1613 }
1614
1615 if (class == BPF_ALU64 || class == BPF_JMP ||
1616 /* BPF_END always use BPF_ALU class. */
1617 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1618 return true;
1619
1620 if (class == BPF_ALU || class == BPF_JMP32)
1621 return false;
1622
1623 if (class == BPF_LDX) {
1624 if (t != SRC_OP)
1625 return BPF_SIZE(code) == BPF_DW;
1626 /* LDX source must be ptr. */
1627 return true;
1628 }
1629
1630 if (class == BPF_STX) {
1631 if (reg->type != SCALAR_VALUE)
1632 return true;
1633 return BPF_SIZE(code) == BPF_DW;
1634 }
1635
1636 if (class == BPF_LD) {
1637 u8 mode = BPF_MODE(code);
1638
1639 /* LD_IMM64 */
1640 if (mode == BPF_IMM)
1641 return true;
1642
1643 /* Both LD_IND and LD_ABS return 32-bit data. */
1644 if (t != SRC_OP)
1645 return false;
1646
1647 /* Implicit ctx ptr. */
1648 if (regno == BPF_REG_6)
1649 return true;
1650
1651 /* Explicit source could be any width. */
1652 return true;
1653 }
1654
1655 if (class == BPF_ST)
1656 /* The only source register for BPF_ST is a ptr. */
1657 return true;
1658
1659 /* Conservatively return true at default. */
1660 return true;
1661}
1662
Jiong Wangb325fbc2019-05-24 23:25:13 +01001663/* Return TRUE if INSN doesn't have explicit value define. */
1664static bool insn_no_def(struct bpf_insn *insn)
1665{
1666 u8 class = BPF_CLASS(insn->code);
1667
1668 return (class == BPF_JMP || class == BPF_JMP32 ||
1669 class == BPF_STX || class == BPF_ST);
1670}
1671
1672/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1673static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1674{
1675 if (insn_no_def(insn))
1676 return false;
1677
1678 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1679}
1680
Jiong Wang5327ed32019-05-24 23:25:12 +01001681static void mark_insn_zext(struct bpf_verifier_env *env,
1682 struct bpf_reg_state *reg)
1683{
1684 s32 def_idx = reg->subreg_def;
1685
1686 if (def_idx == DEF_NOT_SUBREG)
1687 return;
1688
1689 env->insn_aux_data[def_idx - 1].zext_dst = true;
1690 /* The dst will be zero extended, so won't be sub-register anymore. */
1691 reg->subreg_def = DEF_NOT_SUBREG;
1692}
1693
Edward Creedc503a82017-08-15 20:34:35 +01001694static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001695 enum reg_arg_type t)
1696{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001697 struct bpf_verifier_state *vstate = env->cur_state;
1698 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01001699 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01001700 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01001701 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01001702
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001703 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001704 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001705 return -EINVAL;
1706 }
1707
Jiong Wangc342dc12019-04-12 22:59:37 +01001708 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01001709 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001710 if (t == SRC_OP) {
1711 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01001712 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001713 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001714 return -EACCES;
1715 }
Edward Cree679c7822018-08-22 20:02:19 +01001716 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01001717 if (regno == BPF_REG_FP)
1718 return 0;
1719
Jiong Wang5327ed32019-05-24 23:25:12 +01001720 if (rw64)
1721 mark_insn_zext(env, reg);
1722
1723 return mark_reg_read(env, reg, reg->parent,
1724 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001725 } else {
1726 /* check whether register used as dest operand can be written to */
1727 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001728 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001729 return -EACCES;
1730 }
Jiong Wangc342dc12019-04-12 22:59:37 +01001731 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01001732 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001733 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001734 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001735 }
1736 return 0;
1737}
1738
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001739/* for any branch, call, exit record the history of jmps in the given state */
1740static int push_jmp_history(struct bpf_verifier_env *env,
1741 struct bpf_verifier_state *cur)
1742{
1743 u32 cnt = cur->jmp_history_cnt;
1744 struct bpf_idx_pair *p;
1745
1746 cnt++;
1747 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1748 if (!p)
1749 return -ENOMEM;
1750 p[cnt - 1].idx = env->insn_idx;
1751 p[cnt - 1].prev_idx = env->prev_insn_idx;
1752 cur->jmp_history = p;
1753 cur->jmp_history_cnt = cnt;
1754 return 0;
1755}
1756
1757/* Backtrack one insn at a time. If idx is not at the top of recorded
1758 * history then previous instruction came from straight line execution.
1759 */
1760static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1761 u32 *history)
1762{
1763 u32 cnt = *history;
1764
1765 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1766 i = st->jmp_history[cnt - 1].prev_idx;
1767 (*history)--;
1768 } else {
1769 i--;
1770 }
1771 return i;
1772}
1773
1774/* For given verifier state backtrack_insn() is called from the last insn to
1775 * the first insn. Its purpose is to compute a bitmask of registers and
1776 * stack slots that needs precision in the parent verifier state.
1777 */
1778static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1779 u32 *reg_mask, u64 *stack_mask)
1780{
1781 const struct bpf_insn_cbs cbs = {
1782 .cb_print = verbose,
1783 .private_data = env,
1784 };
1785 struct bpf_insn *insn = env->prog->insnsi + idx;
1786 u8 class = BPF_CLASS(insn->code);
1787 u8 opcode = BPF_OP(insn->code);
1788 u8 mode = BPF_MODE(insn->code);
1789 u32 dreg = 1u << insn->dst_reg;
1790 u32 sreg = 1u << insn->src_reg;
1791 u32 spi;
1792
1793 if (insn->code == 0)
1794 return 0;
1795 if (env->log.level & BPF_LOG_LEVEL) {
1796 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1797 verbose(env, "%d: ", idx);
1798 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1799 }
1800
1801 if (class == BPF_ALU || class == BPF_ALU64) {
1802 if (!(*reg_mask & dreg))
1803 return 0;
1804 if (opcode == BPF_MOV) {
1805 if (BPF_SRC(insn->code) == BPF_X) {
1806 /* dreg = sreg
1807 * dreg needs precision after this insn
1808 * sreg needs precision before this insn
1809 */
1810 *reg_mask &= ~dreg;
1811 *reg_mask |= sreg;
1812 } else {
1813 /* dreg = K
1814 * dreg needs precision after this insn.
1815 * Corresponding register is already marked
1816 * as precise=true in this verifier state.
1817 * No further markings in parent are necessary
1818 */
1819 *reg_mask &= ~dreg;
1820 }
1821 } else {
1822 if (BPF_SRC(insn->code) == BPF_X) {
1823 /* dreg += sreg
1824 * both dreg and sreg need precision
1825 * before this insn
1826 */
1827 *reg_mask |= sreg;
1828 } /* else dreg += K
1829 * dreg still needs precision before this insn
1830 */
1831 }
1832 } else if (class == BPF_LDX) {
1833 if (!(*reg_mask & dreg))
1834 return 0;
1835 *reg_mask &= ~dreg;
1836
1837 /* scalars can only be spilled into stack w/o losing precision.
1838 * Load from any other memory can be zero extended.
1839 * The desire to keep that precision is already indicated
1840 * by 'precise' mark in corresponding register of this state.
1841 * No further tracking necessary.
1842 */
1843 if (insn->src_reg != BPF_REG_FP)
1844 return 0;
1845 if (BPF_SIZE(insn->code) != BPF_DW)
1846 return 0;
1847
1848 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1849 * that [fp - off] slot contains scalar that needs to be
1850 * tracked with precision
1851 */
1852 spi = (-insn->off - 1) / BPF_REG_SIZE;
1853 if (spi >= 64) {
1854 verbose(env, "BUG spi %d\n", spi);
1855 WARN_ONCE(1, "verifier backtracking bug");
1856 return -EFAULT;
1857 }
1858 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001859 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001860 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001861 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001862 * to access memory. It means backtracking
1863 * encountered a case of pointer subtraction.
1864 */
1865 return -ENOTSUPP;
1866 /* scalars can only be spilled into stack */
1867 if (insn->dst_reg != BPF_REG_FP)
1868 return 0;
1869 if (BPF_SIZE(insn->code) != BPF_DW)
1870 return 0;
1871 spi = (-insn->off - 1) / BPF_REG_SIZE;
1872 if (spi >= 64) {
1873 verbose(env, "BUG spi %d\n", spi);
1874 WARN_ONCE(1, "verifier backtracking bug");
1875 return -EFAULT;
1876 }
1877 if (!(*stack_mask & (1ull << spi)))
1878 return 0;
1879 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001880 if (class == BPF_STX)
1881 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001882 } else if (class == BPF_JMP || class == BPF_JMP32) {
1883 if (opcode == BPF_CALL) {
1884 if (insn->src_reg == BPF_PSEUDO_CALL)
1885 return -ENOTSUPP;
1886 /* regular helper call sets R0 */
1887 *reg_mask &= ~1;
1888 if (*reg_mask & 0x3f) {
1889 /* if backtracing was looking for registers R1-R5
1890 * they should have been found already.
1891 */
1892 verbose(env, "BUG regs %x\n", *reg_mask);
1893 WARN_ONCE(1, "verifier backtracking bug");
1894 return -EFAULT;
1895 }
1896 } else if (opcode == BPF_EXIT) {
1897 return -ENOTSUPP;
1898 }
1899 } else if (class == BPF_LD) {
1900 if (!(*reg_mask & dreg))
1901 return 0;
1902 *reg_mask &= ~dreg;
1903 /* It's ld_imm64 or ld_abs or ld_ind.
1904 * For ld_imm64 no further tracking of precision
1905 * into parent is necessary
1906 */
1907 if (mode == BPF_IND || mode == BPF_ABS)
1908 /* to be analyzed */
1909 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001910 }
1911 return 0;
1912}
1913
1914/* the scalar precision tracking algorithm:
1915 * . at the start all registers have precise=false.
1916 * . scalar ranges are tracked as normal through alu and jmp insns.
1917 * . once precise value of the scalar register is used in:
1918 * . ptr + scalar alu
1919 * . if (scalar cond K|scalar)
1920 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1921 * backtrack through the verifier states and mark all registers and
1922 * stack slots with spilled constants that these scalar regisers
1923 * should be precise.
1924 * . during state pruning two registers (or spilled stack slots)
1925 * are equivalent if both are not precise.
1926 *
1927 * Note the verifier cannot simply walk register parentage chain,
1928 * since many different registers and stack slots could have been
1929 * used to compute single precise scalar.
1930 *
1931 * The approach of starting with precise=true for all registers and then
1932 * backtrack to mark a register as not precise when the verifier detects
1933 * that program doesn't care about specific value (e.g., when helper
1934 * takes register as ARG_ANYTHING parameter) is not safe.
1935 *
1936 * It's ok to walk single parentage chain of the verifier states.
1937 * It's possible that this backtracking will go all the way till 1st insn.
1938 * All other branches will be explored for needing precision later.
1939 *
1940 * The backtracking needs to deal with cases like:
1941 * 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)
1942 * r9 -= r8
1943 * r5 = r9
1944 * if r5 > 0x79f goto pc+7
1945 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1946 * r5 += 1
1947 * ...
1948 * call bpf_perf_event_output#25
1949 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1950 *
1951 * and this case:
1952 * r6 = 1
1953 * call foo // uses callee's r6 inside to compute r0
1954 * r0 += r6
1955 * if r0 == 0 goto
1956 *
1957 * to track above reg_mask/stack_mask needs to be independent for each frame.
1958 *
1959 * Also if parent's curframe > frame where backtracking started,
1960 * the verifier need to mark registers in both frames, otherwise callees
1961 * may incorrectly prune callers. This is similar to
1962 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1963 *
1964 * For now backtracking falls back into conservative marking.
1965 */
1966static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1967 struct bpf_verifier_state *st)
1968{
1969 struct bpf_func_state *func;
1970 struct bpf_reg_state *reg;
1971 int i, j;
1972
1973 /* big hammer: mark all scalars precise in this path.
1974 * pop_stack may still get !precise scalars.
1975 */
1976 for (; st; st = st->parent)
1977 for (i = 0; i <= st->curframe; i++) {
1978 func = st->frame[i];
1979 for (j = 0; j < BPF_REG_FP; j++) {
1980 reg = &func->regs[j];
1981 if (reg->type != SCALAR_VALUE)
1982 continue;
1983 reg->precise = true;
1984 }
1985 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1986 if (func->stack[j].slot_type[0] != STACK_SPILL)
1987 continue;
1988 reg = &func->stack[j].spilled_ptr;
1989 if (reg->type != SCALAR_VALUE)
1990 continue;
1991 reg->precise = true;
1992 }
1993 }
1994}
1995
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001996static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1997 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001998{
1999 struct bpf_verifier_state *st = env->cur_state;
2000 int first_idx = st->first_insn_idx;
2001 int last_idx = env->insn_idx;
2002 struct bpf_func_state *func;
2003 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002004 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2005 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002006 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002007 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002008 int i, err;
2009
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002010 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002011 return 0;
2012
2013 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002014 if (regno >= 0) {
2015 reg = &func->regs[regno];
2016 if (reg->type != SCALAR_VALUE) {
2017 WARN_ONCE(1, "backtracing misuse");
2018 return -EFAULT;
2019 }
2020 if (!reg->precise)
2021 new_marks = true;
2022 else
2023 reg_mask = 0;
2024 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002025 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002026
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002027 while (spi >= 0) {
2028 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2029 stack_mask = 0;
2030 break;
2031 }
2032 reg = &func->stack[spi].spilled_ptr;
2033 if (reg->type != SCALAR_VALUE) {
2034 stack_mask = 0;
2035 break;
2036 }
2037 if (!reg->precise)
2038 new_marks = true;
2039 else
2040 stack_mask = 0;
2041 reg->precise = true;
2042 break;
2043 }
2044
2045 if (!new_marks)
2046 return 0;
2047 if (!reg_mask && !stack_mask)
2048 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002049 for (;;) {
2050 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002051 u32 history = st->jmp_history_cnt;
2052
2053 if (env->log.level & BPF_LOG_LEVEL)
2054 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2055 for (i = last_idx;;) {
2056 if (skip_first) {
2057 err = 0;
2058 skip_first = false;
2059 } else {
2060 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2061 }
2062 if (err == -ENOTSUPP) {
2063 mark_all_scalars_precise(env, st);
2064 return 0;
2065 } else if (err) {
2066 return err;
2067 }
2068 if (!reg_mask && !stack_mask)
2069 /* Found assignment(s) into tracked register in this state.
2070 * Since this state is already marked, just return.
2071 * Nothing to be tracked further in the parent state.
2072 */
2073 return 0;
2074 if (i == first_idx)
2075 break;
2076 i = get_prev_insn_idx(st, i, &history);
2077 if (i >= env->prog->len) {
2078 /* This can happen if backtracking reached insn 0
2079 * and there are still reg_mask or stack_mask
2080 * to backtrack.
2081 * It means the backtracking missed the spot where
2082 * particular register was initialized with a constant.
2083 */
2084 verbose(env, "BUG backtracking idx %d\n", i);
2085 WARN_ONCE(1, "verifier backtracking bug");
2086 return -EFAULT;
2087 }
2088 }
2089 st = st->parent;
2090 if (!st)
2091 break;
2092
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002093 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002094 func = st->frame[st->curframe];
2095 bitmap_from_u64(mask, reg_mask);
2096 for_each_set_bit(i, mask, 32) {
2097 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002098 if (reg->type != SCALAR_VALUE) {
2099 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002100 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002101 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002102 if (!reg->precise)
2103 new_marks = true;
2104 reg->precise = true;
2105 }
2106
2107 bitmap_from_u64(mask, stack_mask);
2108 for_each_set_bit(i, mask, 64) {
2109 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002110 /* the sequence of instructions:
2111 * 2: (bf) r3 = r10
2112 * 3: (7b) *(u64 *)(r3 -8) = r0
2113 * 4: (79) r4 = *(u64 *)(r10 -8)
2114 * doesn't contain jmps. It's backtracked
2115 * as a single block.
2116 * During backtracking insn 3 is not recognized as
2117 * stack access, so at the end of backtracking
2118 * stack slot fp-8 is still marked in stack_mask.
2119 * However the parent state may not have accessed
2120 * fp-8 and it's "unallocated" stack space.
2121 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002122 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002123 mark_all_scalars_precise(env, st);
2124 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002125 }
2126
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002127 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2128 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002129 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002130 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002131 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002132 if (reg->type != SCALAR_VALUE) {
2133 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002134 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002135 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002136 if (!reg->precise)
2137 new_marks = true;
2138 reg->precise = true;
2139 }
2140 if (env->log.level & BPF_LOG_LEVEL) {
2141 print_verifier_state(env, func);
2142 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2143 new_marks ? "didn't have" : "already had",
2144 reg_mask, stack_mask);
2145 }
2146
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002147 if (!reg_mask && !stack_mask)
2148 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002149 if (!new_marks)
2150 break;
2151
2152 last_idx = st->last_insn_idx;
2153 first_idx = st->first_insn_idx;
2154 }
2155 return 0;
2156}
2157
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002158static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2159{
2160 return __mark_chain_precision(env, regno, -1);
2161}
2162
2163static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2164{
2165 return __mark_chain_precision(env, -1, spi);
2166}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002167
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002168static bool is_spillable_regtype(enum bpf_reg_type type)
2169{
2170 switch (type) {
2171 case PTR_TO_MAP_VALUE:
2172 case PTR_TO_MAP_VALUE_OR_NULL:
2173 case PTR_TO_STACK:
2174 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002175 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002176 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002177 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002178 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002179 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002180 case PTR_TO_SOCKET:
2181 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002182 case PTR_TO_SOCK_COMMON:
2183 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002184 case PTR_TO_TCP_SOCK:
2185 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002186 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002187 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002188 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002189 case PTR_TO_RDONLY_BUF:
2190 case PTR_TO_RDONLY_BUF_OR_NULL:
2191 case PTR_TO_RDWR_BUF:
2192 case PTR_TO_RDWR_BUF_OR_NULL:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002193 return true;
2194 default:
2195 return false;
2196 }
2197}
2198
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002199/* Does this register contain a constant zero? */
2200static bool register_is_null(struct bpf_reg_state *reg)
2201{
2202 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2203}
2204
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002205static bool register_is_const(struct bpf_reg_state *reg)
2206{
2207 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2208}
2209
Jann Horn6e7e63c2020-04-17 02:00:06 +02002210static bool __is_pointer_value(bool allow_ptr_leaks,
2211 const struct bpf_reg_state *reg)
2212{
2213 if (allow_ptr_leaks)
2214 return false;
2215
2216 return reg->type != SCALAR_VALUE;
2217}
2218
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002219static void save_register_state(struct bpf_func_state *state,
2220 int spi, struct bpf_reg_state *reg)
2221{
2222 int i;
2223
2224 state->stack[spi].spilled_ptr = *reg;
2225 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2226
2227 for (i = 0; i < BPF_REG_SIZE; i++)
2228 state->stack[spi].slot_type[i] = STACK_SPILL;
2229}
2230
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002231/* check_stack_read/write functions track spill/fill of registers,
2232 * stack boundary and alignment are checked in check_mem_access()
2233 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002234static int check_stack_write(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002235 struct bpf_func_state *state, /* func where register points to */
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002236 int off, int size, int value_regno, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002237{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002238 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002239 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002240 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002241 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002242
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002243 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07002244 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002245 if (err)
2246 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002247 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2248 * so it's aligned access and [off, off + size) are within stack limits
2249 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002250 if (!env->allow_ptr_leaks &&
2251 state->stack[spi].slot_type[0] == STACK_SPILL &&
2252 size != BPF_REG_SIZE) {
2253 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2254 return -EACCES;
2255 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002256
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002257 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002258 if (value_regno >= 0)
2259 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002260
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002261 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002262 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002263 if (dst_reg != BPF_REG_FP) {
2264 /* The backtracking logic can only recognize explicit
2265 * stack slot address like [fp - 8]. Other spill of
2266 * scalar via different register has to be conervative.
2267 * Backtrack from here and mark all registers as precise
2268 * that contributed into 'reg' being a constant.
2269 */
2270 err = mark_chain_precision(env, value_regno);
2271 if (err)
2272 return err;
2273 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002274 save_register_state(state, spi, reg);
2275 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002276 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002277 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002278 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002279 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002280 return -EACCES;
2281 }
2282
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002283 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002284 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2285 return -EINVAL;
2286 }
2287
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002288 if (!env->bypass_spec_v4) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002289 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002290
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002291 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2292 register_is_const(&state->stack[spi].spilled_ptr))
2293 sanitize = true;
2294 for (i = 0; i < BPF_REG_SIZE; i++)
2295 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2296 sanitize = true;
2297 break;
2298 }
2299 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002300 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2301 int soff = (-spi - 1) * BPF_REG_SIZE;
2302
2303 /* detected reuse of integer stack slot with a pointer
2304 * which means either llvm is reusing stack slot or
2305 * an attacker is trying to exploit CVE-2018-3639
2306 * (speculative store bypass)
2307 * Have to sanitize that slot with preemptive
2308 * store of zero.
2309 */
2310 if (*poff && *poff != soff) {
2311 /* disallow programs where single insn stores
2312 * into two different stack slots, since verifier
2313 * cannot sanitize them
2314 */
2315 verbose(env,
2316 "insn %d cannot access two stack slots fp%d and fp%d",
2317 insn_idx, *poff, soff);
2318 return -EINVAL;
2319 }
2320 *poff = soff;
2321 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002322 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002323 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002324 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002325 u8 type = STACK_MISC;
2326
Edward Cree679c7822018-08-22 20:02:19 +01002327 /* regular write of data into stack destroys any spilled ptr */
2328 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002329 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2330 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2331 for (i = 0; i < BPF_REG_SIZE; i++)
2332 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002333
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002334 /* only mark the slot as written if all 8 bytes were written
2335 * otherwise read propagation may incorrectly stop too soon
2336 * when stack slots are partially written.
2337 * This heuristic means that read propagation will be
2338 * conservative, since it will add reg_live_read marks
2339 * to stack slots all the way to first state when programs
2340 * writes+reads less than 8 bytes
2341 */
2342 if (size == BPF_REG_SIZE)
2343 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2344
2345 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002346 if (reg && register_is_null(reg)) {
2347 /* backtracking doesn't work for STACK_ZERO yet. */
2348 err = mark_chain_precision(env, value_regno);
2349 if (err)
2350 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002351 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002352 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002353
Jiong Wang0bae2d42018-12-15 03:34:40 -05002354 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002355 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002356 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002357 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002358 }
2359 return 0;
2360}
2361
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002362static int check_stack_read(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002363 struct bpf_func_state *reg_state /* func where register points to */,
2364 int off, int size, int value_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002365{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002366 struct bpf_verifier_state *vstate = env->cur_state;
2367 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002368 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002369 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002370 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002371
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002372 if (reg_state->allocated_stack <= slot) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002373 verbose(env, "invalid read from stack off %d+0 size %d\n",
2374 off, size);
2375 return -EACCES;
2376 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002377 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002378 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002379
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002380 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002381 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002382 if (reg->type != SCALAR_VALUE) {
2383 verbose_linfo(env, env->insn_idx, "; ");
2384 verbose(env, "invalid size of register fill\n");
2385 return -EACCES;
2386 }
2387 if (value_regno >= 0) {
2388 mark_reg_unknown(env, state->regs, value_regno);
2389 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2390 }
2391 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2392 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002393 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002394 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002395 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002396 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002397 return -EACCES;
2398 }
2399 }
2400
Edward Creedc503a82017-08-15 20:34:35 +01002401 if (value_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002402 /* restore register state from stack */
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002403 state->regs[value_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002404 /* mark reg as written since spilled pointer state likely
2405 * has its liveness marks cleared by is_state_visited()
2406 * which resets stack/reg liveness for state transitions
2407 */
2408 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02002409 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2410 /* If value_regno==-1, the caller is asking us whether
2411 * it is acceptable to use this value as a SCALAR_VALUE
2412 * (e.g. for XADD).
2413 * We must not allow unprivileged callers to do that
2414 * with spilled pointers.
2415 */
2416 verbose(env, "leaking pointer from stack off %d\n",
2417 off);
2418 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01002419 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002420 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002421 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002422 int zeros = 0;
2423
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002424 for (i = 0; i < size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002425 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2426 continue;
2427 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2428 zeros++;
2429 continue;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002430 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002431 verbose(env, "invalid read from stack off %d+%d size %d\n",
2432 off, i, size);
2433 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002434 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002435 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002436 if (value_regno >= 0) {
2437 if (zeros == size) {
2438 /* any size read into register is zero extended,
2439 * so the whole register == const_zero
2440 */
2441 __mark_reg_const_zero(&state->regs[value_regno]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002442 /* backtracking doesn't support STACK_ZERO yet,
2443 * so mark it precise here, so that later
2444 * backtracking can stop here.
2445 * Backtracking may not need this if this register
2446 * doesn't participate in pointer adjustment.
2447 * Forward propagation of precise flag is not
2448 * necessary either. This mark is only to stop
2449 * backtracking. Any register that contributed
2450 * to const 0 was marked precise before spill.
2451 */
2452 state->regs[value_regno].precise = true;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002453 } else {
2454 /* have read misc data from the stack */
2455 mark_reg_unknown(env, state->regs, value_regno);
2456 }
2457 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2458 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002459 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002460 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002461}
2462
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002463static int check_stack_access(struct bpf_verifier_env *env,
2464 const struct bpf_reg_state *reg,
2465 int off, int size)
2466{
2467 /* Stack accesses must be at a fixed offset, so that we
2468 * can determine what type of data were returned. See
2469 * check_stack_read().
2470 */
2471 if (!tnum_is_const(reg->var_off)) {
2472 char tn_buf[48];
2473
2474 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrey Ignatov1fbd20f2019-04-03 23:22:43 -07002475 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002476 tn_buf, off, size);
2477 return -EACCES;
2478 }
2479
2480 if (off >= 0 || off < -MAX_BPF_STACK) {
2481 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2482 return -EACCES;
2483 }
2484
2485 return 0;
2486}
2487
Daniel Borkmann591fe982019-04-09 23:20:05 +02002488static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2489 int off, int size, enum bpf_access_type type)
2490{
2491 struct bpf_reg_state *regs = cur_regs(env);
2492 struct bpf_map *map = regs[regno].map_ptr;
2493 u32 cap = bpf_map_flags_to_cap(map);
2494
2495 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2496 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2497 map->value_size, off, size);
2498 return -EACCES;
2499 }
2500
2501 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2502 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2503 map->value_size, off, size);
2504 return -EACCES;
2505 }
2506
2507 return 0;
2508}
2509
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002510/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2511static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2512 int off, int size, u32 mem_size,
2513 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002514{
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002515 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2516 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002517
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002518 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2519 return 0;
2520
2521 reg = &cur_regs(env)[regno];
2522 switch (reg->type) {
2523 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002524 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002525 mem_size, off, size);
2526 break;
2527 case PTR_TO_PACKET:
2528 case PTR_TO_PACKET_META:
2529 case PTR_TO_PACKET_END:
2530 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2531 off, size, regno, reg->id, off, mem_size);
2532 break;
2533 case PTR_TO_MEM:
2534 default:
2535 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2536 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002537 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002538
2539 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002540}
2541
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002542/* check read/write into a memory region with possible variable offset */
2543static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2544 int off, int size, u32 mem_size,
2545 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002546{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002547 struct bpf_verifier_state *vstate = env->cur_state;
2548 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002549 struct bpf_reg_state *reg = &state->regs[regno];
2550 int err;
2551
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002552 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01002553 * need to try adding each of min_value and max_value to off
2554 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002555 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002556 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002557 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002558
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002559 /* The minimum value is only important with signed
2560 * comparisons where we can't assume the floor of a
2561 * value is 0. If we are using signed variables for our
2562 * index'es we need to make sure that whatever we use
2563 * will have a set floor within our range.
2564 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002565 if (reg->smin_value < 0 &&
2566 (reg->smin_value == S64_MIN ||
2567 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2568 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002569 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 -08002570 regno);
2571 return -EACCES;
2572 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002573 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2574 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002575 if (err) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002576 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002577 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002578 return err;
2579 }
2580
Edward Creeb03c9f92017-08-07 15:26:36 +01002581 /* If we haven't set a max value then we need to bail since we can't be
2582 * sure we won't do bad things.
2583 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002584 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002585 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002586 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002587 regno);
2588 return -EACCES;
2589 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002590 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2591 mem_size, zero_size_allowed);
2592 if (err) {
2593 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002594 regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002595 return err;
2596 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002597
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002598 return 0;
2599}
2600
2601/* check read/write into a map element with possible variable offset */
2602static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2603 int off, int size, bool zero_size_allowed)
2604{
2605 struct bpf_verifier_state *vstate = env->cur_state;
2606 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2607 struct bpf_reg_state *reg = &state->regs[regno];
2608 struct bpf_map *map = reg->map_ptr;
2609 int err;
2610
2611 err = check_mem_region_access(env, regno, off, size, map->value_size,
2612 zero_size_allowed);
2613 if (err)
2614 return err;
2615
2616 if (map_value_has_spin_lock(map)) {
2617 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002618
2619 /* if any part of struct bpf_spin_lock can be touched by
2620 * load/store reject this program.
2621 * To check that [x1, x2) overlaps with [y1, y2)
2622 * it is sufficient to check x1 < y2 && y1 < x2.
2623 */
2624 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2625 lock < reg->umax_value + off + size) {
2626 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2627 return -EACCES;
2628 }
2629 }
Edward Creef1174f72017-08-07 15:26:19 +01002630 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002631}
2632
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002633#define MAX_PACKET_OFF 0xffff
2634
Udip Pant7e407812020-08-25 16:20:00 -07002635static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2636{
2637 return prog->aux->linked_prog ? prog->aux->linked_prog->type
2638 : prog->type;
2639}
2640
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01002641static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002642 const struct bpf_call_arg_meta *meta,
2643 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002644{
Udip Pant7e407812020-08-25 16:20:00 -07002645 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2646
2647 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002648 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002649 case BPF_PROG_TYPE_LWT_IN:
2650 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01002651 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07002652 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002653 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02002654 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002655 if (t == BPF_WRITE)
2656 return false;
Alexander Alemayhu7e57fbb2017-02-14 00:02:35 +01002657 /* fallthrough */
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002658
2659 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002660 case BPF_PROG_TYPE_SCHED_CLS:
2661 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002662 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002663 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07002664 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07002665 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002666 if (meta)
2667 return meta->pkt_access;
2668
2669 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002670 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07002671
2672 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2673 if (t == BPF_WRITE)
2674 env->seen_direct_write = true;
2675
2676 return true;
2677
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002678 default:
2679 return false;
2680 }
2681}
2682
Edward Creef1174f72017-08-07 15:26:19 +01002683static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002684 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01002685{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002686 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01002687 struct bpf_reg_state *reg = &regs[regno];
2688 int err;
2689
2690 /* We may have added a variable offset to the packet pointer; but any
2691 * reg->range we have comes after that. We are only checking the fixed
2692 * offset.
2693 */
2694
2695 /* We don't allow negative numbers, because we aren't tracking enough
2696 * detail to prove they're safe.
2697 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002698 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002699 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 +01002700 regno);
2701 return -EACCES;
2702 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002703 err = __check_mem_access(env, regno, off, size, reg->range,
2704 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01002705 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002706 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01002707 return err;
2708 }
Jiong Wange6478152018-11-08 04:08:42 -05002709
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002710 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05002711 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2712 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002713 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05002714 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2715 */
2716 env->prog->aux->max_pkt_offset =
2717 max_t(u32, env->prog->aux->max_pkt_offset,
2718 off + reg->umax_value + size - 1);
2719
Edward Creef1174f72017-08-07 15:26:19 +01002720 return err;
2721}
2722
2723/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07002724static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002725 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2726 u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002727{
Daniel Borkmannf96da092017-07-02 02:13:27 +02002728 struct bpf_insn_access_aux info = {
2729 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002730 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02002731 };
Yonghong Song31fd8582017-06-13 15:52:13 -07002732
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07002733 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07002734 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02002735 /* A non zero info.ctx_field_size indicates that this field is a
2736 * candidate for later verifier transformation to load the whole
2737 * field and then apply a mask when accessed with a narrower
2738 * access than actual ctx access size. A zero info.ctx_field_size
2739 * will only allow for whole field access and rejects any other
2740 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07002741 */
Yonghong Song23994632017-06-22 15:07:39 -07002742 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07002743
Yonghong Songb121b342020-05-09 10:59:12 -07002744 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002745 *btf_id = info.btf_id;
2746 else
2747 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002748 /* remember the offset of last byte accessed in ctx */
2749 if (env->prog->aux->max_ctx_offset < off + size)
2750 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002751 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002752 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002753
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002754 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002755 return -EACCES;
2756}
2757
Petar Penkovd58e4682018-09-14 07:46:18 -07002758static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2759 int size)
2760{
2761 if (size < 0 || off < 0 ||
2762 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2763 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2764 off, size);
2765 return -EACCES;
2766 }
2767 return 0;
2768}
2769
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002770static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2771 u32 regno, int off, int size,
2772 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07002773{
2774 struct bpf_reg_state *regs = cur_regs(env);
2775 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002776 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002777 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07002778
2779 if (reg->smin_value < 0) {
2780 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2781 regno);
2782 return -EACCES;
2783 }
2784
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002785 switch (reg->type) {
2786 case PTR_TO_SOCK_COMMON:
2787 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2788 break;
2789 case PTR_TO_SOCKET:
2790 valid = bpf_sock_is_valid_access(off, size, t, &info);
2791 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002792 case PTR_TO_TCP_SOCK:
2793 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2794 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002795 case PTR_TO_XDP_SOCK:
2796 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2797 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002798 default:
2799 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07002800 }
2801
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002802
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002803 if (valid) {
2804 env->insn_aux_data[insn_idx].ctx_field_size =
2805 info.ctx_field_size;
2806 return 0;
2807 }
2808
2809 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2810 regno, reg_type_str[reg->type], off, size);
2811
2812 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07002813}
2814
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002815static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2816{
2817 return cur_regs(env) + regno;
2818}
2819
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002820static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2821{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002822 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002823}
2824
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002825static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2826{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002827 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002828
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002829 return reg->type == PTR_TO_CTX;
2830}
2831
2832static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2833{
2834 const struct bpf_reg_state *reg = reg_state(env, regno);
2835
2836 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002837}
2838
Daniel Borkmannca369602018-02-23 22:29:05 +01002839static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2840{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002841 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01002842
2843 return type_is_pkt_pointer(reg->type);
2844}
2845
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02002846static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2847{
2848 const struct bpf_reg_state *reg = reg_state(env, regno);
2849
2850 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2851 return reg->type == PTR_TO_FLOW_KEYS;
2852}
2853
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002854static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2855 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07002856 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002857{
Edward Creef1174f72017-08-07 15:26:19 +01002858 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07002859 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07002860
2861 /* Byte size accesses are always allowed. */
2862 if (!strict || size == 1)
2863 return 0;
2864
David S. Millere4eda882017-05-22 12:27:07 -04002865 /* For platforms that do not have a Kconfig enabling
2866 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2867 * NET_IP_ALIGN is universally set to '2'. And on platforms
2868 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2869 * to this code only in strict mode where we want to emulate
2870 * the NET_IP_ALIGN==2 checking. Therefore use an
2871 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07002872 */
David S. Millere4eda882017-05-22 12:27:07 -04002873 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01002874
2875 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2876 if (!tnum_is_aligned(reg_off, size)) {
2877 char tn_buf[48];
2878
2879 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002880 verbose(env,
2881 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002882 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002883 return -EACCES;
2884 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002885
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002886 return 0;
2887}
2888
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002889static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2890 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01002891 const char *pointer_desc,
2892 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002893{
Edward Creef1174f72017-08-07 15:26:19 +01002894 struct tnum reg_off;
2895
2896 /* Byte size accesses are always allowed. */
2897 if (!strict || size == 1)
2898 return 0;
2899
2900 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2901 if (!tnum_is_aligned(reg_off, size)) {
2902 char tn_buf[48];
2903
2904 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002905 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002906 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002907 return -EACCES;
2908 }
2909
2910 return 0;
2911}
2912
David S. Millere07b98d2017-05-10 11:38:07 -07002913static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01002914 const struct bpf_reg_state *reg, int off,
2915 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002916{
Daniel Borkmannca369602018-02-23 22:29:05 +01002917 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01002918 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07002919
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002920 switch (reg->type) {
2921 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002922 case PTR_TO_PACKET_META:
2923 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2924 * right in front, treat it the very same way.
2925 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002926 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07002927 case PTR_TO_FLOW_KEYS:
2928 pointer_desc = "flow keys ";
2929 break;
Edward Creef1174f72017-08-07 15:26:19 +01002930 case PTR_TO_MAP_VALUE:
2931 pointer_desc = "value ";
2932 break;
2933 case PTR_TO_CTX:
2934 pointer_desc = "context ";
2935 break;
2936 case PTR_TO_STACK:
2937 pointer_desc = "stack ";
Jann Horna5ec6ae2017-12-18 20:11:58 -08002938 /* The stack spill tracking logic in check_stack_write()
2939 * and check_stack_read() relies on stack accesses being
2940 * aligned.
2941 */
2942 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01002943 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07002944 case PTR_TO_SOCKET:
2945 pointer_desc = "sock ";
2946 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002947 case PTR_TO_SOCK_COMMON:
2948 pointer_desc = "sock_common ";
2949 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002950 case PTR_TO_TCP_SOCK:
2951 pointer_desc = "tcp_sock ";
2952 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002953 case PTR_TO_XDP_SOCK:
2954 pointer_desc = "xdp_sock ";
2955 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002956 default:
Edward Creef1174f72017-08-07 15:26:19 +01002957 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002958 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002959 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2960 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002961}
2962
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002963static int update_stack_depth(struct bpf_verifier_env *env,
2964 const struct bpf_func_state *func,
2965 int off)
2966{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002967 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002968
2969 if (stack >= -off)
2970 return 0;
2971
2972 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04002973 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002974 return 0;
2975}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002976
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002977/* starting from main bpf function walk all instructions of the function
2978 * and recursively walk all callees that given function can call.
2979 * Ignore jump and exit insns.
2980 * Since recursion is prevented by check_cfg() this algorithm
2981 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2982 */
2983static int check_max_stack_depth(struct bpf_verifier_env *env)
2984{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002985 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2986 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002987 struct bpf_insn *insn = env->prog->insnsi;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02002988 bool tail_call_reachable = false;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002989 int ret_insn[MAX_CALL_FRAMES];
2990 int ret_prog[MAX_CALL_FRAMES];
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02002991 int j;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002992
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002993process_func:
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02002994 /* protect against potential stack overflow that might happen when
2995 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
2996 * depth for such case down to 256 so that the worst case scenario
2997 * would result in 8k stack size (32 which is tailcall limit * 256 =
2998 * 8k).
2999 *
3000 * To get the idea what might happen, see an example:
3001 * func1 -> sub rsp, 128
3002 * subfunc1 -> sub rsp, 256
3003 * tailcall1 -> add rsp, 256
3004 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3005 * subfunc2 -> sub rsp, 64
3006 * subfunc22 -> sub rsp, 128
3007 * tailcall2 -> add rsp, 128
3008 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3009 *
3010 * tailcall will unwind the current stack frame but it will not get rid
3011 * of caller's stack as shown on the example above.
3012 */
3013 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3014 verbose(env,
3015 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3016 depth);
3017 return -EACCES;
3018 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003019 /* round up to 32-bytes, since this is granularity
3020 * of interpreter stack size
3021 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003022 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003023 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003024 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003025 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003026 return -EACCES;
3027 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003028continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04003029 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003030 for (; i < subprog_end; i++) {
3031 if (insn[i].code != (BPF_JMP | BPF_CALL))
3032 continue;
3033 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3034 continue;
3035 /* remember insn and function to return to */
3036 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003037 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003038
3039 /* find the callee */
3040 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003041 idx = find_subprog(env, i);
3042 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003043 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3044 i);
3045 return -EFAULT;
3046 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003047
3048 if (subprog[idx].has_tail_call)
3049 tail_call_reachable = true;
3050
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003051 frame++;
3052 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003053 verbose(env, "the call stack of %d frames is too deep !\n",
3054 frame);
3055 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003056 }
3057 goto process_func;
3058 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003059 /* if tail call got detected across bpf2bpf calls then mark each of the
3060 * currently present subprog frames as tail call reachable subprogs;
3061 * this info will be utilized by JIT so that we will be preserving the
3062 * tail call counter throughout bpf2bpf calls combined with tailcalls
3063 */
3064 if (tail_call_reachable)
3065 for (j = 0; j < frame; j++)
3066 subprog[ret_prog[j]].tail_call_reachable = true;
3067
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003068 /* end of for() loop means the last insn of the 'subprog'
3069 * was reached. Doesn't matter whether it was JA or EXIT
3070 */
3071 if (frame == 0)
3072 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003073 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003074 frame--;
3075 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003076 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003077 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003078}
3079
David S. Miller19d28fb2018-01-11 21:27:54 -05003080#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003081static int get_callee_stack_depth(struct bpf_verifier_env *env,
3082 const struct bpf_insn *insn, int idx)
3083{
3084 int start = idx + insn->imm + 1, subprog;
3085
3086 subprog = find_subprog(env, start);
3087 if (subprog < 0) {
3088 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3089 start);
3090 return -EFAULT;
3091 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04003092 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003093}
David S. Miller19d28fb2018-01-11 21:27:54 -05003094#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003095
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003096int check_ctx_reg(struct bpf_verifier_env *env,
3097 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02003098{
3099 /* Access to ctx or passing it to a helper is only allowed in
3100 * its original, unmodified form.
3101 */
3102
3103 if (reg->off) {
3104 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3105 regno, reg->off);
3106 return -EACCES;
3107 }
3108
3109 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3110 char tn_buf[48];
3111
3112 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3113 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3114 return -EACCES;
3115 }
3116
3117 return 0;
3118}
3119
Yonghong Songafbf21d2020-07-23 11:41:11 -07003120static int __check_buffer_access(struct bpf_verifier_env *env,
3121 const char *buf_info,
3122 const struct bpf_reg_state *reg,
3123 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07003124{
3125 if (off < 0) {
3126 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003127 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003128 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07003129 return -EACCES;
3130 }
3131 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3132 char tn_buf[48];
3133
3134 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3135 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003136 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07003137 regno, off, tn_buf);
3138 return -EACCES;
3139 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07003140
3141 return 0;
3142}
3143
3144static int check_tp_buffer_access(struct bpf_verifier_env *env,
3145 const struct bpf_reg_state *reg,
3146 int regno, int off, int size)
3147{
3148 int err;
3149
3150 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3151 if (err)
3152 return err;
3153
Matt Mullins9df1c282019-04-26 11:49:47 -07003154 if (off + size > env->prog->aux->max_tp_access)
3155 env->prog->aux->max_tp_access = off + size;
3156
3157 return 0;
3158}
3159
Yonghong Songafbf21d2020-07-23 11:41:11 -07003160static int check_buffer_access(struct bpf_verifier_env *env,
3161 const struct bpf_reg_state *reg,
3162 int regno, int off, int size,
3163 bool zero_size_allowed,
3164 const char *buf_info,
3165 u32 *max_access)
3166{
3167 int err;
3168
3169 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3170 if (err)
3171 return err;
3172
3173 if (off + size > *max_access)
3174 *max_access = off + size;
3175
3176 return 0;
3177}
3178
John Fastabend3f50f132020-03-30 14:36:39 -07003179/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3180static void zext_32_to_64(struct bpf_reg_state *reg)
3181{
3182 reg->var_off = tnum_subreg(reg->var_off);
3183 __reg_assign_32_into_64(reg);
3184}
Matt Mullins9df1c282019-04-26 11:49:47 -07003185
Jann Horn0c17d1d2017-12-18 20:11:55 -08003186/* truncate register to smaller size (in bytes)
3187 * must be called with size < BPF_REG_SIZE
3188 */
3189static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3190{
3191 u64 mask;
3192
3193 /* clear high bits in bit representation */
3194 reg->var_off = tnum_cast(reg->var_off, size);
3195
3196 /* fix arithmetic bounds */
3197 mask = ((u64)1 << (size * 8)) - 1;
3198 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3199 reg->umin_value &= mask;
3200 reg->umax_value &= mask;
3201 } else {
3202 reg->umin_value = 0;
3203 reg->umax_value = mask;
3204 }
3205 reg->smin_value = reg->umin_value;
3206 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07003207
3208 /* If size is smaller than 32bit register the 32bit register
3209 * values are also truncated so we push 64-bit bounds into
3210 * 32-bit bounds. Above were truncated < 32-bits already.
3211 */
3212 if (size >= 4)
3213 return;
3214 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08003215}
3216
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003217static bool bpf_map_is_rdonly(const struct bpf_map *map)
3218{
3219 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3220}
3221
3222static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3223{
3224 void *ptr;
3225 u64 addr;
3226 int err;
3227
3228 err = map->ops->map_direct_value_addr(map, &addr, off);
3229 if (err)
3230 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07003231 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003232
3233 switch (size) {
3234 case sizeof(u8):
3235 *val = (u64)*(u8 *)ptr;
3236 break;
3237 case sizeof(u16):
3238 *val = (u64)*(u16 *)ptr;
3239 break;
3240 case sizeof(u32):
3241 *val = (u64)*(u32 *)ptr;
3242 break;
3243 case sizeof(u64):
3244 *val = *(u64 *)ptr;
3245 break;
3246 default:
3247 return -EINVAL;
3248 }
3249 return 0;
3250}
3251
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003252static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3253 struct bpf_reg_state *regs,
3254 int regno, int off, int size,
3255 enum bpf_access_type atype,
3256 int value_regno)
3257{
3258 struct bpf_reg_state *reg = regs + regno;
3259 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3260 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3261 u32 btf_id;
3262 int ret;
3263
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003264 if (off < 0) {
3265 verbose(env,
3266 "R%d is ptr_%s invalid negative access: off=%d\n",
3267 regno, tname, off);
3268 return -EACCES;
3269 }
3270 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3271 char tn_buf[48];
3272
3273 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3274 verbose(env,
3275 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3276 regno, tname, off, tn_buf);
3277 return -EACCES;
3278 }
3279
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003280 if (env->ops->btf_struct_access) {
3281 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3282 atype, &btf_id);
3283 } else {
3284 if (atype != BPF_READ) {
3285 verbose(env, "only read is supported\n");
3286 return -EACCES;
3287 }
3288
3289 ret = btf_struct_access(&env->log, t, off, size, atype,
3290 &btf_id);
3291 }
3292
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003293 if (ret < 0)
3294 return ret;
3295
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003296 if (atype == BPF_READ && value_regno >= 0)
3297 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003298
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003299 return 0;
3300}
3301
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003302static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3303 struct bpf_reg_state *regs,
3304 int regno, int off, int size,
3305 enum bpf_access_type atype,
3306 int value_regno)
3307{
3308 struct bpf_reg_state *reg = regs + regno;
3309 struct bpf_map *map = reg->map_ptr;
3310 const struct btf_type *t;
3311 const char *tname;
3312 u32 btf_id;
3313 int ret;
3314
3315 if (!btf_vmlinux) {
3316 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3317 return -ENOTSUPP;
3318 }
3319
3320 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3321 verbose(env, "map_ptr access not supported for map type %d\n",
3322 map->map_type);
3323 return -ENOTSUPP;
3324 }
3325
3326 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3327 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3328
3329 if (!env->allow_ptr_to_map_access) {
3330 verbose(env,
3331 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3332 tname);
3333 return -EPERM;
3334 }
3335
3336 if (off < 0) {
3337 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3338 regno, tname, off);
3339 return -EACCES;
3340 }
3341
3342 if (atype != BPF_READ) {
3343 verbose(env, "only read from %s is supported\n", tname);
3344 return -EACCES;
3345 }
3346
3347 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3348 if (ret < 0)
3349 return ret;
3350
3351 if (value_regno >= 0)
3352 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3353
3354 return 0;
3355}
3356
3357
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003358/* check whether memory at (regno + off) is accessible for t = (read | write)
3359 * if t==write, value_regno is a register which value is stored into memory
3360 * if t==read, value_regno is a register which will receive the value from memory
3361 * if t==write && value_regno==-1, some unknown value is stored into memory
3362 * if t==read && value_regno==-1, don't care what we read from memory
3363 */
Daniel Borkmannca369602018-02-23 22:29:05 +01003364static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3365 int off, int bpf_size, enum bpf_access_type t,
3366 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003367{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003368 struct bpf_reg_state *regs = cur_regs(env);
3369 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003370 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003371 int size, err = 0;
3372
3373 size = bpf_size_to_bytes(bpf_size);
3374 if (size < 0)
3375 return size;
3376
Edward Creef1174f72017-08-07 15:26:19 +01003377 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01003378 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003379 if (err)
3380 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003381
Edward Creef1174f72017-08-07 15:26:19 +01003382 /* for access checks, reg->off is just part of off */
3383 off += reg->off;
3384
3385 if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003386 if (t == BPF_WRITE && value_regno >= 0 &&
3387 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003388 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003389 return -EACCES;
3390 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02003391 err = check_map_access_type(env, regno, off, size, t);
3392 if (err)
3393 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003394 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003395 if (!err && t == BPF_READ && value_regno >= 0) {
3396 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003397
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003398 /* if map is read-only, track its contents as scalars */
3399 if (tnum_is_const(reg->var_off) &&
3400 bpf_map_is_rdonly(map) &&
3401 map->ops->map_direct_value_addr) {
3402 int map_off = off + reg->var_off.value;
3403 u64 val = 0;
3404
3405 err = bpf_map_direct_read(map, map_off, size,
3406 &val);
3407 if (err)
3408 return err;
3409
3410 regs[value_regno].type = SCALAR_VALUE;
3411 __mark_reg_known(&regs[value_regno], val);
3412 } else {
3413 mark_reg_unknown(env, regs, value_regno);
3414 }
3415 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003416 } else if (reg->type == PTR_TO_MEM) {
3417 if (t == BPF_WRITE && value_regno >= 0 &&
3418 is_pointer_value(env, value_regno)) {
3419 verbose(env, "R%d leaks addr into mem\n", value_regno);
3420 return -EACCES;
3421 }
3422 err = check_mem_region_access(env, regno, off, size,
3423 reg->mem_size, false);
3424 if (!err && t == BPF_READ && value_regno >= 0)
3425 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07003426 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01003427 enum bpf_reg_type reg_type = SCALAR_VALUE;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003428 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07003429
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003430 if (t == BPF_WRITE && value_regno >= 0 &&
3431 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003432 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003433 return -EACCES;
3434 }
Edward Creef1174f72017-08-07 15:26:19 +01003435
Daniel Borkmann58990d12018-06-07 17:40:03 +02003436 err = check_ctx_reg(env, reg, regno);
3437 if (err < 0)
3438 return err;
3439
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003440 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3441 if (err)
3442 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003443 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01003444 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003445 * PTR_TO_PACKET[_META,_END]. In the latter
3446 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01003447 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003448 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003449 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003450 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003451 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003452 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003453 if (reg_type_may_be_null(reg_type))
3454 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01003455 /* A load of ctx field could have different
3456 * actual load size with the one encoded in the
3457 * insn. When the dst is PTR, it is for sure not
3458 * a sub-register.
3459 */
3460 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07003461 if (reg_type == PTR_TO_BTF_ID ||
3462 reg_type == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003463 regs[value_regno].btf_id = btf_id;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003464 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003465 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003466 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003467
Edward Creef1174f72017-08-07 15:26:19 +01003468 } else if (reg->type == PTR_TO_STACK) {
Edward Creef1174f72017-08-07 15:26:19 +01003469 off += reg->var_off.value;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003470 err = check_stack_access(env, reg, off, size);
3471 if (err)
3472 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003473
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003474 state = func(env, reg);
3475 err = update_stack_depth(env, state, off);
3476 if (err)
3477 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003478
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003479 if (t == BPF_WRITE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003480 err = check_stack_write(env, state, off, size,
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07003481 value_regno, insn_idx);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003482 else
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003483 err = check_stack_read(env, state, off, size,
3484 value_regno);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003485 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003486 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003487 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003488 return -EACCES;
3489 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003490 if (t == BPF_WRITE && value_regno >= 0 &&
3491 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003492 verbose(env, "R%d leaks addr into packet\n",
3493 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003494 return -EACCES;
3495 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08003496 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003497 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003498 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07003499 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3500 if (t == BPF_WRITE && value_regno >= 0 &&
3501 is_pointer_value(env, value_regno)) {
3502 verbose(env, "R%d leaks addr into flow keys\n",
3503 value_regno);
3504 return -EACCES;
3505 }
3506
3507 err = check_flow_keys_access(env, off, size);
3508 if (!err && t == BPF_READ && value_regno >= 0)
3509 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003510 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07003511 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003512 verbose(env, "R%d cannot write into %s\n",
3513 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07003514 return -EACCES;
3515 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003516 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07003517 if (!err && value_regno >= 0)
3518 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07003519 } else if (reg->type == PTR_TO_TP_BUFFER) {
3520 err = check_tp_buffer_access(env, reg, regno, off, size);
3521 if (!err && t == BPF_READ && value_regno >= 0)
3522 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003523 } else if (reg->type == PTR_TO_BTF_ID) {
3524 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3525 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003526 } else if (reg->type == CONST_PTR_TO_MAP) {
3527 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3528 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07003529 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3530 if (t == BPF_WRITE) {
3531 verbose(env, "R%d cannot write into %s\n",
3532 regno, reg_type_str[reg->type]);
3533 return -EACCES;
3534 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003535 err = check_buffer_access(env, reg, regno, off, size, false,
3536 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003537 &env->prog->aux->max_rdonly_access);
3538 if (!err && value_regno >= 0)
3539 mark_reg_unknown(env, regs, value_regno);
3540 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003541 err = check_buffer_access(env, reg, regno, off, size, false,
3542 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003543 &env->prog->aux->max_rdwr_access);
3544 if (!err && t == BPF_READ && value_regno >= 0)
3545 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003546 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003547 verbose(env, "R%d invalid mem access '%s'\n", regno,
3548 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003549 return -EACCES;
3550 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003551
Edward Creef1174f72017-08-07 15:26:19 +01003552 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003553 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01003554 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08003555 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003556 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003557 return err;
3558}
3559
Yonghong Song31fd8582017-06-13 15:52:13 -07003560static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003561{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003562 int err;
3563
3564 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3565 insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003566 verbose(env, "BPF_XADD uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003567 return -EINVAL;
3568 }
3569
3570 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003571 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003572 if (err)
3573 return err;
3574
3575 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003576 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003577 if (err)
3578 return err;
3579
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003580 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003581 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003582 return -EACCES;
3583 }
3584
Daniel Borkmannca369602018-02-23 22:29:05 +01003585 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003586 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003587 is_flow_key_reg(env, insn->dst_reg) ||
3588 is_sk_reg(env, insn->dst_reg)) {
Daniel Borkmannca369602018-02-23 22:29:05 +01003589 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003590 insn->dst_reg,
3591 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003592 return -EACCES;
3593 }
3594
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003595 /* check whether atomic_add can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003596 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003597 BPF_SIZE(insn->code), BPF_READ, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003598 if (err)
3599 return err;
3600
3601 /* check whether atomic_add can write into the same memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003602 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003603 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003604}
3605
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003606static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3607 int off, int access_size,
3608 bool zero_size_allowed)
3609{
3610 struct bpf_reg_state *reg = reg_state(env, regno);
3611
3612 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3613 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3614 if (tnum_is_const(reg->var_off)) {
3615 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3616 regno, off, access_size);
3617 } else {
3618 char tn_buf[48];
3619
3620 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3621 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3622 regno, tn_buf, access_size);
3623 }
3624 return -EACCES;
3625 }
3626 return 0;
3627}
3628
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003629/* when register 'regno' is passed into function that will read 'access_size'
3630 * bytes from that pointer, make sure that it's within stack boundary
Edward Creef1174f72017-08-07 15:26:19 +01003631 * and all elements of stack are initialized.
3632 * Unlike most pointer bounds-checking functions, this one doesn't take an
3633 * 'off' argument, so it has to add in reg->off itself.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003634 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003635static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
Daniel Borkmann435faee12016-04-13 00:10:51 +02003636 int access_size, bool zero_size_allowed,
3637 struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003638{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003639 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003640 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003641 int err, min_off, max_off, i, j, slot, spi;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003642
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003643 if (tnum_is_const(reg->var_off)) {
3644 min_off = max_off = reg->var_off.value + reg->off;
3645 err = __check_stack_boundary(env, regno, min_off, access_size,
3646 zero_size_allowed);
3647 if (err)
3648 return err;
3649 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07003650 /* Variable offset is prohibited for unprivileged mode for
3651 * simplicity since it requires corresponding support in
3652 * Spectre masking for stack ALU.
3653 * See also retrieve_ptr_limit().
3654 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07003655 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07003656 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01003657
Andrey Ignatov088ec262019-04-03 23:22:39 -07003658 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3659 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3660 regno, tn_buf);
3661 return -EACCES;
3662 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07003663 /* Only initialized buffer on stack is allowed to be accessed
3664 * with variable offset. With uninitialized buffer it's hard to
3665 * guarantee that whole memory is marked as initialized on
3666 * helper return since specific bounds are unknown what may
3667 * cause uninitialized stack leaking.
3668 */
3669 if (meta && meta->raw_mode)
3670 meta = NULL;
3671
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003672 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3673 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3674 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3675 regno);
3676 return -EACCES;
3677 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003678 min_off = reg->smin_value + reg->off;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003679 max_off = reg->smax_value + reg->off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003680 err = __check_stack_boundary(env, regno, min_off, access_size,
3681 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003682 if (err) {
3683 verbose(env, "R%d min value is outside of stack bound\n",
3684 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003685 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003686 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003687 err = __check_stack_boundary(env, regno, max_off, access_size,
3688 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003689 if (err) {
3690 verbose(env, "R%d max value is outside of stack bound\n",
3691 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003692 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003693 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003694 }
3695
Daniel Borkmann435faee12016-04-13 00:10:51 +02003696 if (meta && meta->raw_mode) {
3697 meta->access_size = access_size;
3698 meta->regno = regno;
3699 return 0;
3700 }
3701
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003702 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003703 u8 *stype;
3704
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003705 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003706 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003707 if (state->allocated_stack <= slot)
3708 goto err;
3709 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3710 if (*stype == STACK_MISC)
3711 goto mark;
3712 if (*stype == STACK_ZERO) {
3713 /* helper can write anything into the stack */
3714 *stype = STACK_MISC;
3715 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003716 }
Yonghong Song1d68f222020-05-09 10:59:15 -07003717
3718 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3719 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3720 goto mark;
3721
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003722 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3723 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003724 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003725 for (j = 0; j < BPF_REG_SIZE; j++)
3726 state->stack[spi].slot_type[j] = STACK_MISC;
3727 goto mark;
3728 }
3729
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003730err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003731 if (tnum_is_const(reg->var_off)) {
3732 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3733 min_off, i - min_off, access_size);
3734 } else {
3735 char tn_buf[48];
3736
3737 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3738 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3739 tn_buf, i - min_off, access_size);
3740 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003741 return -EACCES;
3742mark:
3743 /* reading any byte out of 8-byte 'spill_slot' will cause
3744 * the whole slot to be marked as 'read'
3745 */
Edward Cree679c7822018-08-22 20:02:19 +01003746 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01003747 state->stack[spi].spilled_ptr.parent,
3748 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003749 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003750 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003751}
3752
Gianluca Borello06c1c042017-01-09 10:19:49 -08003753static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3754 int access_size, bool zero_size_allowed,
3755 struct bpf_call_arg_meta *meta)
3756{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003757 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08003758
Edward Creef1174f72017-08-07 15:26:19 +01003759 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08003760 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003761 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08003762 return check_packet_access(env, regno, reg->off, access_size,
3763 zero_size_allowed);
Gianluca Borello06c1c042017-01-09 10:19:49 -08003764 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02003765 if (check_map_access_type(env, regno, reg->off, access_size,
3766 meta && meta->raw_mode ? BPF_WRITE :
3767 BPF_READ))
3768 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003769 return check_map_access(env, regno, reg->off, access_size,
3770 zero_size_allowed);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003771 case PTR_TO_MEM:
3772 return check_mem_region_access(env, regno, reg->off,
3773 access_size, reg->mem_size,
3774 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07003775 case PTR_TO_RDONLY_BUF:
3776 if (meta && meta->raw_mode)
3777 return -EACCES;
3778 return check_buffer_access(env, reg, regno, reg->off,
3779 access_size, zero_size_allowed,
3780 "rdonly",
3781 &env->prog->aux->max_rdonly_access);
3782 case PTR_TO_RDWR_BUF:
3783 return check_buffer_access(env, reg, regno, reg->off,
3784 access_size, zero_size_allowed,
3785 "rdwr",
3786 &env->prog->aux->max_rdwr_access);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01003787 case PTR_TO_STACK:
Gianluca Borello06c1c042017-01-09 10:19:49 -08003788 return check_stack_boundary(env, regno, access_size,
3789 zero_size_allowed, meta);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01003790 default: /* scalar_value or invalid ptr */
3791 /* Allow zero-byte read from NULL, regardless of pointer type */
3792 if (zero_size_allowed && access_size == 0 &&
3793 register_is_null(reg))
3794 return 0;
3795
3796 verbose(env, "R%d type=%s expected=%s\n", regno,
3797 reg_type_str[reg->type],
3798 reg_type_str[PTR_TO_STACK]);
3799 return -EACCES;
Gianluca Borello06c1c042017-01-09 10:19:49 -08003800 }
3801}
3802
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003803/* Implementation details:
3804 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3805 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3806 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3807 * value_or_null->value transition, since the verifier only cares about
3808 * the range of access to valid map value pointer and doesn't care about actual
3809 * address of the map element.
3810 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3811 * reg->id > 0 after value_or_null->value transition. By doing so
3812 * two bpf_map_lookups will be considered two different pointers that
3813 * point to different bpf_spin_locks.
3814 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3815 * dead-locks.
3816 * Since only one bpf_spin_lock is allowed the checks are simpler than
3817 * reg_is_refcounted() logic. The verifier needs to remember only
3818 * one spin_lock instead of array of acquired_refs.
3819 * cur_state->active_spin_lock remembers which map value element got locked
3820 * and clears it after bpf_spin_unlock.
3821 */
3822static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3823 bool is_lock)
3824{
3825 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3826 struct bpf_verifier_state *cur = env->cur_state;
3827 bool is_const = tnum_is_const(reg->var_off);
3828 struct bpf_map *map = reg->map_ptr;
3829 u64 val = reg->var_off.value;
3830
3831 if (reg->type != PTR_TO_MAP_VALUE) {
3832 verbose(env, "R%d is not a pointer to map_value\n", regno);
3833 return -EINVAL;
3834 }
3835 if (!is_const) {
3836 verbose(env,
3837 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3838 regno);
3839 return -EINVAL;
3840 }
3841 if (!map->btf) {
3842 verbose(env,
3843 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3844 map->name);
3845 return -EINVAL;
3846 }
3847 if (!map_value_has_spin_lock(map)) {
3848 if (map->spin_lock_off == -E2BIG)
3849 verbose(env,
3850 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3851 map->name);
3852 else if (map->spin_lock_off == -ENOENT)
3853 verbose(env,
3854 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3855 map->name);
3856 else
3857 verbose(env,
3858 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3859 map->name);
3860 return -EINVAL;
3861 }
3862 if (map->spin_lock_off != val + reg->off) {
3863 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3864 val + reg->off);
3865 return -EINVAL;
3866 }
3867 if (is_lock) {
3868 if (cur->active_spin_lock) {
3869 verbose(env,
3870 "Locking two bpf_spin_locks are not allowed\n");
3871 return -EINVAL;
3872 }
3873 cur->active_spin_lock = reg->id;
3874 } else {
3875 if (!cur->active_spin_lock) {
3876 verbose(env, "bpf_spin_unlock without taking a lock\n");
3877 return -EINVAL;
3878 }
3879 if (cur->active_spin_lock != reg->id) {
3880 verbose(env, "bpf_spin_unlock of different lock\n");
3881 return -EINVAL;
3882 }
3883 cur->active_spin_lock = 0;
3884 }
3885 return 0;
3886}
3887
Daniel Borkmann90133412018-01-20 01:24:29 +01003888static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3889{
3890 return type == ARG_PTR_TO_MEM ||
3891 type == ARG_PTR_TO_MEM_OR_NULL ||
3892 type == ARG_PTR_TO_UNINIT_MEM;
3893}
3894
3895static bool arg_type_is_mem_size(enum bpf_arg_type type)
3896{
3897 return type == ARG_CONST_SIZE ||
3898 type == ARG_CONST_SIZE_OR_ZERO;
3899}
3900
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003901static bool arg_type_is_alloc_mem_ptr(enum bpf_arg_type type)
3902{
3903 return type == ARG_PTR_TO_ALLOC_MEM ||
3904 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
3905}
3906
3907static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3908{
3909 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3910}
3911
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003912static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3913{
3914 return type == ARG_PTR_TO_INT ||
3915 type == ARG_PTR_TO_LONG;
3916}
3917
3918static int int_ptr_type_to_size(enum bpf_arg_type type)
3919{
3920 if (type == ARG_PTR_TO_INT)
3921 return sizeof(u32);
3922 else if (type == ARG_PTR_TO_LONG)
3923 return sizeof(u64);
3924
3925 return -EINVAL;
3926}
3927
Lorenz Bauer912f4422020-08-21 11:29:46 +01003928static int resolve_map_arg_type(struct bpf_verifier_env *env,
3929 const struct bpf_call_arg_meta *meta,
3930 enum bpf_arg_type *arg_type)
3931{
3932 if (!meta->map_ptr) {
3933 /* kernel subsystem misconfigured verifier */
3934 verbose(env, "invalid map_ptr to access map->type\n");
3935 return -EACCES;
3936 }
3937
3938 switch (meta->map_ptr->map_type) {
3939 case BPF_MAP_TYPE_SOCKMAP:
3940 case BPF_MAP_TYPE_SOCKHASH:
3941 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
3942 *arg_type = ARG_PTR_TO_SOCKET;
3943 } else {
3944 verbose(env, "invalid arg_type for sockmap/sockhash\n");
3945 return -EINVAL;
3946 }
3947 break;
3948
3949 default:
3950 break;
3951 }
3952 return 0;
3953}
3954
Yonghong Songaf7ec132020-06-23 16:08:09 -07003955static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
3956 struct bpf_call_arg_meta *meta,
3957 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003958{
Yonghong Songaf7ec132020-06-23 16:08:09 -07003959 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003960 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003961 enum bpf_reg_type expected_type, type = reg->type;
Yonghong Songaf7ec132020-06-23 16:08:09 -07003962 enum bpf_arg_type arg_type = fn->arg_type[arg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003963 int err = 0;
3964
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003965 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003966 return 0;
3967
Edward Creedc503a82017-08-15 20:34:35 +01003968 err = check_reg_arg(env, regno, SRC_OP);
3969 if (err)
3970 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003971
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003972 if (arg_type == ARG_ANYTHING) {
3973 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003974 verbose(env, "R%d leaks addr into helper function\n",
3975 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003976 return -EACCES;
3977 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003978 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003979 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003980
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003981 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003982 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003983 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003984 return -EACCES;
3985 }
3986
Lorenz Bauer912f4422020-08-21 11:29:46 +01003987 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
3988 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3989 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
3990 err = resolve_map_arg_type(env, meta, &arg_type);
3991 if (err)
3992 return err;
3993 }
3994
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003995 if (arg_type == ARG_PTR_TO_MAP_KEY ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003996 arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003997 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3998 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003999 expected_type = PTR_TO_STACK;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004000 if (register_is_null(reg) &&
4001 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
4002 /* final test in check_stack_boundary() */;
4003 else if (!type_is_pkt_pointer(type) &&
4004 type != PTR_TO_MAP_VALUE &&
4005 type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004006 goto err_type;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004007 } else if (arg_type == ARG_CONST_SIZE ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004008 arg_type == ARG_CONST_SIZE_OR_ZERO ||
4009 arg_type == ARG_CONST_ALLOC_SIZE_OR_ZERO) {
Edward Creef1174f72017-08-07 15:26:19 +01004010 expected_type = SCALAR_VALUE;
4011 if (type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004012 goto err_type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004013 } else if (arg_type == ARG_CONST_MAP_PTR) {
4014 expected_type = CONST_PTR_TO_MAP;
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004015 if (type != expected_type)
4016 goto err_type;
Daniel Borkmannf3189032020-03-27 16:58:52 +01004017 } else if (arg_type == ARG_PTR_TO_CTX ||
4018 arg_type == ARG_PTR_TO_CTX_OR_NULL) {
Alexei Starovoitov608cd712015-03-26 19:53:57 -07004019 expected_type = PTR_TO_CTX;
Daniel Borkmannf3189032020-03-27 16:58:52 +01004020 if (!(register_is_null(reg) &&
4021 arg_type == ARG_PTR_TO_CTX_OR_NULL)) {
4022 if (type != expected_type)
4023 goto err_type;
4024 err = check_ctx_reg(env, reg, regno);
4025 if (err < 0)
4026 return err;
4027 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004028 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
4029 expected_type = PTR_TO_SOCK_COMMON;
4030 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
4031 if (!type_is_sk_pointer(type))
4032 goto err_type;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004033 if (reg->ref_obj_id) {
4034 if (meta->ref_obj_id) {
4035 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4036 regno, reg->ref_obj_id,
4037 meta->ref_obj_id);
4038 return -EFAULT;
4039 }
4040 meta->ref_obj_id = reg->ref_obj_id;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004041 }
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02004042 } else if (arg_type == ARG_PTR_TO_SOCKET ||
4043 arg_type == ARG_PTR_TO_SOCKET_OR_NULL) {
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004044 expected_type = PTR_TO_SOCKET;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02004045 if (!(register_is_null(reg) &&
4046 arg_type == ARG_PTR_TO_SOCKET_OR_NULL)) {
4047 if (type != expected_type)
4048 goto err_type;
4049 }
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004050 } else if (arg_type == ARG_PTR_TO_BTF_ID) {
4051 expected_type = PTR_TO_BTF_ID;
4052 if (type != expected_type)
4053 goto err_type;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004054 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4055 if (meta->func_id == BPF_FUNC_spin_lock) {
4056 if (process_spin_lock(env, regno, true))
4057 return -EACCES;
4058 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4059 if (process_spin_lock(env, regno, false))
4060 return -EACCES;
4061 } else {
4062 verbose(env, "verifier internal error\n");
4063 return -EFAULT;
4064 }
Daniel Borkmann90133412018-01-20 01:24:29 +01004065 } else if (arg_type_is_mem_ptr(arg_type)) {
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01004066 expected_type = PTR_TO_STACK;
4067 /* One exception here. In case function allows for NULL to be
Edward Creef1174f72017-08-07 15:26:19 +01004068 * passed in as argument, it's a SCALAR_VALUE type. Final test
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01004069 * happens during stack boundary checking.
4070 */
Alexei Starovoitov914cb782017-11-30 21:31:40 -08004071 if (register_is_null(reg) &&
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004072 (arg_type == ARG_PTR_TO_MEM_OR_NULL ||
4073 arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL))
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004074 /* final test in check_stack_boundary() */;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004075 else if (!type_is_pkt_pointer(type) &&
4076 type != PTR_TO_MAP_VALUE &&
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004077 type != PTR_TO_MEM &&
Yonghong Songafbf21d2020-07-23 11:41:11 -07004078 type != PTR_TO_RDONLY_BUF &&
4079 type != PTR_TO_RDWR_BUF &&
Edward Creef1174f72017-08-07 15:26:19 +01004080 type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004081 goto err_type;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004082 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004083 } else if (arg_type_is_alloc_mem_ptr(arg_type)) {
4084 expected_type = PTR_TO_MEM;
4085 if (register_is_null(reg) &&
4086 arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL)
4087 /* final test in check_stack_boundary() */;
4088 else if (type != expected_type)
4089 goto err_type;
4090 if (meta->ref_obj_id) {
4091 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4092 regno, reg->ref_obj_id,
4093 meta->ref_obj_id);
4094 return -EFAULT;
4095 }
4096 meta->ref_obj_id = reg->ref_obj_id;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004097 } else if (arg_type_is_int_ptr(arg_type)) {
4098 expected_type = PTR_TO_STACK;
4099 if (!type_is_pkt_pointer(type) &&
4100 type != PTR_TO_MAP_VALUE &&
4101 type != expected_type)
4102 goto err_type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004103 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004104 verbose(env, "unsupported arg_type %d\n", arg_type);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004105 return -EFAULT;
4106 }
4107
Lorenz Bauerd7b94542020-09-21 13:12:21 +01004108 if (type == PTR_TO_BTF_ID) {
4109 const u32 *btf_id = fn->arg_btf_id[arg];
4110
4111 if (!btf_id) {
4112 verbose(env, "verifier internal error: missing BTF ID\n");
4113 return -EFAULT;
4114 }
4115
4116 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id, *btf_id)) {
4117 verbose(env, "R%d is of type %s but %s is expected\n",
4118 regno, kernel_type_name(reg->btf_id), kernel_type_name(*btf_id));
4119 return -EACCES;
4120 }
4121 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4122 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4123 regno);
4124 return -EACCES;
4125 }
4126 }
4127
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004128 if (arg_type == ARG_CONST_MAP_PTR) {
4129 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004130 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004131 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4132 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4133 * check that [key, key + map->key_size) are within
4134 * stack limits and initialized
4135 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004136 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004137 /* in function declaration map_ptr must come before
4138 * map_key, so that it's verified and known before
4139 * we have to check map_key here. Otherwise it means
4140 * that kernel subsystem misconfigured verifier
4141 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004142 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004143 return -EACCES;
4144 }
Paul Chaignond71962f2018-04-24 15:07:54 +02004145 err = check_helper_mem_access(env, regno,
4146 meta->map_ptr->key_size, false,
4147 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004148 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004149 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4150 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004151 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004152 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4153 * check [value, value + map->value_size) validity
4154 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004155 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004156 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004157 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004158 return -EACCES;
4159 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004160 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02004161 err = check_helper_mem_access(env, regno,
4162 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004163 meta);
Daniel Borkmann90133412018-01-20 01:24:29 +01004164 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004165 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004166
John Fastabend10060502020-03-30 14:36:19 -07004167 /* This is used to refine r0 return value bounds for helpers
4168 * that enforce this value as an upper bound on return values.
4169 * See do_refine_retval_range() for helpers that can refine
4170 * the return value. C type of helper is u32 so we pull register
4171 * bound from umax_value however, if negative verifier errors
4172 * out. Only upper bounds can be learned because retval is an
4173 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07004174 */
John Fastabend10060502020-03-30 14:36:19 -07004175 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004176
Edward Creef1174f72017-08-07 15:26:19 +01004177 /* The register is SCALAR_VALUE; the access check
4178 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08004179 */
Edward Creef1174f72017-08-07 15:26:19 +01004180 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08004181 /* For unprivileged variable accesses, disable raw
4182 * mode so that the program is required to
4183 * initialize all the memory that the helper could
4184 * just partially fill up.
4185 */
4186 meta = NULL;
4187
Edward Creeb03c9f92017-08-07 15:26:36 +01004188 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004189 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004190 regno);
4191 return -EACCES;
4192 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08004193
Edward Creeb03c9f92017-08-07 15:26:36 +01004194 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004195 err = check_helper_mem_access(env, regno - 1, 0,
4196 zero_size_allowed,
4197 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004198 if (err)
4199 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004200 }
Edward Creef1174f72017-08-07 15:26:19 +01004201
Edward Creeb03c9f92017-08-07 15:26:36 +01004202 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004203 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004204 regno);
4205 return -EACCES;
4206 }
4207 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01004208 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01004209 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07004210 if (!err)
4211 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004212 } else if (arg_type_is_alloc_size(arg_type)) {
4213 if (!tnum_is_const(reg->var_off)) {
4214 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4215 regno);
4216 return -EACCES;
4217 }
4218 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004219 } else if (arg_type_is_int_ptr(arg_type)) {
4220 int size = int_ptr_type_to_size(arg_type);
4221
4222 err = check_helper_mem_access(env, regno, size, false, meta);
4223 if (err)
4224 return err;
4225 err = check_ptr_alignment(env, reg, 0, size, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004226 }
4227
4228 return err;
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004229err_type:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004230 verbose(env, "R%d type=%s expected=%s\n", regno,
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004231 reg_type_str[type], reg_type_str[expected_type]);
4232 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004233}
4234
Lorenz Bauer01262402020-08-21 11:29:47 +01004235static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4236{
4237 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07004238 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01004239
4240 if (func_id != BPF_FUNC_map_update_elem)
4241 return false;
4242
4243 /* It's not possible to get access to a locked struct sock in these
4244 * contexts, so updating is safe.
4245 */
4246 switch (type) {
4247 case BPF_PROG_TYPE_TRACING:
4248 if (eatype == BPF_TRACE_ITER)
4249 return true;
4250 break;
4251 case BPF_PROG_TYPE_SOCKET_FILTER:
4252 case BPF_PROG_TYPE_SCHED_CLS:
4253 case BPF_PROG_TYPE_SCHED_ACT:
4254 case BPF_PROG_TYPE_XDP:
4255 case BPF_PROG_TYPE_SK_REUSEPORT:
4256 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4257 case BPF_PROG_TYPE_SK_LOOKUP:
4258 return true;
4259 default:
4260 break;
4261 }
4262
4263 verbose(env, "cannot update sockmap in this context\n");
4264 return false;
4265}
4266
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004267static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4268{
4269 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4270}
4271
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004272static int check_map_func_compatibility(struct bpf_verifier_env *env,
4273 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00004274{
Kaixu Xia35578d72015-08-06 07:02:35 +00004275 if (!map)
4276 return 0;
4277
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004278 /* We need a two way check, first is from map perspective ... */
4279 switch (map->map_type) {
4280 case BPF_MAP_TYPE_PROG_ARRAY:
4281 if (func_id != BPF_FUNC_tail_call)
4282 goto error;
4283 break;
4284 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4285 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07004286 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004287 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004288 func_id != BPF_FUNC_perf_event_read_value &&
4289 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004290 goto error;
4291 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004292 case BPF_MAP_TYPE_RINGBUF:
4293 if (func_id != BPF_FUNC_ringbuf_output &&
4294 func_id != BPF_FUNC_ringbuf_reserve &&
4295 func_id != BPF_FUNC_ringbuf_submit &&
4296 func_id != BPF_FUNC_ringbuf_discard &&
4297 func_id != BPF_FUNC_ringbuf_query)
4298 goto error;
4299 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004300 case BPF_MAP_TYPE_STACK_TRACE:
4301 if (func_id != BPF_FUNC_get_stackid)
4302 goto error;
4303 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07004304 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04004305 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004306 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004307 goto error;
4308 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004309 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00004310 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07004311 if (func_id != BPF_FUNC_get_local_storage)
4312 goto error;
4313 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07004314 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004315 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02004316 if (func_id != BPF_FUNC_redirect_map &&
4317 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07004318 goto error;
4319 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004320 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4321 * appear.
4322 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02004323 case BPF_MAP_TYPE_CPUMAP:
4324 if (func_id != BPF_FUNC_redirect_map)
4325 goto error;
4326 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07004327 case BPF_MAP_TYPE_XSKMAP:
4328 if (func_id != BPF_FUNC_redirect_map &&
4329 func_id != BPF_FUNC_map_lookup_elem)
4330 goto error;
4331 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004332 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07004333 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004334 if (func_id != BPF_FUNC_map_lookup_elem)
4335 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07004336 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004337 case BPF_MAP_TYPE_SOCKMAP:
4338 if (func_id != BPF_FUNC_sk_redirect_map &&
4339 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07004340 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004341 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004342 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004343 func_id != BPF_FUNC_map_lookup_elem &&
4344 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07004345 goto error;
4346 break;
John Fastabend81110382018-05-14 10:00:17 -07004347 case BPF_MAP_TYPE_SOCKHASH:
4348 if (func_id != BPF_FUNC_sk_redirect_hash &&
4349 func_id != BPF_FUNC_sock_hash_update &&
4350 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004351 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004352 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004353 func_id != BPF_FUNC_map_lookup_elem &&
4354 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07004355 goto error;
4356 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004357 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4358 if (func_id != BPF_FUNC_sk_select_reuseport)
4359 goto error;
4360 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004361 case BPF_MAP_TYPE_QUEUE:
4362 case BPF_MAP_TYPE_STACK:
4363 if (func_id != BPF_FUNC_map_peek_elem &&
4364 func_id != BPF_FUNC_map_pop_elem &&
4365 func_id != BPF_FUNC_map_push_elem)
4366 goto error;
4367 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004368 case BPF_MAP_TYPE_SK_STORAGE:
4369 if (func_id != BPF_FUNC_sk_storage_get &&
4370 func_id != BPF_FUNC_sk_storage_delete)
4371 goto error;
4372 break;
KP Singh8ea63682020-08-25 20:29:17 +02004373 case BPF_MAP_TYPE_INODE_STORAGE:
4374 if (func_id != BPF_FUNC_inode_storage_get &&
4375 func_id != BPF_FUNC_inode_storage_delete)
4376 goto error;
4377 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004378 default:
4379 break;
4380 }
4381
4382 /* ... and second from the function itself. */
4383 switch (func_id) {
4384 case BPF_FUNC_tail_call:
4385 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4386 goto error;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004387 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4388 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004389 return -EINVAL;
4390 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004391 break;
4392 case BPF_FUNC_perf_event_read:
4393 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07004394 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004395 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004396 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004397 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4398 goto error;
4399 break;
4400 case BPF_FUNC_get_stackid:
4401 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4402 goto error;
4403 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004404 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02004405 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004406 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4407 goto error;
4408 break;
John Fastabend97f91a72017-07-17 09:29:18 -07004409 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02004410 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004411 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004412 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4413 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07004414 goto error;
4415 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004416 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07004417 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07004418 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07004419 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4420 goto error;
4421 break;
John Fastabend81110382018-05-14 10:00:17 -07004422 case BPF_FUNC_sk_redirect_hash:
4423 case BPF_FUNC_msg_redirect_hash:
4424 case BPF_FUNC_sock_hash_update:
4425 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07004426 goto error;
4427 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004428 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00004429 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4430 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07004431 goto error;
4432 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004433 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004434 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4435 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4436 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004437 goto error;
4438 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004439 case BPF_FUNC_map_peek_elem:
4440 case BPF_FUNC_map_pop_elem:
4441 case BPF_FUNC_map_push_elem:
4442 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4443 map->map_type != BPF_MAP_TYPE_STACK)
4444 goto error;
4445 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004446 case BPF_FUNC_sk_storage_get:
4447 case BPF_FUNC_sk_storage_delete:
4448 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4449 goto error;
4450 break;
KP Singh8ea63682020-08-25 20:29:17 +02004451 case BPF_FUNC_inode_storage_get:
4452 case BPF_FUNC_inode_storage_delete:
4453 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4454 goto error;
4455 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004456 default:
4457 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00004458 }
4459
4460 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004461error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004462 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004463 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004464 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00004465}
4466
Daniel Borkmann90133412018-01-20 01:24:29 +01004467static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004468{
4469 int count = 0;
4470
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004471 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004472 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004473 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004474 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004475 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004476 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004477 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004478 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004479 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004480 count++;
4481
Daniel Borkmann90133412018-01-20 01:24:29 +01004482 /* We only support one arg being in raw mode at the moment,
4483 * which is sufficient for the helper functions we have
4484 * right now.
4485 */
4486 return count <= 1;
4487}
4488
4489static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4490 enum bpf_arg_type arg_next)
4491{
4492 return (arg_type_is_mem_ptr(arg_curr) &&
4493 !arg_type_is_mem_size(arg_next)) ||
4494 (!arg_type_is_mem_ptr(arg_curr) &&
4495 arg_type_is_mem_size(arg_next));
4496}
4497
4498static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4499{
4500 /* bpf_xxx(..., buf, len) call will access 'len'
4501 * bytes from memory 'buf'. Both arg types need
4502 * to be paired, so make sure there's no buggy
4503 * helper function specification.
4504 */
4505 if (arg_type_is_mem_size(fn->arg1_type) ||
4506 arg_type_is_mem_ptr(fn->arg5_type) ||
4507 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4508 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4509 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4510 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4511 return false;
4512
4513 return true;
4514}
4515
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004516static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004517{
4518 int count = 0;
4519
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004520 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004521 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004522 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004523 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004524 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004525 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004526 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004527 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004528 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004529 count++;
4530
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004531 /* A reference acquiring function cannot acquire
4532 * another refcounted ptr.
4533 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004534 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004535 return false;
4536
Joe Stringerfd978bf72018-10-02 13:35:35 -07004537 /* We only support one arg being unreferenced at the moment,
4538 * which is sufficient for the helper functions we have right now.
4539 */
4540 return count <= 1;
4541}
4542
Lorenz Bauer9436ef62020-09-21 13:12:20 +01004543static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4544{
4545 int i;
4546
4547 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++)
4548 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4549 return false;
4550
4551 return true;
4552}
4553
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004554static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01004555{
4556 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07004557 check_arg_pair_ok(fn) &&
Lorenz Bauer9436ef62020-09-21 13:12:20 +01004558 check_btf_id_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004559 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02004560}
4561
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004562/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4563 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01004564 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004565static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4566 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004567{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01004568 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004569 int i;
4570
4571 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004572 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004573 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004574
Joe Stringerf3709f62018-10-02 13:35:29 -07004575 bpf_for_each_spilled_reg(i, state, reg) {
4576 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004577 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004578 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01004579 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004580 }
4581}
4582
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004583static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4584{
4585 struct bpf_verifier_state *vstate = env->cur_state;
4586 int i;
4587
4588 for (i = 0; i <= vstate->curframe; i++)
4589 __clear_all_pkt_pointers(env, vstate->frame[i]);
4590}
4591
Joe Stringerfd978bf72018-10-02 13:35:35 -07004592static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004593 struct bpf_func_state *state,
4594 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004595{
4596 struct bpf_reg_state *regs = state->regs, *reg;
4597 int i;
4598
4599 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004600 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004601 mark_reg_unknown(env, regs, i);
4602
4603 bpf_for_each_spilled_reg(i, state, reg) {
4604 if (!reg)
4605 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004606 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01004607 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07004608 }
4609}
4610
4611/* The pointer with the specified id has released its reference to kernel
4612 * resources. Identify all copies of the same pointer and clear the reference.
4613 */
4614static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004615 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004616{
4617 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004618 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004619 int i;
4620
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004621 err = release_reference_state(cur_func(env), ref_obj_id);
4622 if (err)
4623 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004624
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004625 for (i = 0; i <= vstate->curframe; i++)
4626 release_reg_references(env, vstate->frame[i], ref_obj_id);
4627
4628 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004629}
4630
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004631static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4632 struct bpf_reg_state *regs)
4633{
4634 int i;
4635
4636 /* after the call registers r0 - r5 were scratched */
4637 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4638 mark_reg_not_init(env, regs, caller_saved[i]);
4639 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4640 }
4641}
4642
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004643static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4644 int *insn_idx)
4645{
4646 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004647 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004648 struct bpf_func_state *caller, *callee;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004649 int i, err, subprog, target_insn;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004650 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004651
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08004652 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004653 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08004654 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004655 return -E2BIG;
4656 }
4657
4658 target_insn = *insn_idx + insn->imm;
4659 subprog = find_subprog(env, target_insn + 1);
4660 if (subprog < 0) {
4661 verbose(env, "verifier bug. No program starts at insn %d\n",
4662 target_insn + 1);
4663 return -EFAULT;
4664 }
4665
4666 caller = state->frame[state->curframe];
4667 if (state->frame[state->curframe + 1]) {
4668 verbose(env, "verifier bug. Frame %d already allocated\n",
4669 state->curframe + 1);
4670 return -EFAULT;
4671 }
4672
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004673 func_info_aux = env->prog->aux->func_info_aux;
4674 if (func_info_aux)
4675 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4676 err = btf_check_func_arg_match(env, subprog, caller->regs);
4677 if (err == -EFAULT)
4678 return err;
4679 if (is_global) {
4680 if (err) {
4681 verbose(env, "Caller passes invalid args into func#%d\n",
4682 subprog);
4683 return err;
4684 } else {
4685 if (env->log.level & BPF_LOG_LEVEL)
4686 verbose(env,
4687 "Func#%d is global and valid. Skipping.\n",
4688 subprog);
4689 clear_caller_saved_regs(env, caller->regs);
4690
4691 /* All global functions return SCALAR_VALUE */
4692 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4693
4694 /* continue with next insn after call */
4695 return 0;
4696 }
4697 }
4698
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004699 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4700 if (!callee)
4701 return -ENOMEM;
4702 state->frame[state->curframe + 1] = callee;
4703
4704 /* callee cannot access r0, r6 - r9 for reading and has to write
4705 * into its own stack before reading from it.
4706 * callee can read/write into caller's stack
4707 */
4708 init_func_state(env, callee,
4709 /* remember the callsite, it will be used by bpf_exit */
4710 *insn_idx /* callsite */,
4711 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04004712 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004713
Joe Stringerfd978bf72018-10-02 13:35:35 -07004714 /* Transfer references to the callee */
4715 err = transfer_reference_state(callee, caller);
4716 if (err)
4717 return err;
4718
Edward Cree679c7822018-08-22 20:02:19 +01004719 /* copy r1 - r5 args that callee can access. The copy includes parent
4720 * pointers, which connects us up to the liveness chain
4721 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004722 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4723 callee->regs[i] = caller->regs[i];
4724
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004725 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004726
4727 /* only increment it after check_reg_arg() finished */
4728 state->curframe++;
4729
4730 /* and go analyze first insn of the callee */
4731 *insn_idx = target_insn;
4732
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004733 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004734 verbose(env, "caller:\n");
4735 print_verifier_state(env, caller);
4736 verbose(env, "callee:\n");
4737 print_verifier_state(env, callee);
4738 }
4739 return 0;
4740}
4741
4742static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4743{
4744 struct bpf_verifier_state *state = env->cur_state;
4745 struct bpf_func_state *caller, *callee;
4746 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004747 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004748
4749 callee = state->frame[state->curframe];
4750 r0 = &callee->regs[BPF_REG_0];
4751 if (r0->type == PTR_TO_STACK) {
4752 /* technically it's ok to return caller's stack pointer
4753 * (or caller's caller's pointer) back to the caller,
4754 * since these pointers are valid. Only current stack
4755 * pointer will be invalid as soon as function exits,
4756 * but let's be conservative
4757 */
4758 verbose(env, "cannot return stack pointer to the caller\n");
4759 return -EINVAL;
4760 }
4761
4762 state->curframe--;
4763 caller = state->frame[state->curframe];
4764 /* return to the caller whatever r0 had in the callee */
4765 caller->regs[BPF_REG_0] = *r0;
4766
Joe Stringerfd978bf72018-10-02 13:35:35 -07004767 /* Transfer references to the caller */
4768 err = transfer_reference_state(caller, callee);
4769 if (err)
4770 return err;
4771
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004772 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004773 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004774 verbose(env, "returning from callee:\n");
4775 print_verifier_state(env, callee);
4776 verbose(env, "to caller at %d:\n", *insn_idx);
4777 print_verifier_state(env, caller);
4778 }
4779 /* clear everything in the callee */
4780 free_func_state(callee);
4781 state->frame[state->curframe + 1] = NULL;
4782 return 0;
4783}
4784
Yonghong Song849fa502018-04-28 22:28:09 -07004785static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4786 int func_id,
4787 struct bpf_call_arg_meta *meta)
4788{
4789 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4790
4791 if (ret_type != RET_INTEGER ||
4792 (func_id != BPF_FUNC_get_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02004793 func_id != BPF_FUNC_probe_read_str &&
4794 func_id != BPF_FUNC_probe_read_kernel_str &&
4795 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07004796 return;
4797
John Fastabend10060502020-03-30 14:36:19 -07004798 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07004799 ret_reg->s32_max_value = meta->msize_max_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004800 __reg_deduce_bounds(ret_reg);
4801 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07004802 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07004803}
4804
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004805static int
4806record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4807 int func_id, int insn_idx)
4808{
4809 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02004810 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004811
4812 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02004813 func_id != BPF_FUNC_map_lookup_elem &&
4814 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004815 func_id != BPF_FUNC_map_delete_elem &&
4816 func_id != BPF_FUNC_map_push_elem &&
4817 func_id != BPF_FUNC_map_pop_elem &&
4818 func_id != BPF_FUNC_map_peek_elem)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004819 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02004820
Daniel Borkmann591fe982019-04-09 23:20:05 +02004821 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004822 verbose(env, "kernel subsystem misconfigured verifier\n");
4823 return -EINVAL;
4824 }
4825
Daniel Borkmann591fe982019-04-09 23:20:05 +02004826 /* In case of read-only, some additional restrictions
4827 * need to be applied in order to prevent altering the
4828 * state of the map from program side.
4829 */
4830 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4831 (func_id == BPF_FUNC_map_delete_elem ||
4832 func_id == BPF_FUNC_map_update_elem ||
4833 func_id == BPF_FUNC_map_push_elem ||
4834 func_id == BPF_FUNC_map_pop_elem)) {
4835 verbose(env, "write into map forbidden\n");
4836 return -EACCES;
4837 }
4838
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004839 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004840 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004841 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004842 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004843 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004844 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004845 return 0;
4846}
4847
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004848static int
4849record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4850 int func_id, int insn_idx)
4851{
4852 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4853 struct bpf_reg_state *regs = cur_regs(env), *reg;
4854 struct bpf_map *map = meta->map_ptr;
4855 struct tnum range;
4856 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004857 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004858
4859 if (func_id != BPF_FUNC_tail_call)
4860 return 0;
4861 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4862 verbose(env, "kernel subsystem misconfigured verifier\n");
4863 return -EINVAL;
4864 }
4865
4866 range = tnum_range(0, map->max_entries - 1);
4867 reg = &regs[BPF_REG_3];
4868
4869 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4870 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4871 return 0;
4872 }
4873
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004874 err = mark_chain_precision(env, BPF_REG_3);
4875 if (err)
4876 return err;
4877
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004878 val = reg->var_off.value;
4879 if (bpf_map_key_unseen(aux))
4880 bpf_map_key_store(aux, val);
4881 else if (!bpf_map_key_poisoned(aux) &&
4882 bpf_map_key_immediate(aux) != val)
4883 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4884 return 0;
4885}
4886
Joe Stringerfd978bf72018-10-02 13:35:35 -07004887static int check_reference_leak(struct bpf_verifier_env *env)
4888{
4889 struct bpf_func_state *state = cur_func(env);
4890 int i;
4891
4892 for (i = 0; i < state->acquired_refs; i++) {
4893 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4894 state->refs[i].id, state->refs[i].insn_idx);
4895 }
4896 return state->acquired_refs ? -EINVAL : 0;
4897}
4898
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004899static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004900{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004901 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004902 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004903 struct bpf_call_arg_meta meta;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004904 bool changes_data;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004905 int i, err;
4906
4907 /* find function prototype */
4908 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004909 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4910 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004911 return -EINVAL;
4912 }
4913
Jakub Kicinski00176a32017-10-16 16:40:54 -07004914 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07004915 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004916 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004917 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4918 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004919 return -EINVAL;
4920 }
4921
4922 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01004923 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02004924 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004925 return -EINVAL;
4926 }
4927
Jiri Olsaeae2e832020-08-25 21:21:19 +02004928 if (fn->allowed && !fn->allowed(env->prog)) {
4929 verbose(env, "helper call is not allowed in probe\n");
4930 return -EINVAL;
4931 }
4932
Daniel Borkmann04514d12017-12-14 21:07:25 +01004933 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08004934 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01004935 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4936 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4937 func_id_name(func_id), func_id);
4938 return -EINVAL;
4939 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004940
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004941 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02004942 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004943
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004944 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004945 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004946 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004947 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004948 return err;
4949 }
4950
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004951 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004952 /* check args */
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004953 for (i = 0; i < 5; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07004954 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004955 if (err)
4956 return err;
4957 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004958
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004959 err = record_func_map(env, &meta, func_id, insn_idx);
4960 if (err)
4961 return err;
4962
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004963 err = record_func_key(env, &meta, func_id, insn_idx);
4964 if (err)
4965 return err;
4966
Daniel Borkmann435faee12016-04-13 00:10:51 +02004967 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4968 * is inferred from register state.
4969 */
4970 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01004971 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4972 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004973 if (err)
4974 return err;
4975 }
4976
Joe Stringerfd978bf72018-10-02 13:35:35 -07004977 if (func_id == BPF_FUNC_tail_call) {
4978 err = check_reference_leak(env);
4979 if (err) {
4980 verbose(env, "tail_call would lead to reference leak\n");
4981 return err;
4982 }
4983 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004984 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004985 if (err) {
4986 verbose(env, "func %s#%d reference has not been acquired before\n",
4987 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07004988 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004989 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07004990 }
4991
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004992 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07004993
4994 /* check that flags argument in get_local_storage(map, flags) is 0,
4995 * this is required because get_local_storage() can't return an error.
4996 */
4997 if (func_id == BPF_FUNC_get_local_storage &&
4998 !register_is_null(&regs[BPF_REG_2])) {
4999 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5000 return -EINVAL;
5001 }
5002
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005003 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01005004 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005005 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01005006 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5007 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005008
Jiong Wang5327ed32019-05-24 23:25:12 +01005009 /* helper call returns 64-bit value. */
5010 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5011
Edward Creedc503a82017-08-15 20:34:35 +01005012 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005013 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01005014 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005015 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005016 } else if (fn->ret_type == RET_VOID) {
5017 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07005018 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5019 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01005020 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005021 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005022 /* remember map_ptr, so that check_map_access()
5023 * can check 'value_size' boundary of memory access
5024 * to map element returned from bpf_map_lookup_elem()
5025 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005026 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005027 verbose(env,
5028 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005029 return -EINVAL;
5030 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005031 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005032 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5033 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08005034 if (map_value_has_spin_lock(meta.map_ptr))
5035 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005036 } else {
5037 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5038 regs[BPF_REG_0].id = ++env->id_gen;
5039 }
Joe Stringerc64b7982018-10-02 13:35:33 -07005040 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5041 mark_reg_known_zero(env, regs, BPF_REG_0);
5042 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005043 regs[BPF_REG_0].id = ++env->id_gen;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08005044 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5045 mark_reg_known_zero(env, regs, BPF_REG_0);
5046 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5047 regs[BPF_REG_0].id = ++env->id_gen;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005048 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5049 mark_reg_known_zero(env, regs, BPF_REG_0);
5050 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5051 regs[BPF_REG_0].id = ++env->id_gen;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005052 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5053 mark_reg_known_zero(env, regs, BPF_REG_0);
5054 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5055 regs[BPF_REG_0].id = ++env->id_gen;
5056 regs[BPF_REG_0].mem_size = meta.mem_size;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005057 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5058 int ret_btf_id;
5059
5060 mark_reg_known_zero(env, regs, BPF_REG_0);
5061 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5062 ret_btf_id = *fn->ret_btf_id;
5063 if (ret_btf_id == 0) {
5064 verbose(env, "invalid return type %d of func %s#%d\n",
5065 fn->ret_type, func_id_name(func_id), func_id);
5066 return -EINVAL;
5067 }
5068 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005069 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005070 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005071 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005072 return -EINVAL;
5073 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005074
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005075 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005076 /* For release_reference() */
5077 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005078 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005079 int id = acquire_reference_state(env, insn_idx);
5080
5081 if (id < 0)
5082 return id;
5083 /* For mark_ptr_or_null_reg() */
5084 regs[BPF_REG_0].id = id;
5085 /* For release_reference() */
5086 regs[BPF_REG_0].ref_obj_id = id;
5087 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005088
Yonghong Song849fa502018-04-28 22:28:09 -07005089 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5090
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005091 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00005092 if (err)
5093 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005094
Song Liufa28dcb2020-06-29 23:28:44 -07005095 if ((func_id == BPF_FUNC_get_stack ||
5096 func_id == BPF_FUNC_get_task_stack) &&
5097 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07005098 const char *err_str;
5099
5100#ifdef CONFIG_PERF_EVENTS
5101 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5102 err_str = "cannot get callchain buffer for func %s#%d\n";
5103#else
5104 err = -ENOTSUPP;
5105 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5106#endif
5107 if (err) {
5108 verbose(env, err_str, func_id_name(func_id), func_id);
5109 return err;
5110 }
5111
5112 env->prog->has_callchain_buf = true;
5113 }
5114
Song Liu5d99cb2c2020-07-23 11:06:45 -07005115 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5116 env->prog->call_get_stack = true;
5117
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005118 if (changes_data)
5119 clear_all_pkt_pointers(env);
5120 return 0;
5121}
5122
Edward Creeb03c9f92017-08-07 15:26:36 +01005123static bool signed_add_overflows(s64 a, s64 b)
5124{
5125 /* Do the add in u64, where overflow is well-defined */
5126 s64 res = (s64)((u64)a + (u64)b);
5127
5128 if (b < 0)
5129 return res > a;
5130 return res < a;
5131}
5132
John Fastabend3f50f132020-03-30 14:36:39 -07005133static bool signed_add32_overflows(s64 a, s64 b)
5134{
5135 /* Do the add in u32, where overflow is well-defined */
5136 s32 res = (s32)((u32)a + (u32)b);
5137
5138 if (b < 0)
5139 return res > a;
5140 return res < a;
5141}
5142
5143static bool signed_sub_overflows(s32 a, s32 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01005144{
5145 /* Do the sub in u64, where overflow is well-defined */
5146 s64 res = (s64)((u64)a - (u64)b);
5147
5148 if (b < 0)
5149 return res < a;
5150 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07005151}
5152
John Fastabend3f50f132020-03-30 14:36:39 -07005153static bool signed_sub32_overflows(s32 a, s32 b)
5154{
5155 /* Do the sub in u64, where overflow is well-defined */
5156 s32 res = (s32)((u32)a - (u32)b);
5157
5158 if (b < 0)
5159 return res < a;
5160 return res > a;
5161}
5162
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005163static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5164 const struct bpf_reg_state *reg,
5165 enum bpf_reg_type type)
5166{
5167 bool known = tnum_is_const(reg->var_off);
5168 s64 val = reg->var_off.value;
5169 s64 smin = reg->smin_value;
5170
5171 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5172 verbose(env, "math between %s pointer and %lld is not allowed\n",
5173 reg_type_str[type], val);
5174 return false;
5175 }
5176
5177 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5178 verbose(env, "%s pointer offset %d is not allowed\n",
5179 reg_type_str[type], reg->off);
5180 return false;
5181 }
5182
5183 if (smin == S64_MIN) {
5184 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5185 reg_type_str[type]);
5186 return false;
5187 }
5188
5189 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5190 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5191 smin, reg_type_str[type]);
5192 return false;
5193 }
5194
5195 return true;
5196}
5197
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005198static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5199{
5200 return &env->insn_aux_data[env->insn_idx];
5201}
5202
5203static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5204 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5205{
5206 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5207 (opcode == BPF_SUB && !off_is_neg);
5208 u32 off;
5209
5210 switch (ptr_reg->type) {
5211 case PTR_TO_STACK:
Andrey Ignatov088ec262019-04-03 23:22:39 -07005212 /* Indirect variable offset stack access is prohibited in
5213 * unprivileged mode so it's not handled here.
5214 */
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005215 off = ptr_reg->off + ptr_reg->var_off.value;
5216 if (mask_to_left)
5217 *ptr_limit = MAX_BPF_STACK + off;
5218 else
5219 *ptr_limit = -off;
5220 return 0;
5221 case PTR_TO_MAP_VALUE:
5222 if (mask_to_left) {
5223 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5224 } else {
5225 off = ptr_reg->smin_value + ptr_reg->off;
5226 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5227 }
5228 return 0;
5229 default:
5230 return -EINVAL;
5231 }
5232}
5233
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005234static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5235 const struct bpf_insn *insn)
5236{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005237 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005238}
5239
5240static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5241 u32 alu_state, u32 alu_limit)
5242{
5243 /* If we arrived here from different branches with different
5244 * state or limits to sanitize, then this won't work.
5245 */
5246 if (aux->alu_state &&
5247 (aux->alu_state != alu_state ||
5248 aux->alu_limit != alu_limit))
5249 return -EACCES;
5250
5251 /* Corresponding fixup done in fixup_bpf_calls(). */
5252 aux->alu_state = alu_state;
5253 aux->alu_limit = alu_limit;
5254 return 0;
5255}
5256
5257static int sanitize_val_alu(struct bpf_verifier_env *env,
5258 struct bpf_insn *insn)
5259{
5260 struct bpf_insn_aux_data *aux = cur_aux(env);
5261
5262 if (can_skip_alu_sanitation(env, insn))
5263 return 0;
5264
5265 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5266}
5267
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005268static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5269 struct bpf_insn *insn,
5270 const struct bpf_reg_state *ptr_reg,
5271 struct bpf_reg_state *dst_reg,
5272 bool off_is_neg)
5273{
5274 struct bpf_verifier_state *vstate = env->cur_state;
5275 struct bpf_insn_aux_data *aux = cur_aux(env);
5276 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5277 u8 opcode = BPF_OP(insn->code);
5278 u32 alu_state, alu_limit;
5279 struct bpf_reg_state tmp;
5280 bool ret;
5281
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005282 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005283 return 0;
5284
5285 /* We already marked aux for masking from non-speculative
5286 * paths, thus we got here in the first place. We only care
5287 * to explore bad access from here.
5288 */
5289 if (vstate->speculative)
5290 goto do_sim;
5291
5292 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5293 alu_state |= ptr_is_dst_reg ?
5294 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5295
5296 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5297 return 0;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005298 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005299 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005300do_sim:
5301 /* Simulate and find potential out-of-bounds access under
5302 * speculative execution from truncation as a result of
5303 * masking when off was not within expected range. If off
5304 * sits in dst, then we temporarily need to move ptr there
5305 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5306 * for cases where we use K-based arithmetic in one direction
5307 * and truncated reg-based in the other in order to explore
5308 * bad access.
5309 */
5310 if (!ptr_is_dst_reg) {
5311 tmp = *dst_reg;
5312 *dst_reg = *ptr_reg;
5313 }
5314 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08005315 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005316 *dst_reg = tmp;
5317 return !ret ? -EFAULT : 0;
5318}
5319
Edward Creef1174f72017-08-07 15:26:19 +01005320/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01005321 * Caller should also handle BPF_MOV case separately.
5322 * If we return -EACCES, caller may want to try again treating pointer as a
5323 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5324 */
5325static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5326 struct bpf_insn *insn,
5327 const struct bpf_reg_state *ptr_reg,
5328 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04005329{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005330 struct bpf_verifier_state *vstate = env->cur_state;
5331 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5332 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01005333 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01005334 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5335 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5336 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5337 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01005338 u32 dst = insn->dst_reg, src = insn->src_reg;
Josef Bacik48461132016-09-28 10:54:32 -04005339 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005340 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04005341
Edward Creef1174f72017-08-07 15:26:19 +01005342 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04005343
Daniel Borkmann6f161012018-01-18 01:15:21 +01005344 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5345 smin_val > smax_val || umin_val > umax_val) {
5346 /* Taint dst register if offset had invalid bounds derived from
5347 * e.g. dead branches.
5348 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005349 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01005350 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04005351 }
5352
Edward Creef1174f72017-08-07 15:26:19 +01005353 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5354 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07005355 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5356 __mark_reg_unknown(env, dst_reg);
5357 return 0;
5358 }
5359
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005360 verbose(env,
5361 "R%d 32-bit pointer arithmetic prohibited\n",
5362 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005363 return -EACCES;
5364 }
David S. Millerd1174412017-05-10 11:22:52 -07005365
Joe Stringeraad2eea2018-10-02 13:35:30 -07005366 switch (ptr_reg->type) {
5367 case PTR_TO_MAP_VALUE_OR_NULL:
5368 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5369 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01005370 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07005371 case CONST_PTR_TO_MAP:
Yonghong Song7c696732020-09-08 10:57:02 -07005372 /* smin_val represents the known value */
5373 if (known && smin_val == 0 && opcode == BPF_ADD)
5374 break;
5375 /* fall-through */
Joe Stringeraad2eea2018-10-02 13:35:30 -07005376 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07005377 case PTR_TO_SOCKET:
5378 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005379 case PTR_TO_SOCK_COMMON:
5380 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005381 case PTR_TO_TCP_SOCK:
5382 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07005383 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07005384 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5385 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01005386 return -EACCES;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01005387 case PTR_TO_MAP_VALUE:
5388 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5389 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5390 off_reg == dst_reg ? dst : src);
5391 return -EACCES;
5392 }
5393 /* fall-through */
Joe Stringeraad2eea2018-10-02 13:35:30 -07005394 default:
5395 break;
Edward Creef1174f72017-08-07 15:26:19 +01005396 }
5397
5398 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5399 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04005400 */
Edward Creef1174f72017-08-07 15:26:19 +01005401 dst_reg->type = ptr_reg->type;
5402 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05005403
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005404 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5405 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5406 return -EINVAL;
5407
John Fastabend3f50f132020-03-30 14:36:39 -07005408 /* pointer types do not carry 32-bit bounds at the moment. */
5409 __mark_reg32_unbounded(dst_reg);
5410
Josef Bacik48461132016-09-28 10:54:32 -04005411 switch (opcode) {
5412 case BPF_ADD:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005413 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5414 if (ret < 0) {
5415 verbose(env, "R%d tried to add from different maps or paths\n", dst);
5416 return ret;
5417 }
Edward Creef1174f72017-08-07 15:26:19 +01005418 /* We can take a fixed offset as long as it doesn't overflow
5419 * the s32 'off' field
5420 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005421 if (known && (ptr_reg->off + smin_val ==
5422 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01005423 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01005424 dst_reg->smin_value = smin_ptr;
5425 dst_reg->smax_value = smax_ptr;
5426 dst_reg->umin_value = umin_ptr;
5427 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01005428 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01005429 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01005430 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01005431 break;
5432 }
Edward Creef1174f72017-08-07 15:26:19 +01005433 /* A new variable offset is created. Note that off_reg->off
5434 * == 0, since it's a scalar.
5435 * dst_reg gets the pointer type and since some positive
5436 * integer value was added to the pointer, give it a new 'id'
5437 * if it's a PTR_TO_PACKET.
5438 * this creates a new 'base' pointer, off_reg (variable) gets
5439 * added into the variable offset, and we copy the fixed offset
5440 * from ptr_reg.
5441 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005442 if (signed_add_overflows(smin_ptr, smin_val) ||
5443 signed_add_overflows(smax_ptr, smax_val)) {
5444 dst_reg->smin_value = S64_MIN;
5445 dst_reg->smax_value = S64_MAX;
5446 } else {
5447 dst_reg->smin_value = smin_ptr + smin_val;
5448 dst_reg->smax_value = smax_ptr + smax_val;
5449 }
5450 if (umin_ptr + umin_val < umin_ptr ||
5451 umax_ptr + umax_val < umax_ptr) {
5452 dst_reg->umin_value = 0;
5453 dst_reg->umax_value = U64_MAX;
5454 } else {
5455 dst_reg->umin_value = umin_ptr + umin_val;
5456 dst_reg->umax_value = umax_ptr + umax_val;
5457 }
Edward Creef1174f72017-08-07 15:26:19 +01005458 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5459 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01005460 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005461 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01005462 dst_reg->id = ++env->id_gen;
5463 /* something was added to pkt_ptr, set range to zero */
Daniel Borkmann09625902018-11-01 00:05:52 +01005464 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01005465 }
Josef Bacik48461132016-09-28 10:54:32 -04005466 break;
5467 case BPF_SUB:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005468 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5469 if (ret < 0) {
5470 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5471 return ret;
5472 }
Edward Creef1174f72017-08-07 15:26:19 +01005473 if (dst_reg == off_reg) {
5474 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005475 verbose(env, "R%d tried to subtract pointer from scalar\n",
5476 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005477 return -EACCES;
5478 }
5479 /* We don't allow subtraction from FP, because (according to
5480 * test_verifier.c test "invalid fp arithmetic", JITs might not
5481 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01005482 */
Edward Creef1174f72017-08-07 15:26:19 +01005483 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005484 verbose(env, "R%d subtraction from stack pointer prohibited\n",
5485 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005486 return -EACCES;
5487 }
Edward Creeb03c9f92017-08-07 15:26:36 +01005488 if (known && (ptr_reg->off - smin_val ==
5489 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01005490 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01005491 dst_reg->smin_value = smin_ptr;
5492 dst_reg->smax_value = smax_ptr;
5493 dst_reg->umin_value = umin_ptr;
5494 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01005495 dst_reg->var_off = ptr_reg->var_off;
5496 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01005497 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01005498 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01005499 break;
5500 }
Edward Creef1174f72017-08-07 15:26:19 +01005501 /* A new variable offset is created. If the subtrahend is known
5502 * nonnegative, then any reg->range we had before is still good.
5503 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005504 if (signed_sub_overflows(smin_ptr, smax_val) ||
5505 signed_sub_overflows(smax_ptr, smin_val)) {
5506 /* Overflow possible, we know nothing */
5507 dst_reg->smin_value = S64_MIN;
5508 dst_reg->smax_value = S64_MAX;
5509 } else {
5510 dst_reg->smin_value = smin_ptr - smax_val;
5511 dst_reg->smax_value = smax_ptr - smin_val;
5512 }
5513 if (umin_ptr < umax_val) {
5514 /* Overflow possible, we know nothing */
5515 dst_reg->umin_value = 0;
5516 dst_reg->umax_value = U64_MAX;
5517 } else {
5518 /* Cannot overflow (as long as bounds are consistent) */
5519 dst_reg->umin_value = umin_ptr - umax_val;
5520 dst_reg->umax_value = umax_ptr - umin_val;
5521 }
Edward Creef1174f72017-08-07 15:26:19 +01005522 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5523 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01005524 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005525 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01005526 dst_reg->id = ++env->id_gen;
5527 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01005528 if (smin_val < 0)
Daniel Borkmann09625902018-11-01 00:05:52 +01005529 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01005530 }
5531 break;
5532 case BPF_AND:
5533 case BPF_OR:
5534 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005535 /* bitwise ops on pointers are troublesome, prohibit. */
5536 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5537 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01005538 return -EACCES;
5539 default:
5540 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005541 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5542 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01005543 return -EACCES;
5544 }
5545
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005546 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5547 return -EINVAL;
5548
Edward Creeb03c9f92017-08-07 15:26:36 +01005549 __update_reg_bounds(dst_reg);
5550 __reg_deduce_bounds(dst_reg);
5551 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01005552
5553 /* For unprivileged we require that resulting offset must be in bounds
5554 * in order to be able to sanitize access later on.
5555 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005556 if (!env->bypass_spec_v1) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01005557 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5558 check_map_access(env, dst, dst_reg->off, 1, false)) {
5559 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5560 "prohibited for !root\n", dst);
5561 return -EACCES;
5562 } else if (dst_reg->type == PTR_TO_STACK &&
5563 check_stack_access(env, dst_reg, dst_reg->off +
5564 dst_reg->var_off.value, 1)) {
5565 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5566 "prohibited for !root\n", dst);
5567 return -EACCES;
5568 }
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01005569 }
5570
Edward Creef1174f72017-08-07 15:26:19 +01005571 return 0;
5572}
5573
John Fastabend3f50f132020-03-30 14:36:39 -07005574static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5575 struct bpf_reg_state *src_reg)
5576{
5577 s32 smin_val = src_reg->s32_min_value;
5578 s32 smax_val = src_reg->s32_max_value;
5579 u32 umin_val = src_reg->u32_min_value;
5580 u32 umax_val = src_reg->u32_max_value;
5581
5582 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5583 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5584 dst_reg->s32_min_value = S32_MIN;
5585 dst_reg->s32_max_value = S32_MAX;
5586 } else {
5587 dst_reg->s32_min_value += smin_val;
5588 dst_reg->s32_max_value += smax_val;
5589 }
5590 if (dst_reg->u32_min_value + umin_val < umin_val ||
5591 dst_reg->u32_max_value + umax_val < umax_val) {
5592 dst_reg->u32_min_value = 0;
5593 dst_reg->u32_max_value = U32_MAX;
5594 } else {
5595 dst_reg->u32_min_value += umin_val;
5596 dst_reg->u32_max_value += umax_val;
5597 }
5598}
5599
John Fastabend07cd2632020-03-24 10:38:15 -07005600static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5601 struct bpf_reg_state *src_reg)
5602{
5603 s64 smin_val = src_reg->smin_value;
5604 s64 smax_val = src_reg->smax_value;
5605 u64 umin_val = src_reg->umin_value;
5606 u64 umax_val = src_reg->umax_value;
5607
5608 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5609 signed_add_overflows(dst_reg->smax_value, smax_val)) {
5610 dst_reg->smin_value = S64_MIN;
5611 dst_reg->smax_value = S64_MAX;
5612 } else {
5613 dst_reg->smin_value += smin_val;
5614 dst_reg->smax_value += smax_val;
5615 }
5616 if (dst_reg->umin_value + umin_val < umin_val ||
5617 dst_reg->umax_value + umax_val < umax_val) {
5618 dst_reg->umin_value = 0;
5619 dst_reg->umax_value = U64_MAX;
5620 } else {
5621 dst_reg->umin_value += umin_val;
5622 dst_reg->umax_value += umax_val;
5623 }
John Fastabend3f50f132020-03-30 14:36:39 -07005624}
5625
5626static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5627 struct bpf_reg_state *src_reg)
5628{
5629 s32 smin_val = src_reg->s32_min_value;
5630 s32 smax_val = src_reg->s32_max_value;
5631 u32 umin_val = src_reg->u32_min_value;
5632 u32 umax_val = src_reg->u32_max_value;
5633
5634 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5635 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5636 /* Overflow possible, we know nothing */
5637 dst_reg->s32_min_value = S32_MIN;
5638 dst_reg->s32_max_value = S32_MAX;
5639 } else {
5640 dst_reg->s32_min_value -= smax_val;
5641 dst_reg->s32_max_value -= smin_val;
5642 }
5643 if (dst_reg->u32_min_value < umax_val) {
5644 /* Overflow possible, we know nothing */
5645 dst_reg->u32_min_value = 0;
5646 dst_reg->u32_max_value = U32_MAX;
5647 } else {
5648 /* Cannot overflow (as long as bounds are consistent) */
5649 dst_reg->u32_min_value -= umax_val;
5650 dst_reg->u32_max_value -= umin_val;
5651 }
John Fastabend07cd2632020-03-24 10:38:15 -07005652}
5653
5654static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5655 struct bpf_reg_state *src_reg)
5656{
5657 s64 smin_val = src_reg->smin_value;
5658 s64 smax_val = src_reg->smax_value;
5659 u64 umin_val = src_reg->umin_value;
5660 u64 umax_val = src_reg->umax_value;
5661
5662 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5663 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5664 /* Overflow possible, we know nothing */
5665 dst_reg->smin_value = S64_MIN;
5666 dst_reg->smax_value = S64_MAX;
5667 } else {
5668 dst_reg->smin_value -= smax_val;
5669 dst_reg->smax_value -= smin_val;
5670 }
5671 if (dst_reg->umin_value < umax_val) {
5672 /* Overflow possible, we know nothing */
5673 dst_reg->umin_value = 0;
5674 dst_reg->umax_value = U64_MAX;
5675 } else {
5676 /* Cannot overflow (as long as bounds are consistent) */
5677 dst_reg->umin_value -= umax_val;
5678 dst_reg->umax_value -= umin_val;
5679 }
John Fastabend3f50f132020-03-30 14:36:39 -07005680}
5681
5682static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5683 struct bpf_reg_state *src_reg)
5684{
5685 s32 smin_val = src_reg->s32_min_value;
5686 u32 umin_val = src_reg->u32_min_value;
5687 u32 umax_val = src_reg->u32_max_value;
5688
5689 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5690 /* Ain't nobody got time to multiply that sign */
5691 __mark_reg32_unbounded(dst_reg);
5692 return;
5693 }
5694 /* Both values are positive, so we can work with unsigned and
5695 * copy the result to signed (unless it exceeds S32_MAX).
5696 */
5697 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5698 /* Potential overflow, we know nothing */
5699 __mark_reg32_unbounded(dst_reg);
5700 return;
5701 }
5702 dst_reg->u32_min_value *= umin_val;
5703 dst_reg->u32_max_value *= umax_val;
5704 if (dst_reg->u32_max_value > S32_MAX) {
5705 /* Overflow possible, we know nothing */
5706 dst_reg->s32_min_value = S32_MIN;
5707 dst_reg->s32_max_value = S32_MAX;
5708 } else {
5709 dst_reg->s32_min_value = dst_reg->u32_min_value;
5710 dst_reg->s32_max_value = dst_reg->u32_max_value;
5711 }
John Fastabend07cd2632020-03-24 10:38:15 -07005712}
5713
5714static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5715 struct bpf_reg_state *src_reg)
5716{
5717 s64 smin_val = src_reg->smin_value;
5718 u64 umin_val = src_reg->umin_value;
5719 u64 umax_val = src_reg->umax_value;
5720
John Fastabend07cd2632020-03-24 10:38:15 -07005721 if (smin_val < 0 || dst_reg->smin_value < 0) {
5722 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07005723 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07005724 return;
5725 }
5726 /* Both values are positive, so we can work with unsigned and
5727 * copy the result to signed (unless it exceeds S64_MAX).
5728 */
5729 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5730 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07005731 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07005732 return;
5733 }
5734 dst_reg->umin_value *= umin_val;
5735 dst_reg->umax_value *= umax_val;
5736 if (dst_reg->umax_value > S64_MAX) {
5737 /* Overflow possible, we know nothing */
5738 dst_reg->smin_value = S64_MIN;
5739 dst_reg->smax_value = S64_MAX;
5740 } else {
5741 dst_reg->smin_value = dst_reg->umin_value;
5742 dst_reg->smax_value = dst_reg->umax_value;
5743 }
5744}
5745
John Fastabend3f50f132020-03-30 14:36:39 -07005746static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5747 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07005748{
John Fastabend3f50f132020-03-30 14:36:39 -07005749 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5750 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5751 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5752 s32 smin_val = src_reg->s32_min_value;
5753 u32 umax_val = src_reg->u32_max_value;
5754
5755 /* Assuming scalar64_min_max_and will be called so its safe
5756 * to skip updating register for known 32-bit case.
5757 */
5758 if (src_known && dst_known)
5759 return;
John Fastabend07cd2632020-03-24 10:38:15 -07005760
5761 /* We get our minimum from the var_off, since that's inherently
5762 * bitwise. Our maximum is the minimum of the operands' maxima.
5763 */
John Fastabend3f50f132020-03-30 14:36:39 -07005764 dst_reg->u32_min_value = var32_off.value;
5765 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5766 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5767 /* Lose signed bounds when ANDing negative numbers,
5768 * ain't nobody got time for that.
5769 */
5770 dst_reg->s32_min_value = S32_MIN;
5771 dst_reg->s32_max_value = S32_MAX;
5772 } else {
5773 /* ANDing two positives gives a positive, so safe to
5774 * cast result into s64.
5775 */
5776 dst_reg->s32_min_value = dst_reg->u32_min_value;
5777 dst_reg->s32_max_value = dst_reg->u32_max_value;
5778 }
5779
5780}
5781
5782static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5783 struct bpf_reg_state *src_reg)
5784{
5785 bool src_known = tnum_is_const(src_reg->var_off);
5786 bool dst_known = tnum_is_const(dst_reg->var_off);
5787 s64 smin_val = src_reg->smin_value;
5788 u64 umax_val = src_reg->umax_value;
5789
5790 if (src_known && dst_known) {
5791 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5792 src_reg->var_off.value);
5793 return;
5794 }
5795
5796 /* We get our minimum from the var_off, since that's inherently
5797 * bitwise. Our maximum is the minimum of the operands' maxima.
5798 */
John Fastabend07cd2632020-03-24 10:38:15 -07005799 dst_reg->umin_value = dst_reg->var_off.value;
5800 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5801 if (dst_reg->smin_value < 0 || smin_val < 0) {
5802 /* Lose signed bounds when ANDing negative numbers,
5803 * ain't nobody got time for that.
5804 */
5805 dst_reg->smin_value = S64_MIN;
5806 dst_reg->smax_value = S64_MAX;
5807 } else {
5808 /* ANDing two positives gives a positive, so safe to
5809 * cast result into s64.
5810 */
5811 dst_reg->smin_value = dst_reg->umin_value;
5812 dst_reg->smax_value = dst_reg->umax_value;
5813 }
5814 /* We may learn something more from the var_off */
5815 __update_reg_bounds(dst_reg);
5816}
5817
John Fastabend3f50f132020-03-30 14:36:39 -07005818static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5819 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07005820{
John Fastabend3f50f132020-03-30 14:36:39 -07005821 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5822 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5823 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5824 s32 smin_val = src_reg->smin_value;
5825 u32 umin_val = src_reg->umin_value;
5826
5827 /* Assuming scalar64_min_max_or will be called so it is safe
5828 * to skip updating register for known case.
5829 */
5830 if (src_known && dst_known)
5831 return;
John Fastabend07cd2632020-03-24 10:38:15 -07005832
5833 /* We get our maximum from the var_off, and our minimum is the
5834 * maximum of the operands' minima
5835 */
John Fastabend3f50f132020-03-30 14:36:39 -07005836 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5837 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5838 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5839 /* Lose signed bounds when ORing negative numbers,
5840 * ain't nobody got time for that.
5841 */
5842 dst_reg->s32_min_value = S32_MIN;
5843 dst_reg->s32_max_value = S32_MAX;
5844 } else {
5845 /* ORing two positives gives a positive, so safe to
5846 * cast result into s64.
5847 */
5848 dst_reg->s32_min_value = dst_reg->umin_value;
5849 dst_reg->s32_max_value = dst_reg->umax_value;
5850 }
5851}
5852
5853static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5854 struct bpf_reg_state *src_reg)
5855{
5856 bool src_known = tnum_is_const(src_reg->var_off);
5857 bool dst_known = tnum_is_const(dst_reg->var_off);
5858 s64 smin_val = src_reg->smin_value;
5859 u64 umin_val = src_reg->umin_value;
5860
5861 if (src_known && dst_known) {
5862 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5863 src_reg->var_off.value);
5864 return;
5865 }
5866
5867 /* We get our maximum from the var_off, and our minimum is the
5868 * maximum of the operands' minima
5869 */
John Fastabend07cd2632020-03-24 10:38:15 -07005870 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5871 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5872 if (dst_reg->smin_value < 0 || smin_val < 0) {
5873 /* Lose signed bounds when ORing negative numbers,
5874 * ain't nobody got time for that.
5875 */
5876 dst_reg->smin_value = S64_MIN;
5877 dst_reg->smax_value = S64_MAX;
5878 } else {
5879 /* ORing two positives gives a positive, so safe to
5880 * cast result into s64.
5881 */
5882 dst_reg->smin_value = dst_reg->umin_value;
5883 dst_reg->smax_value = dst_reg->umax_value;
5884 }
5885 /* We may learn something more from the var_off */
5886 __update_reg_bounds(dst_reg);
5887}
5888
Yonghong Song2921c902020-08-24 23:46:08 -07005889static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
5890 struct bpf_reg_state *src_reg)
5891{
5892 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5893 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5894 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5895 s32 smin_val = src_reg->s32_min_value;
5896
5897 /* Assuming scalar64_min_max_xor will be called so it is safe
5898 * to skip updating register for known case.
5899 */
5900 if (src_known && dst_known)
5901 return;
5902
5903 /* We get both minimum and maximum from the var32_off. */
5904 dst_reg->u32_min_value = var32_off.value;
5905 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5906
5907 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
5908 /* XORing two positive sign numbers gives a positive,
5909 * so safe to cast u32 result into s32.
5910 */
5911 dst_reg->s32_min_value = dst_reg->u32_min_value;
5912 dst_reg->s32_max_value = dst_reg->u32_max_value;
5913 } else {
5914 dst_reg->s32_min_value = S32_MIN;
5915 dst_reg->s32_max_value = S32_MAX;
5916 }
5917}
5918
5919static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
5920 struct bpf_reg_state *src_reg)
5921{
5922 bool src_known = tnum_is_const(src_reg->var_off);
5923 bool dst_known = tnum_is_const(dst_reg->var_off);
5924 s64 smin_val = src_reg->smin_value;
5925
5926 if (src_known && dst_known) {
5927 /* dst_reg->var_off.value has been updated earlier */
5928 __mark_reg_known(dst_reg, dst_reg->var_off.value);
5929 return;
5930 }
5931
5932 /* We get both minimum and maximum from the var_off. */
5933 dst_reg->umin_value = dst_reg->var_off.value;
5934 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5935
5936 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
5937 /* XORing two positive sign numbers gives a positive,
5938 * so safe to cast u64 result into s64.
5939 */
5940 dst_reg->smin_value = dst_reg->umin_value;
5941 dst_reg->smax_value = dst_reg->umax_value;
5942 } else {
5943 dst_reg->smin_value = S64_MIN;
5944 dst_reg->smax_value = S64_MAX;
5945 }
5946
5947 __update_reg_bounds(dst_reg);
5948}
5949
John Fastabend3f50f132020-03-30 14:36:39 -07005950static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5951 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07005952{
John Fastabend07cd2632020-03-24 10:38:15 -07005953 /* We lose all sign bit information (except what we can pick
5954 * up from var_off)
5955 */
John Fastabend3f50f132020-03-30 14:36:39 -07005956 dst_reg->s32_min_value = S32_MIN;
5957 dst_reg->s32_max_value = S32_MAX;
5958 /* If we might shift our top bit out, then we know nothing */
5959 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
5960 dst_reg->u32_min_value = 0;
5961 dst_reg->u32_max_value = U32_MAX;
5962 } else {
5963 dst_reg->u32_min_value <<= umin_val;
5964 dst_reg->u32_max_value <<= umax_val;
5965 }
5966}
5967
5968static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5969 struct bpf_reg_state *src_reg)
5970{
5971 u32 umax_val = src_reg->u32_max_value;
5972 u32 umin_val = src_reg->u32_min_value;
5973 /* u32 alu operation will zext upper bits */
5974 struct tnum subreg = tnum_subreg(dst_reg->var_off);
5975
5976 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5977 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
5978 /* Not required but being careful mark reg64 bounds as unknown so
5979 * that we are forced to pick them up from tnum and zext later and
5980 * if some path skips this step we are still safe.
5981 */
5982 __mark_reg64_unbounded(dst_reg);
5983 __update_reg32_bounds(dst_reg);
5984}
5985
5986static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
5987 u64 umin_val, u64 umax_val)
5988{
5989 /* Special case <<32 because it is a common compiler pattern to sign
5990 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
5991 * positive we know this shift will also be positive so we can track
5992 * bounds correctly. Otherwise we lose all sign bit information except
5993 * what we can pick up from var_off. Perhaps we can generalize this
5994 * later to shifts of any length.
5995 */
5996 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
5997 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
5998 else
5999 dst_reg->smax_value = S64_MAX;
6000
6001 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6002 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6003 else
6004 dst_reg->smin_value = S64_MIN;
6005
John Fastabend07cd2632020-03-24 10:38:15 -07006006 /* If we might shift our top bit out, then we know nothing */
6007 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6008 dst_reg->umin_value = 0;
6009 dst_reg->umax_value = U64_MAX;
6010 } else {
6011 dst_reg->umin_value <<= umin_val;
6012 dst_reg->umax_value <<= umax_val;
6013 }
John Fastabend3f50f132020-03-30 14:36:39 -07006014}
6015
6016static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6017 struct bpf_reg_state *src_reg)
6018{
6019 u64 umax_val = src_reg->umax_value;
6020 u64 umin_val = src_reg->umin_value;
6021
6022 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6023 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6024 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6025
John Fastabend07cd2632020-03-24 10:38:15 -07006026 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6027 /* We may learn something more from the var_off */
6028 __update_reg_bounds(dst_reg);
6029}
6030
John Fastabend3f50f132020-03-30 14:36:39 -07006031static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6032 struct bpf_reg_state *src_reg)
6033{
6034 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6035 u32 umax_val = src_reg->u32_max_value;
6036 u32 umin_val = src_reg->u32_min_value;
6037
6038 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6039 * be negative, then either:
6040 * 1) src_reg might be zero, so the sign bit of the result is
6041 * unknown, so we lose our signed bounds
6042 * 2) it's known negative, thus the unsigned bounds capture the
6043 * signed bounds
6044 * 3) the signed bounds cross zero, so they tell us nothing
6045 * about the result
6046 * If the value in dst_reg is known nonnegative, then again the
6047 * unsigned bounts capture the signed bounds.
6048 * Thus, in all cases it suffices to blow away our signed bounds
6049 * and rely on inferring new ones from the unsigned bounds and
6050 * var_off of the result.
6051 */
6052 dst_reg->s32_min_value = S32_MIN;
6053 dst_reg->s32_max_value = S32_MAX;
6054
6055 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6056 dst_reg->u32_min_value >>= umax_val;
6057 dst_reg->u32_max_value >>= umin_val;
6058
6059 __mark_reg64_unbounded(dst_reg);
6060 __update_reg32_bounds(dst_reg);
6061}
6062
John Fastabend07cd2632020-03-24 10:38:15 -07006063static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6064 struct bpf_reg_state *src_reg)
6065{
6066 u64 umax_val = src_reg->umax_value;
6067 u64 umin_val = src_reg->umin_value;
6068
6069 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6070 * be negative, then either:
6071 * 1) src_reg might be zero, so the sign bit of the result is
6072 * unknown, so we lose our signed bounds
6073 * 2) it's known negative, thus the unsigned bounds capture the
6074 * signed bounds
6075 * 3) the signed bounds cross zero, so they tell us nothing
6076 * about the result
6077 * If the value in dst_reg is known nonnegative, then again the
6078 * unsigned bounts capture the signed bounds.
6079 * Thus, in all cases it suffices to blow away our signed bounds
6080 * and rely on inferring new ones from the unsigned bounds and
6081 * var_off of the result.
6082 */
6083 dst_reg->smin_value = S64_MIN;
6084 dst_reg->smax_value = S64_MAX;
6085 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6086 dst_reg->umin_value >>= umax_val;
6087 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006088
6089 /* Its not easy to operate on alu32 bounds here because it depends
6090 * on bits being shifted in. Take easy way out and mark unbounded
6091 * so we can recalculate later from tnum.
6092 */
6093 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006094 __update_reg_bounds(dst_reg);
6095}
6096
John Fastabend3f50f132020-03-30 14:36:39 -07006097static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6098 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006099{
John Fastabend3f50f132020-03-30 14:36:39 -07006100 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07006101
6102 /* Upon reaching here, src_known is true and
6103 * umax_val is equal to umin_val.
6104 */
John Fastabend3f50f132020-03-30 14:36:39 -07006105 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6106 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07006107
John Fastabend3f50f132020-03-30 14:36:39 -07006108 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6109
6110 /* blow away the dst_reg umin_value/umax_value and rely on
6111 * dst_reg var_off to refine the result.
6112 */
6113 dst_reg->u32_min_value = 0;
6114 dst_reg->u32_max_value = U32_MAX;
6115
6116 __mark_reg64_unbounded(dst_reg);
6117 __update_reg32_bounds(dst_reg);
6118}
6119
6120static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6121 struct bpf_reg_state *src_reg)
6122{
6123 u64 umin_val = src_reg->umin_value;
6124
6125 /* Upon reaching here, src_known is true and umax_val is equal
6126 * to umin_val.
6127 */
6128 dst_reg->smin_value >>= umin_val;
6129 dst_reg->smax_value >>= umin_val;
6130
6131 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07006132
6133 /* blow away the dst_reg umin_value/umax_value and rely on
6134 * dst_reg var_off to refine the result.
6135 */
6136 dst_reg->umin_value = 0;
6137 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07006138
6139 /* Its not easy to operate on alu32 bounds here because it depends
6140 * on bits being shifted in from upper 32-bits. Take easy way out
6141 * and mark unbounded so we can recalculate later from tnum.
6142 */
6143 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006144 __update_reg_bounds(dst_reg);
6145}
6146
Jann Horn468f6ea2017-12-18 20:11:56 -08006147/* WARNING: This function does calculations on 64-bit values, but the actual
6148 * execution may occur on 32-bit values. Therefore, things like bitshifts
6149 * need extra checks in the 32-bit case.
6150 */
Edward Creef1174f72017-08-07 15:26:19 +01006151static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6152 struct bpf_insn *insn,
6153 struct bpf_reg_state *dst_reg,
6154 struct bpf_reg_state src_reg)
6155{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006156 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01006157 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08006158 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01006159 s64 smin_val, smax_val;
6160 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006161 s32 s32_min_val, s32_max_val;
6162 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08006163 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006164 u32 dst = insn->dst_reg;
6165 int ret;
John Fastabend3f50f132020-03-30 14:36:39 -07006166 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Jann Hornb7992072018-10-05 18:17:59 +02006167
Edward Creeb03c9f92017-08-07 15:26:36 +01006168 smin_val = src_reg.smin_value;
6169 smax_val = src_reg.smax_value;
6170 umin_val = src_reg.umin_value;
6171 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01006172
John Fastabend3f50f132020-03-30 14:36:39 -07006173 s32_min_val = src_reg.s32_min_value;
6174 s32_max_val = src_reg.s32_max_value;
6175 u32_min_val = src_reg.u32_min_value;
6176 u32_max_val = src_reg.u32_max_value;
6177
6178 if (alu32) {
6179 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006180 if ((src_known &&
6181 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6182 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6183 /* Taint dst register if offset had invalid bounds
6184 * derived from e.g. dead branches.
6185 */
6186 __mark_reg_unknown(env, dst_reg);
6187 return 0;
6188 }
6189 } else {
6190 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006191 if ((src_known &&
6192 (smin_val != smax_val || umin_val != umax_val)) ||
6193 smin_val > smax_val || umin_val > umax_val) {
6194 /* Taint dst register if offset had invalid bounds
6195 * derived from e.g. dead branches.
6196 */
6197 __mark_reg_unknown(env, dst_reg);
6198 return 0;
6199 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01006200 }
6201
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006202 if (!src_known &&
6203 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006204 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006205 return 0;
6206 }
6207
John Fastabend3f50f132020-03-30 14:36:39 -07006208 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6209 * There are two classes of instructions: The first class we track both
6210 * alu32 and alu64 sign/unsigned bounds independently this provides the
6211 * greatest amount of precision when alu operations are mixed with jmp32
6212 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6213 * and BPF_OR. This is possible because these ops have fairly easy to
6214 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6215 * See alu32 verifier tests for examples. The second class of
6216 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6217 * with regards to tracking sign/unsigned bounds because the bits may
6218 * cross subreg boundaries in the alu64 case. When this happens we mark
6219 * the reg unbounded in the subreg bound space and use the resulting
6220 * tnum to calculate an approximation of the sign/unsigned bounds.
6221 */
Edward Creef1174f72017-08-07 15:26:19 +01006222 switch (opcode) {
6223 case BPF_ADD:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006224 ret = sanitize_val_alu(env, insn);
6225 if (ret < 0) {
6226 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6227 return ret;
6228 }
John Fastabend3f50f132020-03-30 14:36:39 -07006229 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006230 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006231 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01006232 break;
6233 case BPF_SUB:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006234 ret = sanitize_val_alu(env, insn);
6235 if (ret < 0) {
6236 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6237 return ret;
6238 }
John Fastabend3f50f132020-03-30 14:36:39 -07006239 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006240 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006241 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04006242 break;
6243 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07006244 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6245 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006246 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006247 break;
6248 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07006249 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6250 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006251 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006252 break;
6253 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07006254 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6255 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006256 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006257 break;
Yonghong Song2921c902020-08-24 23:46:08 -07006258 case BPF_XOR:
6259 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6260 scalar32_min_max_xor(dst_reg, &src_reg);
6261 scalar_min_max_xor(dst_reg, &src_reg);
6262 break;
Josef Bacik48461132016-09-28 10:54:32 -04006263 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006264 if (umax_val >= insn_bitness) {
6265 /* Shifts greater than 31 or 63 are undefined.
6266 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006267 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006268 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006269 break;
6270 }
John Fastabend3f50f132020-03-30 14:36:39 -07006271 if (alu32)
6272 scalar32_min_max_lsh(dst_reg, &src_reg);
6273 else
6274 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006275 break;
6276 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006277 if (umax_val >= insn_bitness) {
6278 /* Shifts greater than 31 or 63 are undefined.
6279 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006280 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006281 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006282 break;
6283 }
John Fastabend3f50f132020-03-30 14:36:39 -07006284 if (alu32)
6285 scalar32_min_max_rsh(dst_reg, &src_reg);
6286 else
6287 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006288 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006289 case BPF_ARSH:
6290 if (umax_val >= insn_bitness) {
6291 /* Shifts greater than 31 or 63 are undefined.
6292 * This includes shifts by a negative number.
6293 */
6294 mark_reg_unknown(env, regs, insn->dst_reg);
6295 break;
6296 }
John Fastabend3f50f132020-03-30 14:36:39 -07006297 if (alu32)
6298 scalar32_min_max_arsh(dst_reg, &src_reg);
6299 else
6300 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006301 break;
Josef Bacik48461132016-09-28 10:54:32 -04006302 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006303 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006304 break;
6305 }
6306
John Fastabend3f50f132020-03-30 14:36:39 -07006307 /* ALU32 ops are zero extended into 64bit register */
6308 if (alu32)
6309 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08006310
John Fastabend294f2fc2020-03-24 10:38:37 -07006311 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01006312 __reg_deduce_bounds(dst_reg);
6313 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006314 return 0;
6315}
6316
6317/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6318 * and var_off.
6319 */
6320static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6321 struct bpf_insn *insn)
6322{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006323 struct bpf_verifier_state *vstate = env->cur_state;
6324 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6325 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01006326 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6327 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006328 int err;
Edward Creef1174f72017-08-07 15:26:19 +01006329
6330 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01006331 src_reg = NULL;
6332 if (dst_reg->type != SCALAR_VALUE)
6333 ptr_reg = dst_reg;
6334 if (BPF_SRC(insn->code) == BPF_X) {
6335 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01006336 if (src_reg->type != SCALAR_VALUE) {
6337 if (dst_reg->type != SCALAR_VALUE) {
6338 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006339 * an arbitrary scalar. Disallow all math except
6340 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01006341 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07006342 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006343 mark_reg_unknown(env, regs, insn->dst_reg);
6344 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01006345 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006346 verbose(env, "R%d pointer %s pointer prohibited\n",
6347 insn->dst_reg,
6348 bpf_alu_string[opcode >> 4]);
6349 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01006350 } else {
6351 /* scalar += pointer
6352 * This is legal, but we have to reverse our
6353 * src/dest handling in computing the range
6354 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006355 err = mark_chain_precision(env, insn->dst_reg);
6356 if (err)
6357 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006358 return adjust_ptr_min_max_vals(env, insn,
6359 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006360 }
6361 } else if (ptr_reg) {
6362 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006363 err = mark_chain_precision(env, insn->src_reg);
6364 if (err)
6365 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006366 return adjust_ptr_min_max_vals(env, insn,
6367 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006368 }
6369 } else {
6370 /* Pretend the src is a reg with a known value, since we only
6371 * need to be able to read from this state.
6372 */
6373 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01006374 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01006375 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006376 if (ptr_reg) /* pointer += K */
6377 return adjust_ptr_min_max_vals(env, insn,
6378 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006379 }
6380
6381 /* Got here implies adding two SCALAR_VALUEs */
6382 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006383 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006384 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01006385 return -EINVAL;
6386 }
6387 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006388 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006389 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01006390 return -EINVAL;
6391 }
6392 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006393}
6394
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006395/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006396static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006397{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006398 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006399 u8 opcode = BPF_OP(insn->code);
6400 int err;
6401
6402 if (opcode == BPF_END || opcode == BPF_NEG) {
6403 if (opcode == BPF_NEG) {
6404 if (BPF_SRC(insn->code) != 0 ||
6405 insn->src_reg != BPF_REG_0 ||
6406 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006407 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006408 return -EINVAL;
6409 }
6410 } else {
6411 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01006412 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6413 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006414 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006415 return -EINVAL;
6416 }
6417 }
6418
6419 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01006420 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006421 if (err)
6422 return err;
6423
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006424 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006425 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006426 insn->dst_reg);
6427 return -EACCES;
6428 }
6429
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006430 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01006431 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006432 if (err)
6433 return err;
6434
6435 } else if (opcode == BPF_MOV) {
6436
6437 if (BPF_SRC(insn->code) == BPF_X) {
6438 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006439 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006440 return -EINVAL;
6441 }
6442
6443 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01006444 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006445 if (err)
6446 return err;
6447 } else {
6448 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006449 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006450 return -EINVAL;
6451 }
6452 }
6453
Arthur Fabrefbeb1602018-07-31 18:17:22 +01006454 /* check dest operand, mark as required later */
6455 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006456 if (err)
6457 return err;
6458
6459 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05006460 struct bpf_reg_state *src_reg = regs + insn->src_reg;
6461 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6462
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006463 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6464 /* case: R1 = R2
6465 * copy register state to dest reg
6466 */
Jiong Wange434b8c2018-12-07 12:16:18 -05006467 *dst_reg = *src_reg;
6468 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01006469 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006470 } else {
Edward Creef1174f72017-08-07 15:26:19 +01006471 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006472 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006473 verbose(env,
6474 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006475 insn->src_reg);
6476 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05006477 } else if (src_reg->type == SCALAR_VALUE) {
6478 *dst_reg = *src_reg;
6479 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01006480 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05006481 } else {
6482 mark_reg_unknown(env, regs,
6483 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006484 }
John Fastabend3f50f132020-03-30 14:36:39 -07006485 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006486 }
6487 } else {
6488 /* case: R = imm
6489 * remember the value we stored into this reg
6490 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01006491 /* clear any state __mark_reg_known doesn't set */
6492 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006493 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08006494 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6495 __mark_reg_known(regs + insn->dst_reg,
6496 insn->imm);
6497 } else {
6498 __mark_reg_known(regs + insn->dst_reg,
6499 (u32)insn->imm);
6500 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006501 }
6502
6503 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006504 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006505 return -EINVAL;
6506
6507 } else { /* all other ALU ops: and, sub, xor, add, ... */
6508
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006509 if (BPF_SRC(insn->code) == BPF_X) {
6510 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006511 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006512 return -EINVAL;
6513 }
6514 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006515 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006516 if (err)
6517 return err;
6518 } else {
6519 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006520 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006521 return -EINVAL;
6522 }
6523 }
6524
6525 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006526 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006527 if (err)
6528 return err;
6529
6530 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6531 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006532 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006533 return -EINVAL;
6534 }
6535
Rabin Vincent229394e82016-01-12 20:17:08 +01006536 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6537 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6538 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6539
6540 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006541 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01006542 return -EINVAL;
6543 }
6544 }
6545
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006546 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01006547 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006548 if (err)
6549 return err;
6550
Edward Creef1174f72017-08-07 15:26:19 +01006551 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006552 }
6553
6554 return 0;
6555}
6556
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006557static void __find_good_pkt_pointers(struct bpf_func_state *state,
6558 struct bpf_reg_state *dst_reg,
6559 enum bpf_reg_type type, u16 new_range)
6560{
6561 struct bpf_reg_state *reg;
6562 int i;
6563
6564 for (i = 0; i < MAX_BPF_REG; i++) {
6565 reg = &state->regs[i];
6566 if (reg->type == type && reg->id == dst_reg->id)
6567 /* keep the maximum range already checked */
6568 reg->range = max(reg->range, new_range);
6569 }
6570
6571 bpf_for_each_spilled_reg(i, state, reg) {
6572 if (!reg)
6573 continue;
6574 if (reg->type == type && reg->id == dst_reg->id)
6575 reg->range = max(reg->range, new_range);
6576 }
6577}
6578
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006579static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006580 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01006581 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006582 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006583{
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006584 u16 new_range;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006585 int i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006586
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006587 if (dst_reg->off < 0 ||
6588 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01006589 /* This doesn't give us any range */
6590 return;
6591
Edward Creeb03c9f92017-08-07 15:26:36 +01006592 if (dst_reg->umax_value > MAX_PACKET_OFF ||
6593 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01006594 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6595 * than pkt_end, but that's because it's also less than pkt.
6596 */
6597 return;
6598
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006599 new_range = dst_reg->off;
6600 if (range_right_open)
6601 new_range--;
6602
6603 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006604 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006605 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006606 *
6607 * r2 = r3;
6608 * r2 += 8;
6609 * if (r2 > pkt_end) goto <handle exception>
6610 * <access okay>
6611 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006612 * r2 = r3;
6613 * r2 += 8;
6614 * if (r2 < pkt_end) goto <access okay>
6615 * <handle exception>
6616 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006617 * Where:
6618 * r2 == dst_reg, pkt_end == src_reg
6619 * r2=pkt(id=n,off=8,r=0)
6620 * r3=pkt(id=n,off=0,r=0)
6621 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006622 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006623 *
6624 * r2 = r3;
6625 * r2 += 8;
6626 * if (pkt_end >= r2) goto <access okay>
6627 * <handle exception>
6628 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006629 * r2 = r3;
6630 * r2 += 8;
6631 * if (pkt_end <= r2) goto <handle exception>
6632 * <access okay>
6633 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006634 * Where:
6635 * pkt_end == dst_reg, r2 == src_reg
6636 * r2=pkt(id=n,off=8,r=0)
6637 * r3=pkt(id=n,off=0,r=0)
6638 *
6639 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006640 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6641 * and [r3, r3 + 8-1) respectively is safe to access depending on
6642 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006643 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006644
Edward Creef1174f72017-08-07 15:26:19 +01006645 /* If our ids match, then we must have the same max_value. And we
6646 * don't care about the other reg's fixed offset, since if it's too big
6647 * the range won't allow anything.
6648 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6649 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006650 for (i = 0; i <= vstate->curframe; i++)
6651 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6652 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006653}
6654
John Fastabend3f50f132020-03-30 14:36:39 -07006655static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006656{
John Fastabend3f50f132020-03-30 14:36:39 -07006657 struct tnum subreg = tnum_subreg(reg->var_off);
6658 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006659
John Fastabend3f50f132020-03-30 14:36:39 -07006660 switch (opcode) {
6661 case BPF_JEQ:
6662 if (tnum_is_const(subreg))
6663 return !!tnum_equals_const(subreg, val);
6664 break;
6665 case BPF_JNE:
6666 if (tnum_is_const(subreg))
6667 return !tnum_equals_const(subreg, val);
6668 break;
6669 case BPF_JSET:
6670 if ((~subreg.mask & subreg.value) & val)
6671 return 1;
6672 if (!((subreg.mask | subreg.value) & val))
6673 return 0;
6674 break;
6675 case BPF_JGT:
6676 if (reg->u32_min_value > val)
6677 return 1;
6678 else if (reg->u32_max_value <= val)
6679 return 0;
6680 break;
6681 case BPF_JSGT:
6682 if (reg->s32_min_value > sval)
6683 return 1;
6684 else if (reg->s32_max_value < sval)
6685 return 0;
6686 break;
6687 case BPF_JLT:
6688 if (reg->u32_max_value < val)
6689 return 1;
6690 else if (reg->u32_min_value >= val)
6691 return 0;
6692 break;
6693 case BPF_JSLT:
6694 if (reg->s32_max_value < sval)
6695 return 1;
6696 else if (reg->s32_min_value >= sval)
6697 return 0;
6698 break;
6699 case BPF_JGE:
6700 if (reg->u32_min_value >= val)
6701 return 1;
6702 else if (reg->u32_max_value < val)
6703 return 0;
6704 break;
6705 case BPF_JSGE:
6706 if (reg->s32_min_value >= sval)
6707 return 1;
6708 else if (reg->s32_max_value < sval)
6709 return 0;
6710 break;
6711 case BPF_JLE:
6712 if (reg->u32_max_value <= val)
6713 return 1;
6714 else if (reg->u32_min_value > val)
6715 return 0;
6716 break;
6717 case BPF_JSLE:
6718 if (reg->s32_max_value <= sval)
6719 return 1;
6720 else if (reg->s32_min_value > sval)
6721 return 0;
6722 break;
Jiong Wang092ed092019-01-26 12:26:01 -05006723 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05006724
John Fastabend3f50f132020-03-30 14:36:39 -07006725 return -1;
6726}
6727
6728
6729static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6730{
6731 s64 sval = (s64)val;
6732
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006733 switch (opcode) {
6734 case BPF_JEQ:
6735 if (tnum_is_const(reg->var_off))
6736 return !!tnum_equals_const(reg->var_off, val);
6737 break;
6738 case BPF_JNE:
6739 if (tnum_is_const(reg->var_off))
6740 return !tnum_equals_const(reg->var_off, val);
6741 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08006742 case BPF_JSET:
6743 if ((~reg->var_off.mask & reg->var_off.value) & val)
6744 return 1;
6745 if (!((reg->var_off.mask | reg->var_off.value) & val))
6746 return 0;
6747 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006748 case BPF_JGT:
6749 if (reg->umin_value > val)
6750 return 1;
6751 else if (reg->umax_value <= val)
6752 return 0;
6753 break;
6754 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006755 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006756 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006757 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006758 return 0;
6759 break;
6760 case BPF_JLT:
6761 if (reg->umax_value < val)
6762 return 1;
6763 else if (reg->umin_value >= val)
6764 return 0;
6765 break;
6766 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006767 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006768 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006769 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006770 return 0;
6771 break;
6772 case BPF_JGE:
6773 if (reg->umin_value >= val)
6774 return 1;
6775 else if (reg->umax_value < val)
6776 return 0;
6777 break;
6778 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006779 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006780 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006781 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006782 return 0;
6783 break;
6784 case BPF_JLE:
6785 if (reg->umax_value <= val)
6786 return 1;
6787 else if (reg->umin_value > val)
6788 return 0;
6789 break;
6790 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006791 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006792 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006793 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006794 return 0;
6795 break;
6796 }
6797
6798 return -1;
6799}
6800
John Fastabend3f50f132020-03-30 14:36:39 -07006801/* compute branch direction of the expression "if (reg opcode val) goto target;"
6802 * and return:
6803 * 1 - branch will be taken and "goto target" will be executed
6804 * 0 - branch will not be taken and fall-through to next insn
6805 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6806 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05006807 */
John Fastabend3f50f132020-03-30 14:36:39 -07006808static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6809 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05006810{
John Fastabendcac616d2020-05-21 13:07:26 -07006811 if (__is_pointer_value(false, reg)) {
6812 if (!reg_type_not_null(reg->type))
6813 return -1;
6814
6815 /* If pointer is valid tests against zero will fail so we can
6816 * use this to direct branch taken.
6817 */
6818 if (val != 0)
6819 return -1;
6820
6821 switch (opcode) {
6822 case BPF_JEQ:
6823 return 0;
6824 case BPF_JNE:
6825 return 1;
6826 default:
6827 return -1;
6828 }
6829 }
Jiong Wang092ed092019-01-26 12:26:01 -05006830
John Fastabend3f50f132020-03-30 14:36:39 -07006831 if (is_jmp32)
6832 return is_branch32_taken(reg, val, opcode);
6833 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02006834}
6835
Josef Bacik48461132016-09-28 10:54:32 -04006836/* Adjusts the register min/max values in the case that the dst_reg is the
6837 * variable register that we are working on, and src_reg is a constant or we're
6838 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01006839 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04006840 */
6841static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07006842 struct bpf_reg_state *false_reg,
6843 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05006844 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04006845{
John Fastabend3f50f132020-03-30 14:36:39 -07006846 struct tnum false_32off = tnum_subreg(false_reg->var_off);
6847 struct tnum false_64off = false_reg->var_off;
6848 struct tnum true_32off = tnum_subreg(true_reg->var_off);
6849 struct tnum true_64off = true_reg->var_off;
6850 s64 sval = (s64)val;
6851 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006852
Edward Creef1174f72017-08-07 15:26:19 +01006853 /* If the dst_reg is a pointer, we can't learn anything about its
6854 * variable offset from the compare (unless src_reg were a pointer into
6855 * the same object, but we don't bother with that.
6856 * Since false_reg and true_reg have the same type by construction, we
6857 * only need to check one of them for pointerness.
6858 */
6859 if (__is_pointer_value(false, false_reg))
6860 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02006861
Josef Bacik48461132016-09-28 10:54:32 -04006862 switch (opcode) {
6863 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04006864 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006865 {
6866 struct bpf_reg_state *reg =
6867 opcode == BPF_JEQ ? true_reg : false_reg;
6868
6869 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6870 * if it is true we know the value for sure. Likewise for
6871 * BPF_JNE.
Josef Bacik48461132016-09-28 10:54:32 -04006872 */
John Fastabend3f50f132020-03-30 14:36:39 -07006873 if (is_jmp32)
6874 __mark_reg32_known(reg, val32);
6875 else
Jiong Wang092ed092019-01-26 12:26:01 -05006876 __mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04006877 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006878 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08006879 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07006880 if (is_jmp32) {
6881 false_32off = tnum_and(false_32off, tnum_const(~val32));
6882 if (is_power_of_2(val32))
6883 true_32off = tnum_or(true_32off,
6884 tnum_const(val32));
6885 } else {
6886 false_64off = tnum_and(false_64off, tnum_const(~val));
6887 if (is_power_of_2(val))
6888 true_64off = tnum_or(true_64off,
6889 tnum_const(val));
6890 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08006891 break;
Josef Bacik48461132016-09-28 10:54:32 -04006892 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006893 case BPF_JGT:
6894 {
John Fastabend3f50f132020-03-30 14:36:39 -07006895 if (is_jmp32) {
6896 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
6897 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
6898
6899 false_reg->u32_max_value = min(false_reg->u32_max_value,
6900 false_umax);
6901 true_reg->u32_min_value = max(true_reg->u32_min_value,
6902 true_umin);
6903 } else {
6904 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
6905 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
6906
6907 false_reg->umax_value = min(false_reg->umax_value, false_umax);
6908 true_reg->umin_value = max(true_reg->umin_value, true_umin);
6909 }
Edward Creeb03c9f92017-08-07 15:26:36 +01006910 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006911 }
Josef Bacik48461132016-09-28 10:54:32 -04006912 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006913 case BPF_JSGT:
6914 {
John Fastabend3f50f132020-03-30 14:36:39 -07006915 if (is_jmp32) {
6916 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
6917 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006918
John Fastabend3f50f132020-03-30 14:36:39 -07006919 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
6920 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
6921 } else {
6922 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
6923 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
6924
6925 false_reg->smax_value = min(false_reg->smax_value, false_smax);
6926 true_reg->smin_value = max(true_reg->smin_value, true_smin);
6927 }
Josef Bacik48461132016-09-28 10:54:32 -04006928 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006929 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006930 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006931 case BPF_JLT:
6932 {
John Fastabend3f50f132020-03-30 14:36:39 -07006933 if (is_jmp32) {
6934 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
6935 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
6936
6937 false_reg->u32_min_value = max(false_reg->u32_min_value,
6938 false_umin);
6939 true_reg->u32_max_value = min(true_reg->u32_max_value,
6940 true_umax);
6941 } else {
6942 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
6943 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
6944
6945 false_reg->umin_value = max(false_reg->umin_value, false_umin);
6946 true_reg->umax_value = min(true_reg->umax_value, true_umax);
6947 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006948 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006949 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006950 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006951 case BPF_JSLT:
6952 {
John Fastabend3f50f132020-03-30 14:36:39 -07006953 if (is_jmp32) {
6954 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
6955 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006956
John Fastabend3f50f132020-03-30 14:36:39 -07006957 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
6958 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
6959 } else {
6960 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
6961 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
6962
6963 false_reg->smin_value = max(false_reg->smin_value, false_smin);
6964 true_reg->smax_value = min(true_reg->smax_value, true_smax);
6965 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006966 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006967 }
Josef Bacik48461132016-09-28 10:54:32 -04006968 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02006969 return;
Josef Bacik48461132016-09-28 10:54:32 -04006970 }
6971
John Fastabend3f50f132020-03-30 14:36:39 -07006972 if (is_jmp32) {
6973 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
6974 tnum_subreg(false_32off));
6975 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
6976 tnum_subreg(true_32off));
6977 __reg_combine_32_into_64(false_reg);
6978 __reg_combine_32_into_64(true_reg);
6979 } else {
6980 false_reg->var_off = false_64off;
6981 true_reg->var_off = true_64off;
6982 __reg_combine_64_into_32(false_reg);
6983 __reg_combine_64_into_32(true_reg);
6984 }
Josef Bacik48461132016-09-28 10:54:32 -04006985}
6986
Edward Creef1174f72017-08-07 15:26:19 +01006987/* Same as above, but for the case that dst_reg holds a constant and src_reg is
6988 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04006989 */
6990static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07006991 struct bpf_reg_state *false_reg,
6992 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05006993 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04006994{
Jann Horn0fc31b12020-03-30 18:03:24 +02006995 /* How can we transform "a <op> b" into "b <op> a"? */
6996 static const u8 opcode_flip[16] = {
6997 /* these stay the same */
6998 [BPF_JEQ >> 4] = BPF_JEQ,
6999 [BPF_JNE >> 4] = BPF_JNE,
7000 [BPF_JSET >> 4] = BPF_JSET,
7001 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7002 [BPF_JGE >> 4] = BPF_JLE,
7003 [BPF_JGT >> 4] = BPF_JLT,
7004 [BPF_JLE >> 4] = BPF_JGE,
7005 [BPF_JLT >> 4] = BPF_JGT,
7006 [BPF_JSGE >> 4] = BPF_JSLE,
7007 [BPF_JSGT >> 4] = BPF_JSLT,
7008 [BPF_JSLE >> 4] = BPF_JSGE,
7009 [BPF_JSLT >> 4] = BPF_JSGT
7010 };
7011 opcode = opcode_flip[opcode >> 4];
7012 /* This uses zero as "not present in table"; luckily the zero opcode,
7013 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01007014 */
Jann Horn0fc31b12020-03-30 18:03:24 +02007015 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07007016 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01007017}
7018
7019/* Regs are known to be equal, so intersect their min/max/var_off */
7020static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7021 struct bpf_reg_state *dst_reg)
7022{
Edward Creeb03c9f92017-08-07 15:26:36 +01007023 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7024 dst_reg->umin_value);
7025 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7026 dst_reg->umax_value);
7027 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7028 dst_reg->smin_value);
7029 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7030 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01007031 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7032 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01007033 /* We might have learned new bounds from the var_off. */
7034 __update_reg_bounds(src_reg);
7035 __update_reg_bounds(dst_reg);
7036 /* We might have learned something about the sign bit. */
7037 __reg_deduce_bounds(src_reg);
7038 __reg_deduce_bounds(dst_reg);
7039 /* We might have learned some bits from the bounds. */
7040 __reg_bound_offset(src_reg);
7041 __reg_bound_offset(dst_reg);
7042 /* Intersecting with the old var_off might have improved our bounds
7043 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7044 * then new var_off is (0; 0x7f...fc) which improves our umax.
7045 */
7046 __update_reg_bounds(src_reg);
7047 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007048}
7049
7050static void reg_combine_min_max(struct bpf_reg_state *true_src,
7051 struct bpf_reg_state *true_dst,
7052 struct bpf_reg_state *false_src,
7053 struct bpf_reg_state *false_dst,
7054 u8 opcode)
7055{
7056 switch (opcode) {
7057 case BPF_JEQ:
7058 __reg_combine_min_max(true_src, true_dst);
7059 break;
7060 case BPF_JNE:
7061 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01007062 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007063 }
Josef Bacik48461132016-09-28 10:54:32 -04007064}
7065
Joe Stringerfd978bf72018-10-02 13:35:35 -07007066static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7067 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07007068 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007069{
Joe Stringer840b9612018-10-02 13:35:32 -07007070 if (reg_type_may_be_null(reg->type) && reg->id == id) {
Edward Creef1174f72017-08-07 15:26:19 +01007071 /* Old offset (both fixed and variable parts) should
7072 * have been known-zero, because we don't allow pointer
7073 * arithmetic on pointers that might be NULL.
7074 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007075 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7076 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01007077 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01007078 __mark_reg_known_zero(reg);
7079 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007080 }
7081 if (is_null) {
7082 reg->type = SCALAR_VALUE;
Joe Stringer840b9612018-10-02 13:35:32 -07007083 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007084 const struct bpf_map *map = reg->map_ptr;
7085
7086 if (map->inner_map_meta) {
Joe Stringer840b9612018-10-02 13:35:32 -07007087 reg->type = CONST_PTR_TO_MAP;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007088 reg->map_ptr = map->inner_map_meta;
7089 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07007090 reg->type = PTR_TO_XDP_SOCK;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007091 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7092 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7093 reg->type = PTR_TO_SOCKET;
Joe Stringer840b9612018-10-02 13:35:32 -07007094 } else {
7095 reg->type = PTR_TO_MAP_VALUE;
7096 }
Joe Stringerc64b7982018-10-02 13:35:33 -07007097 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7098 reg->type = PTR_TO_SOCKET;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08007099 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7100 reg->type = PTR_TO_SOCK_COMMON;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08007101 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7102 reg->type = PTR_TO_TCP_SOCK;
Yonghong Songb121b342020-05-09 10:59:12 -07007103 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7104 reg->type = PTR_TO_BTF_ID;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07007105 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7106 reg->type = PTR_TO_MEM;
Yonghong Songafbf21d2020-07-23 11:41:11 -07007107 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7108 reg->type = PTR_TO_RDONLY_BUF;
7109 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7110 reg->type = PTR_TO_RDWR_BUF;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07007111 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007112 if (is_null) {
7113 /* We don't need id and ref_obj_id from this point
7114 * onwards anymore, thus we should better reset it,
7115 * so that state pruning has chances to take effect.
7116 */
7117 reg->id = 0;
7118 reg->ref_obj_id = 0;
7119 } else if (!reg_may_point_to_spin_lock(reg)) {
7120 /* For not-NULL ptr, reg->ref_obj_id will be reset
7121 * in release_reg_references().
7122 *
7123 * reg->id is still used by spin_lock ptr. Other
7124 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07007125 */
7126 reg->id = 0;
7127 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02007128 }
7129}
7130
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007131static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7132 bool is_null)
7133{
7134 struct bpf_reg_state *reg;
7135 int i;
7136
7137 for (i = 0; i < MAX_BPF_REG; i++)
7138 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7139
7140 bpf_for_each_spilled_reg(i, state, reg) {
7141 if (!reg)
7142 continue;
7143 mark_ptr_or_null_reg(state, reg, id, is_null);
7144 }
7145}
7146
Thomas Graf57a09bf2016-10-18 19:51:19 +02007147/* The logic is similar to find_good_pkt_pointers(), both could eventually
7148 * be folded together at some point.
7149 */
Joe Stringer840b9612018-10-02 13:35:32 -07007150static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7151 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007152{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007153 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007154 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007155 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01007156 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007157 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02007158
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007159 if (ref_obj_id && ref_obj_id == id && is_null)
7160 /* regs[regno] is in the " == NULL" branch.
7161 * No one could have freed the reference state before
7162 * doing the NULL check.
7163 */
7164 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07007165
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007166 for (i = 0; i <= vstate->curframe; i++)
7167 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02007168}
7169
Daniel Borkmann5beca082017-11-01 23:58:10 +01007170static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7171 struct bpf_reg_state *dst_reg,
7172 struct bpf_reg_state *src_reg,
7173 struct bpf_verifier_state *this_branch,
7174 struct bpf_verifier_state *other_branch)
7175{
7176 if (BPF_SRC(insn->code) != BPF_X)
7177 return false;
7178
Jiong Wang092ed092019-01-26 12:26:01 -05007179 /* Pointers are always 64-bit. */
7180 if (BPF_CLASS(insn->code) == BPF_JMP32)
7181 return false;
7182
Daniel Borkmann5beca082017-11-01 23:58:10 +01007183 switch (BPF_OP(insn->code)) {
7184 case BPF_JGT:
7185 if ((dst_reg->type == PTR_TO_PACKET &&
7186 src_reg->type == PTR_TO_PACKET_END) ||
7187 (dst_reg->type == PTR_TO_PACKET_META &&
7188 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7189 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7190 find_good_pkt_pointers(this_branch, dst_reg,
7191 dst_reg->type, false);
7192 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7193 src_reg->type == PTR_TO_PACKET) ||
7194 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7195 src_reg->type == PTR_TO_PACKET_META)) {
7196 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7197 find_good_pkt_pointers(other_branch, src_reg,
7198 src_reg->type, true);
7199 } else {
7200 return false;
7201 }
7202 break;
7203 case BPF_JLT:
7204 if ((dst_reg->type == PTR_TO_PACKET &&
7205 src_reg->type == PTR_TO_PACKET_END) ||
7206 (dst_reg->type == PTR_TO_PACKET_META &&
7207 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7208 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7209 find_good_pkt_pointers(other_branch, dst_reg,
7210 dst_reg->type, true);
7211 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7212 src_reg->type == PTR_TO_PACKET) ||
7213 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7214 src_reg->type == PTR_TO_PACKET_META)) {
7215 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7216 find_good_pkt_pointers(this_branch, src_reg,
7217 src_reg->type, false);
7218 } else {
7219 return false;
7220 }
7221 break;
7222 case BPF_JGE:
7223 if ((dst_reg->type == PTR_TO_PACKET &&
7224 src_reg->type == PTR_TO_PACKET_END) ||
7225 (dst_reg->type == PTR_TO_PACKET_META &&
7226 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7227 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7228 find_good_pkt_pointers(this_branch, dst_reg,
7229 dst_reg->type, true);
7230 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7231 src_reg->type == PTR_TO_PACKET) ||
7232 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7233 src_reg->type == PTR_TO_PACKET_META)) {
7234 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7235 find_good_pkt_pointers(other_branch, src_reg,
7236 src_reg->type, false);
7237 } else {
7238 return false;
7239 }
7240 break;
7241 case BPF_JLE:
7242 if ((dst_reg->type == PTR_TO_PACKET &&
7243 src_reg->type == PTR_TO_PACKET_END) ||
7244 (dst_reg->type == PTR_TO_PACKET_META &&
7245 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7246 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7247 find_good_pkt_pointers(other_branch, dst_reg,
7248 dst_reg->type, false);
7249 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7250 src_reg->type == PTR_TO_PACKET) ||
7251 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7252 src_reg->type == PTR_TO_PACKET_META)) {
7253 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7254 find_good_pkt_pointers(this_branch, src_reg,
7255 src_reg->type, true);
7256 } else {
7257 return false;
7258 }
7259 break;
7260 default:
7261 return false;
7262 }
7263
7264 return true;
7265}
7266
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007267static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007268 struct bpf_insn *insn, int *insn_idx)
7269{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007270 struct bpf_verifier_state *this_branch = env->cur_state;
7271 struct bpf_verifier_state *other_branch;
7272 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007273 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007274 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05007275 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007276 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007277 int err;
7278
Jiong Wang092ed092019-01-26 12:26:01 -05007279 /* Only conditional jumps are expected to reach here. */
7280 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7281 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007282 return -EINVAL;
7283 }
7284
7285 if (BPF_SRC(insn->code) == BPF_X) {
7286 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05007287 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007288 return -EINVAL;
7289 }
7290
7291 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007292 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007293 if (err)
7294 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007295
7296 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007297 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007298 insn->src_reg);
7299 return -EACCES;
7300 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007301 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007302 } else {
7303 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05007304 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007305 return -EINVAL;
7306 }
7307 }
7308
7309 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007310 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007311 if (err)
7312 return err;
7313
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007314 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05007315 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007316
John Fastabend3f50f132020-03-30 14:36:39 -07007317 if (BPF_SRC(insn->code) == BPF_K) {
7318 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7319 } else if (src_reg->type == SCALAR_VALUE &&
7320 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7321 pred = is_branch_taken(dst_reg,
7322 tnum_subreg(src_reg->var_off).value,
7323 opcode,
7324 is_jmp32);
7325 } else if (src_reg->type == SCALAR_VALUE &&
7326 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7327 pred = is_branch_taken(dst_reg,
7328 src_reg->var_off.value,
7329 opcode,
7330 is_jmp32);
7331 }
7332
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007333 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07007334 /* If we get here with a dst_reg pointer type it is because
7335 * above is_branch_taken() special cased the 0 comparison.
7336 */
7337 if (!__is_pointer_value(false, dst_reg))
7338 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007339 if (BPF_SRC(insn->code) == BPF_X && !err)
7340 err = mark_chain_precision(env, insn->src_reg);
7341 if (err)
7342 return err;
7343 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007344 if (pred == 1) {
7345 /* only follow the goto, ignore fall-through */
7346 *insn_idx += insn->off;
7347 return 0;
7348 } else if (pred == 0) {
7349 /* only follow fall-through branch, since
7350 * that's where the program will go
7351 */
7352 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007353 }
7354
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007355 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
7356 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007357 if (!other_branch)
7358 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007359 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007360
Josef Bacik48461132016-09-28 10:54:32 -04007361 /* detect if we are comparing against a constant value so we can adjust
7362 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01007363 * this is only legit if both are scalars (or pointers to the same
7364 * object, I suppose, but we don't support that right now), because
7365 * otherwise the different base pointers mean the offsets aren't
7366 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04007367 */
7368 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05007369 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05007370
Edward Creef1174f72017-08-07 15:26:19 +01007371 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05007372 src_reg->type == SCALAR_VALUE) {
7373 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07007374 (is_jmp32 &&
7375 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007376 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007377 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007378 src_reg->var_off.value,
7379 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05007380 opcode, is_jmp32);
7381 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07007382 (is_jmp32 &&
7383 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007384 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007385 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007386 dst_reg->var_off.value,
7387 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05007388 opcode, is_jmp32);
7389 else if (!is_jmp32 &&
7390 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01007391 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007392 reg_combine_min_max(&other_branch_regs[insn->src_reg],
7393 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007394 src_reg, dst_reg, opcode);
Edward Creef1174f72017-08-07 15:26:19 +01007395 }
7396 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007397 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07007398 dst_reg, insn->imm, (u32)insn->imm,
7399 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04007400 }
7401
Jiong Wang092ed092019-01-26 12:26:01 -05007402 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7403 * NOTE: these optimizations below are related with pointer comparison
7404 * which will never be JMP32.
7405 */
7406 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007407 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07007408 reg_type_may_be_null(dst_reg->type)) {
7409 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02007410 * safe or unknown depending R == 0 or R != 0 conditional.
7411 */
Joe Stringer840b9612018-10-02 13:35:32 -07007412 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7413 opcode == BPF_JNE);
7414 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7415 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007416 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7417 this_branch, other_branch) &&
7418 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007419 verbose(env, "R%d pointer comparison prohibited\n",
7420 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007421 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007422 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007423 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007424 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007425 return 0;
7426}
7427
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007428/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007429static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007430{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007431 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007432 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007433 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007434 int err;
7435
7436 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007437 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007438 return -EINVAL;
7439 }
7440 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007441 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007442 return -EINVAL;
7443 }
7444
Edward Creedc503a82017-08-15 20:34:35 +01007445 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007446 if (err)
7447 return err;
7448
Jakub Kicinski6b173872016-09-21 11:43:59 +01007449 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01007450 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7451
Edward Creef1174f72017-08-07 15:26:19 +01007452 regs[insn->dst_reg].type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01007453 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007454 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01007455 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007456
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007457 map = env->used_maps[aux->map_index];
7458 mark_reg_known_zero(env, regs, insn->dst_reg);
7459 regs[insn->dst_reg].map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007460
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007461 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
7462 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
7463 regs[insn->dst_reg].off = aux->map_off;
7464 if (map_value_has_spin_lock(map))
7465 regs[insn->dst_reg].id = ++env->id_gen;
7466 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7467 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
7468 } else {
7469 verbose(env, "bpf verifier is misconfigured\n");
7470 return -EINVAL;
7471 }
7472
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007473 return 0;
7474}
7475
Daniel Borkmann96be4322015-03-01 12:31:46 +01007476static bool may_access_skb(enum bpf_prog_type type)
7477{
7478 switch (type) {
7479 case BPF_PROG_TYPE_SOCKET_FILTER:
7480 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01007481 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01007482 return true;
7483 default:
7484 return false;
7485 }
7486}
7487
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007488/* verify safety of LD_ABS|LD_IND instructions:
7489 * - they can only appear in the programs where ctx == skb
7490 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7491 * preserve R6-R9, and store return value into R0
7492 *
7493 * Implicit input:
7494 * ctx == skb == R6 == CTX
7495 *
7496 * Explicit input:
7497 * SRC == any register
7498 * IMM == 32-bit immediate
7499 *
7500 * Output:
7501 * R0 - 8/16/32-bit skb data converted to cpu endianness
7502 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007503static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007504{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007505 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007506 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007507 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007508 int i, err;
7509
Udip Pant7e407812020-08-25 16:20:00 -07007510 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007511 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007512 return -EINVAL;
7513 }
7514
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02007515 if (!env->ops->gen_ld_abs) {
7516 verbose(env, "bpf verifier is misconfigured\n");
7517 return -EINVAL;
7518 }
7519
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007520 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07007521 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007522 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007523 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007524 return -EINVAL;
7525 }
7526
7527 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007528 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007529 if (err)
7530 return err;
7531
Joe Stringerfd978bf72018-10-02 13:35:35 -07007532 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7533 * gen_ld_abs() may terminate the program at runtime, leading to
7534 * reference leak.
7535 */
7536 err = check_reference_leak(env);
7537 if (err) {
7538 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7539 return err;
7540 }
7541
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08007542 if (env->cur_state->active_spin_lock) {
7543 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7544 return -EINVAL;
7545 }
7546
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007547 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007548 verbose(env,
7549 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007550 return -EINVAL;
7551 }
7552
7553 if (mode == BPF_IND) {
7554 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01007555 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007556 if (err)
7557 return err;
7558 }
7559
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007560 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7561 if (err < 0)
7562 return err;
7563
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007564 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01007565 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007566 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01007567 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7568 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007569
7570 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01007571 * the value fetched from the packet.
7572 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007573 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007574 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01007575 /* ld_abs load up to 32-bit skb data. */
7576 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007577 return 0;
7578}
7579
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007580static int check_return_code(struct bpf_verifier_env *env)
7581{
brakmo5cf1e912019-05-28 16:59:36 -07007582 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007583 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007584 struct bpf_reg_state *reg;
7585 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07007586 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007587 int err;
7588
KP Singh9e4e01d2020-03-29 01:43:52 +01007589 /* LSM and struct_ops func-ptr's return type could be "void" */
Udip Pant7e407812020-08-25 16:20:00 -07007590 if ((prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7591 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007592 !prog->aux->attach_func_proto->type)
7593 return 0;
7594
7595 /* eBPF calling convetion is such that R0 is used
7596 * to return the value from eBPF program.
7597 * Make sure that it's readable at this time
7598 * of bpf_exit, which means that program wrote
7599 * something into it earlier
7600 */
7601 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7602 if (err)
7603 return err;
7604
7605 if (is_pointer_value(env, BPF_REG_0)) {
7606 verbose(env, "R0 leaks addr as return value\n");
7607 return -EACCES;
7608 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007609
Udip Pant7e407812020-08-25 16:20:00 -07007610 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02007611 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7612 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02007613 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7614 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7615 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7616 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7617 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02007618 range = tnum_range(1, 1);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05007619 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007620 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07007621 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7622 range = tnum_range(0, 3);
7623 enforce_attach_type_range = tnum_range(2, 3);
7624 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05007625 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007626 case BPF_PROG_TYPE_CGROUP_SOCK:
7627 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05007628 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08007629 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07007630 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007631 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07007632 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7633 if (!env->prog->aux->attach_btf_id)
7634 return 0;
7635 range = tnum_const(0);
7636 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07007637 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07007638 switch (env->prog->expected_attach_type) {
7639 case BPF_TRACE_FENTRY:
7640 case BPF_TRACE_FEXIT:
7641 range = tnum_const(0);
7642 break;
7643 case BPF_TRACE_RAW_TP:
7644 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07007645 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02007646 case BPF_TRACE_ITER:
7647 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07007648 default:
7649 return -ENOTSUPP;
7650 }
Yonghong Song15d83c42020-05-09 10:59:00 -07007651 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02007652 case BPF_PROG_TYPE_SK_LOOKUP:
7653 range = tnum_range(SK_DROP, SK_PASS);
7654 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07007655 case BPF_PROG_TYPE_EXT:
7656 /* freplace program can return anything as its return value
7657 * depends on the to-be-replaced kernel func or bpf program.
7658 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007659 default:
7660 return 0;
7661 }
7662
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007663 reg = cur_regs(env) + BPF_REG_0;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007664 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007665 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007666 reg_type_str[reg->type]);
7667 return -EINVAL;
7668 }
7669
7670 if (!tnum_in(range, reg->var_off)) {
brakmo5cf1e912019-05-28 16:59:36 -07007671 char tn_buf[48];
7672
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007673 verbose(env, "At program exit the register R0 ");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007674 if (!tnum_is_unknown(reg->var_off)) {
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007675 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007676 verbose(env, "has value %s", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007677 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007678 verbose(env, "has unknown scalar value");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007679 }
brakmo5cf1e912019-05-28 16:59:36 -07007680 tnum_strn(tn_buf, sizeof(tn_buf), range);
Daniel Borkmann983695f2019-06-07 01:48:57 +02007681 verbose(env, " should have been in %s\n", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007682 return -EINVAL;
7683 }
brakmo5cf1e912019-05-28 16:59:36 -07007684
7685 if (!tnum_is_unknown(enforce_attach_type_range) &&
7686 tnum_in(enforce_attach_type_range, reg->var_off))
7687 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007688 return 0;
7689}
7690
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007691/* non-recursive DFS pseudo code
7692 * 1 procedure DFS-iterative(G,v):
7693 * 2 label v as discovered
7694 * 3 let S be a stack
7695 * 4 S.push(v)
7696 * 5 while S is not empty
7697 * 6 t <- S.pop()
7698 * 7 if t is what we're looking for:
7699 * 8 return t
7700 * 9 for all edges e in G.adjacentEdges(t) do
7701 * 10 if edge e is already labelled
7702 * 11 continue with the next edge
7703 * 12 w <- G.adjacentVertex(t,e)
7704 * 13 if vertex w is not discovered and not explored
7705 * 14 label e as tree-edge
7706 * 15 label w as discovered
7707 * 16 S.push(w)
7708 * 17 continue at 5
7709 * 18 else if vertex w is discovered
7710 * 19 label e as back-edge
7711 * 20 else
7712 * 21 // vertex w is explored
7713 * 22 label e as forward- or cross-edge
7714 * 23 label t as explored
7715 * 24 S.pop()
7716 *
7717 * convention:
7718 * 0x10 - discovered
7719 * 0x11 - discovered and fall-through edge labelled
7720 * 0x12 - discovered and fall-through and branch edges labelled
7721 * 0x20 - explored
7722 */
7723
7724enum {
7725 DISCOVERED = 0x10,
7726 EXPLORED = 0x20,
7727 FALLTHROUGH = 1,
7728 BRANCH = 2,
7729};
7730
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007731static u32 state_htab_size(struct bpf_verifier_env *env)
7732{
7733 return env->prog->len;
7734}
7735
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007736static struct bpf_verifier_state_list **explored_state(
7737 struct bpf_verifier_env *env,
7738 int idx)
7739{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007740 struct bpf_verifier_state *cur = env->cur_state;
7741 struct bpf_func_state *state = cur->frame[cur->curframe];
7742
7743 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007744}
7745
7746static void init_explored_state(struct bpf_verifier_env *env, int idx)
7747{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007748 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007749}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007750
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007751/* t, w, e - match pseudo-code above:
7752 * t - index of current instruction
7753 * w - next instruction
7754 * e - edge
7755 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07007756static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7757 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007758{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007759 int *insn_stack = env->cfg.insn_stack;
7760 int *insn_state = env->cfg.insn_state;
7761
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007762 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7763 return 0;
7764
7765 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7766 return 0;
7767
7768 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08007769 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007770 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007771 return -EINVAL;
7772 }
7773
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007774 if (e == BRANCH)
7775 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007776 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007777
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007778 if (insn_state[w] == 0) {
7779 /* tree-edge */
7780 insn_state[t] = DISCOVERED | e;
7781 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007782 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007783 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007784 insn_stack[env->cfg.cur_stack++] = w;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007785 return 1;
7786 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07007787 if (loop_ok && env->bpf_capable)
Alexei Starovoitov25897262019-06-15 12:12:20 -07007788 return 0;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08007789 verbose_linfo(env, t, "%d: ", t);
7790 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007791 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007792 return -EINVAL;
7793 } else if (insn_state[w] == EXPLORED) {
7794 /* forward- or cross-edge */
7795 insn_state[t] = DISCOVERED | e;
7796 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007797 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007798 return -EFAULT;
7799 }
7800 return 0;
7801}
7802
7803/* non-recursive depth-first-search to detect loops in BPF program
7804 * loop == back-edge in directed graph
7805 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007806static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007807{
7808 struct bpf_insn *insns = env->prog->insnsi;
7809 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007810 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007811 int ret = 0;
7812 int i, t;
7813
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007814 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007815 if (!insn_state)
7816 return -ENOMEM;
7817
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007818 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007819 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07007820 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007821 return -ENOMEM;
7822 }
7823
7824 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
7825 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007826 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007827
7828peek_stack:
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007829 if (env->cfg.cur_stack == 0)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007830 goto check_state;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007831 t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007832
Jiong Wang092ed092019-01-26 12:26:01 -05007833 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
7834 BPF_CLASS(insns[t].code) == BPF_JMP32) {
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007835 u8 opcode = BPF_OP(insns[t].code);
7836
7837 if (opcode == BPF_EXIT) {
7838 goto mark_explored;
7839 } else if (opcode == BPF_CALL) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07007840 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007841 if (ret == 1)
7842 goto peek_stack;
7843 else if (ret < 0)
7844 goto err_free;
Daniel Borkmann07016152016-04-05 22:33:17 +02007845 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007846 init_explored_state(env, t + 1);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08007847 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007848 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07007849 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
7850 env, false);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08007851 if (ret == 1)
7852 goto peek_stack;
7853 else if (ret < 0)
7854 goto err_free;
7855 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007856 } else if (opcode == BPF_JA) {
7857 if (BPF_SRC(insns[t].code) != BPF_K) {
7858 ret = -EINVAL;
7859 goto err_free;
7860 }
7861 /* unconditional jump with single edge */
7862 ret = push_insn(t, t + insns[t].off + 1,
Alexei Starovoitov25897262019-06-15 12:12:20 -07007863 FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007864 if (ret == 1)
7865 goto peek_stack;
7866 else if (ret < 0)
7867 goto err_free;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007868 /* unconditional jmp is not a good pruning point,
7869 * but it's marked, since backtracking needs
7870 * to record jmp history in is_state_visited().
7871 */
7872 init_explored_state(env, t + insns[t].off + 1);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007873 /* tell verifier to check for equivalent states
7874 * after every call and jump
7875 */
Alexei Starovoitovc3de6312015-04-14 15:57:13 -07007876 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007877 init_explored_state(env, t + 1);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007878 } else {
7879 /* conditional jump with two edges */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007880 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07007881 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007882 if (ret == 1)
7883 goto peek_stack;
7884 else if (ret < 0)
7885 goto err_free;
7886
Alexei Starovoitov25897262019-06-15 12:12:20 -07007887 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007888 if (ret == 1)
7889 goto peek_stack;
7890 else if (ret < 0)
7891 goto err_free;
7892 }
7893 } else {
7894 /* all other non-branch instructions with single
7895 * fall-through edge
7896 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07007897 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007898 if (ret == 1)
7899 goto peek_stack;
7900 else if (ret < 0)
7901 goto err_free;
7902 }
7903
7904mark_explored:
7905 insn_state[t] = EXPLORED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007906 if (env->cfg.cur_stack-- <= 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007907 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007908 ret = -EFAULT;
7909 goto err_free;
7910 }
7911 goto peek_stack;
7912
7913check_state:
7914 for (i = 0; i < insn_cnt; i++) {
7915 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007916 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007917 ret = -EINVAL;
7918 goto err_free;
7919 }
7920 }
7921 ret = 0; /* cfg looks good */
7922
7923err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07007924 kvfree(insn_state);
7925 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007926 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007927 return ret;
7928}
7929
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07007930static int check_abnormal_return(struct bpf_verifier_env *env)
7931{
7932 int i;
7933
7934 for (i = 1; i < env->subprog_cnt; i++) {
7935 if (env->subprog_info[i].has_ld_abs) {
7936 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
7937 return -EINVAL;
7938 }
7939 if (env->subprog_info[i].has_tail_call) {
7940 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
7941 return -EINVAL;
7942 }
7943 }
7944 return 0;
7945}
7946
Yonghong Song838e9692018-11-19 15:29:11 -08007947/* The minimum supported BTF func info size */
7948#define MIN_BPF_FUNCINFO_SIZE 8
7949#define MAX_FUNCINFO_REC_SIZE 252
7950
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007951static int check_btf_func(struct bpf_verifier_env *env,
7952 const union bpf_attr *attr,
7953 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08007954{
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07007955 const struct btf_type *type, *func_proto, *ret_type;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08007956 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08007957 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007958 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08007959 struct bpf_func_info_aux *info_aux = NULL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007960 struct bpf_prog *prog;
7961 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08007962 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08007963 u32 prev_offset = 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07007964 bool scalar_return;
Dan Carpentere7ed83d2020-06-04 11:54:36 +03007965 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -08007966
7967 nfuncs = attr->func_info_cnt;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07007968 if (!nfuncs) {
7969 if (check_abnormal_return(env))
7970 return -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08007971 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07007972 }
Yonghong Song838e9692018-11-19 15:29:11 -08007973
7974 if (nfuncs != env->subprog_cnt) {
7975 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
7976 return -EINVAL;
7977 }
7978
7979 urec_size = attr->func_info_rec_size;
7980 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
7981 urec_size > MAX_FUNCINFO_REC_SIZE ||
7982 urec_size % sizeof(u32)) {
7983 verbose(env, "invalid func info rec size %u\n", urec_size);
7984 return -EINVAL;
7985 }
7986
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007987 prog = env->prog;
7988 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08007989
7990 urecord = u64_to_user_ptr(attr->func_info);
7991 min_size = min_t(u32, krec_size, urec_size);
7992
Yonghong Songba64e7d2018-11-24 23:20:44 -08007993 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007994 if (!krecord)
7995 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08007996 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
7997 if (!info_aux)
7998 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08007999
Yonghong Song838e9692018-11-19 15:29:11 -08008000 for (i = 0; i < nfuncs; i++) {
8001 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8002 if (ret) {
8003 if (ret == -E2BIG) {
8004 verbose(env, "nonzero tailing record in func info");
8005 /* set the size kernel expects so loader can zero
8006 * out the rest of the record.
8007 */
8008 if (put_user(min_size, &uattr->func_info_rec_size))
8009 ret = -EFAULT;
8010 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008011 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008012 }
8013
Yonghong Songba64e7d2018-11-24 23:20:44 -08008014 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08008015 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008016 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008017 }
8018
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008019 /* check insn_off */
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008020 ret = -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08008021 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008022 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08008023 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008024 "nonzero insn_off %u for the first func info record",
8025 krecord[i].insn_off);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008026 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008027 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008028 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08008029 verbose(env,
8030 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008031 krecord[i].insn_off, prev_offset);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008032 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008033 }
8034
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008035 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08008036 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008037 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008038 }
8039
8040 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08008041 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008042 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08008043 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08008044 krecord[i].type_id);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008045 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008046 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008047 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008048
8049 func_proto = btf_type_by_id(btf, type->type);
8050 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8051 /* btf_func_check() already verified it during BTF load */
8052 goto err_free;
8053 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8054 scalar_return =
8055 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8056 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8057 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8058 goto err_free;
8059 }
8060 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8061 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8062 goto err_free;
8063 }
8064
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008065 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08008066 urecord += urec_size;
8067 }
8068
Yonghong Songba64e7d2018-11-24 23:20:44 -08008069 prog->aux->func_info = krecord;
8070 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008071 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08008072 return 0;
8073
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008074err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08008075 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008076 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08008077 return ret;
8078}
8079
Yonghong Songba64e7d2018-11-24 23:20:44 -08008080static void adjust_btf_func(struct bpf_verifier_env *env)
8081{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008082 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008083 int i;
8084
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008085 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08008086 return;
8087
8088 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008089 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008090}
8091
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008092#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8093 sizeof(((struct bpf_line_info *)(0))->line_col))
8094#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8095
8096static int check_btf_line(struct bpf_verifier_env *env,
8097 const union bpf_attr *attr,
8098 union bpf_attr __user *uattr)
8099{
8100 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8101 struct bpf_subprog_info *sub;
8102 struct bpf_line_info *linfo;
8103 struct bpf_prog *prog;
8104 const struct btf *btf;
8105 void __user *ulinfo;
8106 int err;
8107
8108 nr_linfo = attr->line_info_cnt;
8109 if (!nr_linfo)
8110 return 0;
8111
8112 rec_size = attr->line_info_rec_size;
8113 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8114 rec_size > MAX_LINEINFO_REC_SIZE ||
8115 rec_size & (sizeof(u32) - 1))
8116 return -EINVAL;
8117
8118 /* Need to zero it in case the userspace may
8119 * pass in a smaller bpf_line_info object.
8120 */
8121 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8122 GFP_KERNEL | __GFP_NOWARN);
8123 if (!linfo)
8124 return -ENOMEM;
8125
8126 prog = env->prog;
8127 btf = prog->aux->btf;
8128
8129 s = 0;
8130 sub = env->subprog_info;
8131 ulinfo = u64_to_user_ptr(attr->line_info);
8132 expected_size = sizeof(struct bpf_line_info);
8133 ncopy = min_t(u32, expected_size, rec_size);
8134 for (i = 0; i < nr_linfo; i++) {
8135 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8136 if (err) {
8137 if (err == -E2BIG) {
8138 verbose(env, "nonzero tailing record in line_info");
8139 if (put_user(expected_size,
8140 &uattr->line_info_rec_size))
8141 err = -EFAULT;
8142 }
8143 goto err_free;
8144 }
8145
8146 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8147 err = -EFAULT;
8148 goto err_free;
8149 }
8150
8151 /*
8152 * Check insn_off to ensure
8153 * 1) strictly increasing AND
8154 * 2) bounded by prog->len
8155 *
8156 * The linfo[0].insn_off == 0 check logically falls into
8157 * the later "missing bpf_line_info for func..." case
8158 * because the first linfo[0].insn_off must be the
8159 * first sub also and the first sub must have
8160 * subprog_info[0].start == 0.
8161 */
8162 if ((i && linfo[i].insn_off <= prev_offset) ||
8163 linfo[i].insn_off >= prog->len) {
8164 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8165 i, linfo[i].insn_off, prev_offset,
8166 prog->len);
8167 err = -EINVAL;
8168 goto err_free;
8169 }
8170
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08008171 if (!prog->insnsi[linfo[i].insn_off].code) {
8172 verbose(env,
8173 "Invalid insn code at line_info[%u].insn_off\n",
8174 i);
8175 err = -EINVAL;
8176 goto err_free;
8177 }
8178
Martin KaFai Lau23127b32018-12-13 10:41:46 -08008179 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8180 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008181 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8182 err = -EINVAL;
8183 goto err_free;
8184 }
8185
8186 if (s != env->subprog_cnt) {
8187 if (linfo[i].insn_off == sub[s].start) {
8188 sub[s].linfo_idx = i;
8189 s++;
8190 } else if (sub[s].start < linfo[i].insn_off) {
8191 verbose(env, "missing bpf_line_info for func#%u\n", s);
8192 err = -EINVAL;
8193 goto err_free;
8194 }
8195 }
8196
8197 prev_offset = linfo[i].insn_off;
8198 ulinfo += rec_size;
8199 }
8200
8201 if (s != env->subprog_cnt) {
8202 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8203 env->subprog_cnt - s, s);
8204 err = -EINVAL;
8205 goto err_free;
8206 }
8207
8208 prog->aux->linfo = linfo;
8209 prog->aux->nr_linfo = nr_linfo;
8210
8211 return 0;
8212
8213err_free:
8214 kvfree(linfo);
8215 return err;
8216}
8217
8218static int check_btf_info(struct bpf_verifier_env *env,
8219 const union bpf_attr *attr,
8220 union bpf_attr __user *uattr)
8221{
8222 struct btf *btf;
8223 int err;
8224
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008225 if (!attr->func_info_cnt && !attr->line_info_cnt) {
8226 if (check_abnormal_return(env))
8227 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008228 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008229 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008230
8231 btf = btf_get_by_fd(attr->prog_btf_fd);
8232 if (IS_ERR(btf))
8233 return PTR_ERR(btf);
8234 env->prog->aux->btf = btf;
8235
8236 err = check_btf_func(env, attr, uattr);
8237 if (err)
8238 return err;
8239
8240 err = check_btf_line(env, attr, uattr);
8241 if (err)
8242 return err;
8243
8244 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008245}
8246
Edward Creef1174f72017-08-07 15:26:19 +01008247/* check %cur's range satisfies %old's */
8248static bool range_within(struct bpf_reg_state *old,
8249 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008250{
Edward Creeb03c9f92017-08-07 15:26:36 +01008251 return old->umin_value <= cur->umin_value &&
8252 old->umax_value >= cur->umax_value &&
8253 old->smin_value <= cur->smin_value &&
8254 old->smax_value >= cur->smax_value;
Edward Creef1174f72017-08-07 15:26:19 +01008255}
8256
8257/* Maximum number of register states that can exist at once */
8258#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8259struct idpair {
8260 u32 old;
8261 u32 cur;
8262};
8263
8264/* If in the old state two registers had the same id, then they need to have
8265 * the same id in the new state as well. But that id could be different from
8266 * the old state, so we need to track the mapping from old to new ids.
8267 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8268 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8269 * regs with a different old id could still have new id 9, we don't care about
8270 * that.
8271 * So we look through our idmap to see if this old id has been seen before. If
8272 * so, we require the new id to match; otherwise, we add the id pair to the map.
8273 */
8274static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
8275{
8276 unsigned int i;
8277
8278 for (i = 0; i < ID_MAP_SIZE; i++) {
8279 if (!idmap[i].old) {
8280 /* Reached an empty slot; haven't seen this id before */
8281 idmap[i].old = old_id;
8282 idmap[i].cur = cur_id;
8283 return true;
8284 }
8285 if (idmap[i].old == old_id)
8286 return idmap[i].cur == cur_id;
8287 }
8288 /* We ran out of idmap slots, which should be impossible */
8289 WARN_ON_ONCE(1);
8290 return false;
8291}
8292
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008293static void clean_func_state(struct bpf_verifier_env *env,
8294 struct bpf_func_state *st)
8295{
8296 enum bpf_reg_liveness live;
8297 int i, j;
8298
8299 for (i = 0; i < BPF_REG_FP; i++) {
8300 live = st->regs[i].live;
8301 /* liveness must not touch this register anymore */
8302 st->regs[i].live |= REG_LIVE_DONE;
8303 if (!(live & REG_LIVE_READ))
8304 /* since the register is unused, clear its state
8305 * to make further comparison simpler
8306 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01008307 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008308 }
8309
8310 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
8311 live = st->stack[i].spilled_ptr.live;
8312 /* liveness must not touch this stack slot anymore */
8313 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
8314 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01008315 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008316 for (j = 0; j < BPF_REG_SIZE; j++)
8317 st->stack[i].slot_type[j] = STACK_INVALID;
8318 }
8319 }
8320}
8321
8322static void clean_verifier_state(struct bpf_verifier_env *env,
8323 struct bpf_verifier_state *st)
8324{
8325 int i;
8326
8327 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
8328 /* all regs in this state in all frames were already marked */
8329 return;
8330
8331 for (i = 0; i <= st->curframe; i++)
8332 clean_func_state(env, st->frame[i]);
8333}
8334
8335/* the parentage chains form a tree.
8336 * the verifier states are added to state lists at given insn and
8337 * pushed into state stack for future exploration.
8338 * when the verifier reaches bpf_exit insn some of the verifer states
8339 * stored in the state lists have their final liveness state already,
8340 * but a lot of states will get revised from liveness point of view when
8341 * the verifier explores other branches.
8342 * Example:
8343 * 1: r0 = 1
8344 * 2: if r1 == 100 goto pc+1
8345 * 3: r0 = 2
8346 * 4: exit
8347 * when the verifier reaches exit insn the register r0 in the state list of
8348 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8349 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8350 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8351 *
8352 * Since the verifier pushes the branch states as it sees them while exploring
8353 * the program the condition of walking the branch instruction for the second
8354 * time means that all states below this branch were already explored and
8355 * their final liveness markes are already propagated.
8356 * Hence when the verifier completes the search of state list in is_state_visited()
8357 * we can call this clean_live_states() function to mark all liveness states
8358 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8359 * will not be used.
8360 * This function also clears the registers and stack for states that !READ
8361 * to simplify state merging.
8362 *
8363 * Important note here that walking the same branch instruction in the callee
8364 * doesn't meant that the states are DONE. The verifier has to compare
8365 * the callsites
8366 */
8367static void clean_live_states(struct bpf_verifier_env *env, int insn,
8368 struct bpf_verifier_state *cur)
8369{
8370 struct bpf_verifier_state_list *sl;
8371 int i;
8372
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008373 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008374 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07008375 if (sl->state.branches)
8376 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008377 if (sl->state.insn_idx != insn ||
8378 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008379 goto next;
8380 for (i = 0; i <= cur->curframe; i++)
8381 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
8382 goto next;
8383 clean_verifier_state(env, &sl->state);
8384next:
8385 sl = sl->next;
8386 }
8387}
8388
Edward Creef1174f72017-08-07 15:26:19 +01008389/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01008390static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8391 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01008392{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008393 bool equal;
8394
Edward Creedc503a82017-08-15 20:34:35 +01008395 if (!(rold->live & REG_LIVE_READ))
8396 /* explored state didn't use this */
8397 return true;
8398
Edward Cree679c7822018-08-22 20:02:19 +01008399 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008400
8401 if (rold->type == PTR_TO_STACK)
8402 /* two stack pointers are equal only if they're pointing to
8403 * the same stack frame, since fp-8 in foo != fp-8 in bar
8404 */
8405 return equal && rold->frameno == rcur->frameno;
8406
8407 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01008408 return true;
8409
8410 if (rold->type == NOT_INIT)
8411 /* explored state can't have used this */
8412 return true;
8413 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008414 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008415 switch (rold->type) {
8416 case SCALAR_VALUE:
8417 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008418 if (!rold->precise && !rcur->precise)
8419 return true;
Edward Creef1174f72017-08-07 15:26:19 +01008420 /* new val must satisfy old val knowledge */
8421 return range_within(rold, rcur) &&
8422 tnum_in(rold->var_off, rcur->var_off);
8423 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08008424 /* We're trying to use a pointer in place of a scalar.
8425 * Even if the scalar was unbounded, this could lead to
8426 * pointer leaks because scalars are allowed to leak
8427 * while pointers are not. We could make this safe in
8428 * special cases if root is calling us, but it's
8429 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01008430 */
Jann Horn179d1c52017-12-18 20:11:59 -08008431 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008432 }
8433 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01008434 /* If the new min/max/var_off satisfy the old ones and
8435 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008436 * 'id' is not compared, since it's only used for maps with
8437 * bpf_spin_lock inside map element and in such cases if
8438 * the rest of the prog is valid for one map element then
8439 * it's valid for all map elements regardless of the key
8440 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01008441 */
8442 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8443 range_within(rold, rcur) &&
8444 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01008445 case PTR_TO_MAP_VALUE_OR_NULL:
8446 /* a PTR_TO_MAP_VALUE could be safe to use as a
8447 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8448 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8449 * checked, doing so could have affected others with the same
8450 * id, and we can't check for that because we lost the id when
8451 * we converted to a PTR_TO_MAP_VALUE.
8452 */
8453 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8454 return false;
8455 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8456 return false;
8457 /* Check our ids match any regs they're supposed to */
8458 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02008459 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01008460 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02008461 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01008462 return false;
8463 /* We must have at least as much range as the old ptr
8464 * did, so that any accesses which were safe before are
8465 * still safe. This is true even if old range < old off,
8466 * since someone could have accessed through (ptr - k), or
8467 * even done ptr -= k in a register, to get a safe access.
8468 */
8469 if (rold->range > rcur->range)
8470 return false;
8471 /* If the offsets don't match, we can't trust our alignment;
8472 * nor can we be sure that we won't fall out of range.
8473 */
8474 if (rold->off != rcur->off)
8475 return false;
8476 /* id relations must be preserved */
8477 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8478 return false;
8479 /* new val must satisfy old val knowledge */
8480 return range_within(rold, rcur) &&
8481 tnum_in(rold->var_off, rcur->var_off);
8482 case PTR_TO_CTX:
8483 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01008484 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07008485 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07008486 case PTR_TO_SOCKET:
8487 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08008488 case PTR_TO_SOCK_COMMON:
8489 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08008490 case PTR_TO_TCP_SOCK:
8491 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07008492 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01008493 /* Only valid matches are exact, which memcmp() above
8494 * would have accepted
8495 */
8496 default:
8497 /* Don't know what's going on, just say it's not safe */
8498 return false;
8499 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008500
Edward Creef1174f72017-08-07 15:26:19 +01008501 /* Shouldn't get here; if we do, say it's not safe */
8502 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008503 return false;
8504}
8505
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008506static bool stacksafe(struct bpf_func_state *old,
8507 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008508 struct idpair *idmap)
8509{
8510 int i, spi;
8511
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008512 /* walk slots of the explored stack and ignore any additional
8513 * slots in the current stack, since explored(safe) state
8514 * didn't use them
8515 */
8516 for (i = 0; i < old->allocated_stack; i++) {
8517 spi = i / BPF_REG_SIZE;
8518
Alexei Starovoitovb2339202018-12-13 11:42:31 -08008519 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8520 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008521 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +00008522 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -08008523 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008524
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008525 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8526 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -08008527
8528 /* explored stack has more populated slots than current stack
8529 * and these slots were used
8530 */
8531 if (i >= cur->allocated_stack)
8532 return false;
8533
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008534 /* if old state was safe with misc data in the stack
8535 * it will be safe with zero-initialized stack.
8536 * The opposite is not true
8537 */
8538 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8539 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8540 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008541 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8542 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8543 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -07008544 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008545 * this verifier states are not equivalent,
8546 * return false to continue verification of this path
8547 */
8548 return false;
8549 if (i % BPF_REG_SIZE)
8550 continue;
8551 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8552 continue;
8553 if (!regsafe(&old->stack[spi].spilled_ptr,
8554 &cur->stack[spi].spilled_ptr,
8555 idmap))
8556 /* when explored and current stack slot are both storing
8557 * spilled registers, check that stored pointers types
8558 * are the same as well.
8559 * Ex: explored safe path could have stored
8560 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8561 * but current path has stored:
8562 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8563 * such verifier states are not equivalent.
8564 * return false to continue verification of this path
8565 */
8566 return false;
8567 }
8568 return true;
8569}
8570
Joe Stringerfd978bf72018-10-02 13:35:35 -07008571static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8572{
8573 if (old->acquired_refs != cur->acquired_refs)
8574 return false;
8575 return !memcmp(old->refs, cur->refs,
8576 sizeof(*old->refs) * old->acquired_refs);
8577}
8578
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008579/* compare two verifier states
8580 *
8581 * all states stored in state_list are known to be valid, since
8582 * verifier reached 'bpf_exit' instruction through them
8583 *
8584 * this function is called when verifier exploring different branches of
8585 * execution popped from the state stack. If it sees an old state that has
8586 * more strict register state and more strict stack state then this execution
8587 * branch doesn't need to be explored further, since verifier already
8588 * concluded that more strict state leads to valid finish.
8589 *
8590 * Therefore two states are equivalent if register state is more conservative
8591 * and explored stack state is more conservative than the current one.
8592 * Example:
8593 * explored current
8594 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8595 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8596 *
8597 * In other words if current stack state (one being explored) has more
8598 * valid slots than old one that already passed validation, it means
8599 * the verifier can stop exploring and conclude that current state is valid too
8600 *
8601 * Similarly with registers. If explored state has register type as invalid
8602 * whereas register type in current state is meaningful, it means that
8603 * the current state will reach 'bpf_exit' instruction safely
8604 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008605static bool func_states_equal(struct bpf_func_state *old,
8606 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008607{
Edward Creef1174f72017-08-07 15:26:19 +01008608 struct idpair *idmap;
8609 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008610 int i;
8611
Edward Creef1174f72017-08-07 15:26:19 +01008612 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8613 /* If we failed to allocate the idmap, just say it's not safe */
8614 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008615 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008616
8617 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +01008618 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +01008619 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008620 }
8621
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008622 if (!stacksafe(old, cur, idmap))
8623 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -07008624
8625 if (!refsafe(old, cur))
8626 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +01008627 ret = true;
8628out_free:
8629 kfree(idmap);
8630 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008631}
8632
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008633static bool states_equal(struct bpf_verifier_env *env,
8634 struct bpf_verifier_state *old,
8635 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +01008636{
Edward Creedc503a82017-08-15 20:34:35 +01008637 int i;
8638
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008639 if (old->curframe != cur->curframe)
8640 return false;
8641
Daniel Borkmann979d63d2019-01-03 00:58:34 +01008642 /* Verification state from speculative execution simulation
8643 * must never prune a non-speculative execution one.
8644 */
8645 if (old->speculative && !cur->speculative)
8646 return false;
8647
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008648 if (old->active_spin_lock != cur->active_spin_lock)
8649 return false;
8650
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008651 /* for states to be equal callsites have to be the same
8652 * and all frame states need to be equivalent
8653 */
8654 for (i = 0; i <= old->curframe; i++) {
8655 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8656 return false;
8657 if (!func_states_equal(old->frame[i], cur->frame[i]))
8658 return false;
8659 }
8660 return true;
8661}
8662
Jiong Wang5327ed32019-05-24 23:25:12 +01008663/* Return 0 if no propagation happened. Return negative error code if error
8664 * happened. Otherwise, return the propagated bit.
8665 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008666static int propagate_liveness_reg(struct bpf_verifier_env *env,
8667 struct bpf_reg_state *reg,
8668 struct bpf_reg_state *parent_reg)
8669{
Jiong Wang5327ed32019-05-24 23:25:12 +01008670 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8671 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008672 int err;
8673
Jiong Wang5327ed32019-05-24 23:25:12 +01008674 /* When comes here, read flags of PARENT_REG or REG could be any of
8675 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8676 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8677 */
8678 if (parent_flag == REG_LIVE_READ64 ||
8679 /* Or if there is no read flag from REG. */
8680 !flag ||
8681 /* Or if the read flag from REG is the same as PARENT_REG. */
8682 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008683 return 0;
8684
Jiong Wang5327ed32019-05-24 23:25:12 +01008685 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008686 if (err)
8687 return err;
8688
Jiong Wang5327ed32019-05-24 23:25:12 +01008689 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008690}
8691
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008692/* A write screens off any subsequent reads; but write marks come from the
8693 * straight-line code between a state and its parent. When we arrive at an
8694 * equivalent state (jump target or such) we didn't arrive by the straight-line
8695 * code, so read marks in the state must propagate to the parent regardless
8696 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +01008697 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008698 */
8699static int propagate_liveness(struct bpf_verifier_env *env,
8700 const struct bpf_verifier_state *vstate,
8701 struct bpf_verifier_state *vparent)
8702{
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008703 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008704 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008705 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008706
8707 if (vparent->curframe != vstate->curframe) {
8708 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8709 vparent->curframe, vstate->curframe);
8710 return -EFAULT;
8711 }
Edward Creedc503a82017-08-15 20:34:35 +01008712 /* Propagate read liveness of registers... */
8713 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -07008714 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008715 parent = vparent->frame[frame];
8716 state = vstate->frame[frame];
8717 parent_reg = parent->regs;
8718 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -07008719 /* We don't need to worry about FP liveness, it's read-only */
8720 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008721 err = propagate_liveness_reg(env, &state_reg[i],
8722 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +01008723 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008724 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +01008725 if (err == REG_LIVE_READ64)
8726 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +01008727 }
Edward Creedc503a82017-08-15 20:34:35 +01008728
Jiong Wang1b04aee2019-04-12 22:59:34 +01008729 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008730 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8731 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008732 parent_reg = &parent->stack[i].spilled_ptr;
8733 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008734 err = propagate_liveness_reg(env, state_reg,
8735 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +01008736 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008737 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008738 }
Edward Creedc503a82017-08-15 20:34:35 +01008739 }
Jiong Wang5327ed32019-05-24 23:25:12 +01008740 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01008741}
8742
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07008743/* find precise scalars in the previous equivalent state and
8744 * propagate them into the current state
8745 */
8746static int propagate_precision(struct bpf_verifier_env *env,
8747 const struct bpf_verifier_state *old)
8748{
8749 struct bpf_reg_state *state_reg;
8750 struct bpf_func_state *state;
8751 int i, err = 0;
8752
8753 state = old->frame[old->curframe];
8754 state_reg = state->regs;
8755 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8756 if (state_reg->type != SCALAR_VALUE ||
8757 !state_reg->precise)
8758 continue;
8759 if (env->log.level & BPF_LOG_LEVEL2)
8760 verbose(env, "propagating r%d\n", i);
8761 err = mark_chain_precision(env, i);
8762 if (err < 0)
8763 return err;
8764 }
8765
8766 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8767 if (state->stack[i].slot_type[0] != STACK_SPILL)
8768 continue;
8769 state_reg = &state->stack[i].spilled_ptr;
8770 if (state_reg->type != SCALAR_VALUE ||
8771 !state_reg->precise)
8772 continue;
8773 if (env->log.level & BPF_LOG_LEVEL2)
8774 verbose(env, "propagating fp%d\n",
8775 (-i - 1) * BPF_REG_SIZE);
8776 err = mark_chain_precision_stack(env, i);
8777 if (err < 0)
8778 return err;
8779 }
8780 return 0;
8781}
8782
Alexei Starovoitov25897262019-06-15 12:12:20 -07008783static bool states_maybe_looping(struct bpf_verifier_state *old,
8784 struct bpf_verifier_state *cur)
8785{
8786 struct bpf_func_state *fold, *fcur;
8787 int i, fr = cur->curframe;
8788
8789 if (old->curframe != fr)
8790 return false;
8791
8792 fold = old->frame[fr];
8793 fcur = cur->frame[fr];
8794 for (i = 0; i < MAX_BPF_REG; i++)
8795 if (memcmp(&fold->regs[i], &fcur->regs[i],
8796 offsetof(struct bpf_reg_state, parent)))
8797 return false;
8798 return true;
8799}
8800
8801
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008802static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008803{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008804 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008805 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +01008806 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08008807 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -07008808 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008809
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008810 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008811 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008812 /* this 'insn_idx' instruction wasn't marked, so we will not
8813 * be doing state search here
8814 */
8815 return 0;
8816
Alexei Starovoitov25897262019-06-15 12:12:20 -07008817 /* bpf progs typically have pruning point every 4 instructions
8818 * http://vger.kernel.org/bpfconf2019.html#session-1
8819 * Do not add new state for future pruning if the verifier hasn't seen
8820 * at least 2 jumps and at least 8 instructions.
8821 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8822 * In tests that amounts to up to 50% reduction into total verifier
8823 * memory consumption and 20% verifier time speedup.
8824 */
8825 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
8826 env->insn_processed - env->prev_insn_processed >= 8)
8827 add_new_state = true;
8828
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008829 pprev = explored_state(env, insn_idx);
8830 sl = *pprev;
8831
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008832 clean_live_states(env, insn_idx, cur);
8833
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008834 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008835 states_cnt++;
8836 if (sl->state.insn_idx != insn_idx)
8837 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -07008838 if (sl->state.branches) {
8839 if (states_maybe_looping(&sl->state, cur) &&
8840 states_equal(env, &sl->state, cur)) {
8841 verbose_linfo(env, insn_idx, "; ");
8842 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
8843 return -EINVAL;
8844 }
8845 /* if the verifier is processing a loop, avoid adding new state
8846 * too often, since different loop iterations have distinct
8847 * states and may not help future pruning.
8848 * This threshold shouldn't be too low to make sure that
8849 * a loop with large bound will be rejected quickly.
8850 * The most abusive loop will be:
8851 * r1 += 1
8852 * if r1 < 1000000 goto pc-2
8853 * 1M insn_procssed limit / 100 == 10k peak states.
8854 * This threshold shouldn't be too high either, since states
8855 * at the end of the loop are likely to be useful in pruning.
8856 */
8857 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
8858 env->insn_processed - env->prev_insn_processed < 100)
8859 add_new_state = false;
8860 goto miss;
8861 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008862 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008863 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008864 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +01008865 * prune the search.
8866 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +01008867 * If we have any write marks in env->cur_state, they
8868 * will prevent corresponding reads in the continuation
8869 * from reaching our parent (an explored_state). Our
8870 * own state will get the read marks recorded, but
8871 * they'll be immediately forgotten as we're pruning
8872 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008873 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008874 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07008875
8876 /* if previous state reached the exit with precision and
8877 * current state is equivalent to it (except precsion marks)
8878 * the precision needs to be propagated back in
8879 * the current state.
8880 */
8881 err = err ? : push_jmp_history(env, cur);
8882 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008883 if (err)
8884 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008885 return 1;
Edward Creedc503a82017-08-15 20:34:35 +01008886 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07008887miss:
8888 /* when new state is not going to be added do not increase miss count.
8889 * Otherwise several loop iterations will remove the state
8890 * recorded earlier. The goal of these heuristics is to have
8891 * states from some iterations of the loop (some in the beginning
8892 * and some at the end) to help pruning.
8893 */
8894 if (add_new_state)
8895 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008896 /* heuristic to determine whether this state is beneficial
8897 * to keep checking from state equivalence point of view.
8898 * Higher numbers increase max_states_per_insn and verification time,
8899 * but do not meaningfully decrease insn_processed.
8900 */
8901 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
8902 /* the state is unlikely to be useful. Remove it to
8903 * speed up verification
8904 */
8905 *pprev = sl->next;
8906 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07008907 u32 br = sl->state.branches;
8908
8909 WARN_ONCE(br,
8910 "BUG live_done but branches_to_explore %d\n",
8911 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008912 free_verifier_state(&sl->state, false);
8913 kfree(sl);
8914 env->peak_states--;
8915 } else {
8916 /* cannot free this state, since parentage chain may
8917 * walk it later. Add it for free_list instead to
8918 * be freed at the end of verification
8919 */
8920 sl->next = env->free_list;
8921 env->free_list = sl;
8922 }
8923 sl = *pprev;
8924 continue;
8925 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008926next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008927 pprev = &sl->next;
8928 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008929 }
8930
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008931 if (env->max_states_per_insn < states_cnt)
8932 env->max_states_per_insn = states_cnt;
8933
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07008934 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008935 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08008936
Alexei Starovoitov25897262019-06-15 12:12:20 -07008937 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008938 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -07008939
8940 /* There were no equivalent states, remember the current one.
8941 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008942 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -07008943 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008944 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -07008945 * again on the way to bpf_exit.
8946 * When looping the sl->state.branches will be > 0 and this state
8947 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008948 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008949 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008950 if (!new_sl)
8951 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008952 env->total_states++;
8953 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -07008954 env->prev_jmps_processed = env->jmps_processed;
8955 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008956
8957 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +01008958 new = &new_sl->state;
8959 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07008960 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +01008961 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07008962 kfree(new_sl);
8963 return err;
8964 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008965 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -07008966 WARN_ONCE(new->branches != 1,
8967 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008968
Alexei Starovoitov25897262019-06-15 12:12:20 -07008969 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008970 cur->first_insn_idx = insn_idx;
8971 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008972 new_sl->next = *explored_state(env, insn_idx);
8973 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -08008974 /* connect new state to parentage chain. Current frame needs all
8975 * registers connected. Only r6 - r9 of the callers are alive (pushed
8976 * to the stack implicitly by JITs) so in callers' frames connect just
8977 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
8978 * the state of the call instruction (with WRITTEN set), and r0 comes
8979 * from callee with its full parentage chain, anyway.
8980 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +01008981 /* clear write marks in current state: the writes we did are not writes
8982 * our child did, so they don't screen off its reads from us.
8983 * (There are no read marks in current state, because reads always mark
8984 * their parent and current state never has children yet. Only
8985 * explored_states can get read marks.)
8986 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -07008987 for (j = 0; j <= cur->curframe; j++) {
8988 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
8989 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
8990 for (i = 0; i < BPF_REG_FP; i++)
8991 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
8992 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008993
8994 /* all stack frames are accessible from callee, clear them all */
8995 for (j = 0; j <= cur->curframe; j++) {
8996 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +01008997 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008998
Edward Cree679c7822018-08-22 20:02:19 +01008999 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009000 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01009001 frame->stack[i].spilled_ptr.parent =
9002 &newframe->stack[i].spilled_ptr;
9003 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009004 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009005 return 0;
9006}
9007
Joe Stringerc64b7982018-10-02 13:35:33 -07009008/* Return true if it's OK to have the same insn return a different type. */
9009static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9010{
9011 switch (type) {
9012 case PTR_TO_CTX:
9013 case PTR_TO_SOCKET:
9014 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08009015 case PTR_TO_SOCK_COMMON:
9016 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08009017 case PTR_TO_TCP_SOCK:
9018 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07009019 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -07009020 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07009021 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -07009022 return false;
9023 default:
9024 return true;
9025 }
9026}
9027
9028/* If an instruction was previously used with particular pointer types, then we
9029 * need to be careful to avoid cases such as the below, where it may be ok
9030 * for one branch accessing the pointer, but not ok for the other branch:
9031 *
9032 * R1 = sock_ptr
9033 * goto X;
9034 * ...
9035 * R1 = some_other_valid_ptr;
9036 * goto X;
9037 * ...
9038 * R2 = *(u32 *)(R1 + 0);
9039 */
9040static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9041{
9042 return src != prev && (!reg_type_mismatch_ok(src) ||
9043 !reg_type_mismatch_ok(prev));
9044}
9045
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009046static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009047{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07009048 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009049 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009050 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009051 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009052 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009053 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009054 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009055
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009056 for (;;) {
9057 struct bpf_insn *insn;
9058 u8 class;
9059 int err;
9060
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009061 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009062 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009063 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009064 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009065 return -EFAULT;
9066 }
9067
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009068 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009069 class = BPF_CLASS(insn->code);
9070
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009071 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009072 verbose(env,
9073 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009074 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009075 return -E2BIG;
9076 }
9077
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009078 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009079 if (err < 0)
9080 return err;
9081 if (err == 1) {
9082 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009083 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009084 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009085 verbose(env, "\nfrom %d to %d%s: safe\n",
9086 env->prev_insn_idx, env->insn_idx,
9087 env->cur_state->speculative ?
9088 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009089 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009090 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009091 }
9092 goto process_bpf_exit;
9093 }
9094
Alexei Starovoitovc3494802018-12-03 22:46:04 -08009095 if (signal_pending(current))
9096 return -EAGAIN;
9097
Daniel Borkmann3c2ce602017-05-18 03:00:06 +02009098 if (need_resched())
9099 cond_resched();
9100
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009101 if (env->log.level & BPF_LOG_LEVEL2 ||
9102 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9103 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009104 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -07009105 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009106 verbose(env, "\nfrom %d to %d%s:",
9107 env->prev_insn_idx, env->insn_idx,
9108 env->cur_state->speculative ?
9109 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009110 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009111 do_print_state = false;
9112 }
9113
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009114 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01009115 const struct bpf_insn_cbs cbs = {
9116 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +01009117 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +01009118 };
9119
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009120 verbose_linfo(env, env->insn_idx, "; ");
9121 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +01009122 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009123 }
9124
Jakub Kicinskicae19272017-12-27 18:39:05 -08009125 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009126 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9127 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -08009128 if (err)
9129 return err;
9130 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +01009131
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009132 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009133 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009134 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -07009135
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009136 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07009137 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009138 if (err)
9139 return err;
9140
9141 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009142 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009143
9144 /* check for reserved fields is already done */
9145
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009146 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01009147 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009148 if (err)
9149 return err;
9150
Edward Creedc503a82017-08-15 20:34:35 +01009151 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009152 if (err)
9153 return err;
9154
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -07009155 src_reg_type = regs[insn->src_reg].type;
9156
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009157 /* check that memory (src_reg + off) is readable,
9158 * the state of dst_reg will be updated by this func
9159 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009160 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9161 insn->off, BPF_SIZE(insn->code),
9162 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009163 if (err)
9164 return err;
9165
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009166 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009167
9168 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009169 /* saw a valid insn
9170 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009171 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009172 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009173 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009174
Joe Stringerc64b7982018-10-02 13:35:33 -07009175 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009176 /* ABuser program is trying to use the same insn
9177 * dst_reg = *(u32*) (src_reg + off)
9178 * with different pointer types:
9179 * src_reg == ctx in one branch and
9180 * src_reg == stack|map in some other branch.
9181 * Reject it.
9182 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009183 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009184 return -EINVAL;
9185 }
9186
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009187 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009188 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009189
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009190 if (BPF_MODE(insn->code) == BPF_XADD) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009191 err = check_xadd(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009192 if (err)
9193 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009194 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009195 continue;
9196 }
9197
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009198 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01009199 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009200 if (err)
9201 return err;
9202 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01009203 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009204 if (err)
9205 return err;
9206
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009207 dst_reg_type = regs[insn->dst_reg].type;
9208
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009209 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009210 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9211 insn->off, BPF_SIZE(insn->code),
9212 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009213 if (err)
9214 return err;
9215
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009216 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009217
9218 if (*prev_dst_type == NOT_INIT) {
9219 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -07009220 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009221 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009222 return -EINVAL;
9223 }
9224
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009225 } else if (class == BPF_ST) {
9226 if (BPF_MODE(insn->code) != BPF_MEM ||
9227 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009228 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009229 return -EINVAL;
9230 }
9231 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01009232 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009233 if (err)
9234 return err;
9235
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01009236 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -07009237 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02009238 insn->dst_reg,
9239 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01009240 return -EACCES;
9241 }
9242
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009243 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009244 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9245 insn->off, BPF_SIZE(insn->code),
9246 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009247 if (err)
9248 return err;
9249
Jiong Wang092ed092019-01-26 12:26:01 -05009250 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009251 u8 opcode = BPF_OP(insn->code);
9252
Alexei Starovoitov25897262019-06-15 12:12:20 -07009253 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009254 if (opcode == BPF_CALL) {
9255 if (BPF_SRC(insn->code) != BPF_K ||
9256 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009257 (insn->src_reg != BPF_REG_0 &&
9258 insn->src_reg != BPF_PSEUDO_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -05009259 insn->dst_reg != BPF_REG_0 ||
9260 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009261 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009262 return -EINVAL;
9263 }
9264
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009265 if (env->cur_state->active_spin_lock &&
9266 (insn->src_reg == BPF_PSEUDO_CALL ||
9267 insn->imm != BPF_FUNC_spin_unlock)) {
9268 verbose(env, "function calls are not allowed while holding a lock\n");
9269 return -EINVAL;
9270 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009271 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009272 err = check_func_call(env, insn, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009273 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009274 err = check_helper_call(env, insn->imm, env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009275 if (err)
9276 return err;
9277
9278 } else if (opcode == BPF_JA) {
9279 if (BPF_SRC(insn->code) != BPF_K ||
9280 insn->imm != 0 ||
9281 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05009282 insn->dst_reg != BPF_REG_0 ||
9283 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009284 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009285 return -EINVAL;
9286 }
9287
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009288 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009289 continue;
9290
9291 } else if (opcode == BPF_EXIT) {
9292 if (BPF_SRC(insn->code) != BPF_K ||
9293 insn->imm != 0 ||
9294 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05009295 insn->dst_reg != BPF_REG_0 ||
9296 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009297 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009298 return -EINVAL;
9299 }
9300
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009301 if (env->cur_state->active_spin_lock) {
9302 verbose(env, "bpf_spin_unlock is missing\n");
9303 return -EINVAL;
9304 }
9305
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009306 if (state->curframe) {
9307 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009308 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009309 if (err)
9310 return err;
9311 do_print_state = true;
9312 continue;
9313 }
9314
Joe Stringerfd978bf72018-10-02 13:35:35 -07009315 err = check_reference_leak(env);
9316 if (err)
9317 return err;
9318
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009319 err = check_return_code(env);
9320 if (err)
9321 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009322process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -07009323 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009324 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07009325 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009326 if (err < 0) {
9327 if (err != -ENOENT)
9328 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009329 break;
9330 } else {
9331 do_print_state = true;
9332 continue;
9333 }
9334 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009335 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009336 if (err)
9337 return err;
9338 }
9339 } else if (class == BPF_LD) {
9340 u8 mode = BPF_MODE(insn->code);
9341
9342 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009343 err = check_ld_abs(env, insn);
9344 if (err)
9345 return err;
9346
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009347 } else if (mode == BPF_IMM) {
9348 err = check_ld_imm(env, insn);
9349 if (err)
9350 return err;
9351
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009352 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009353 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009354 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009355 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009356 return -EINVAL;
9357 }
9358 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009359 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009360 return -EINVAL;
9361 }
9362
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009363 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009364 }
9365
9366 return 0;
9367}
9368
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009369static int check_map_prealloc(struct bpf_map *map)
9370{
9371 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07009372 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9373 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009374 !(map->map_flags & BPF_F_NO_PREALLOC);
9375}
9376
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009377static bool is_tracing_prog_type(enum bpf_prog_type type)
9378{
9379 switch (type) {
9380 case BPF_PROG_TYPE_KPROBE:
9381 case BPF_PROG_TYPE_TRACEPOINT:
9382 case BPF_PROG_TYPE_PERF_EVENT:
9383 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9384 return true;
9385 default:
9386 return false;
9387 }
9388}
9389
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009390static bool is_preallocated_map(struct bpf_map *map)
9391{
9392 if (!check_map_prealloc(map))
9393 return false;
9394 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
9395 return false;
9396 return true;
9397}
9398
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009399static int check_map_prog_compatibility(struct bpf_verifier_env *env,
9400 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009401 struct bpf_prog *prog)
9402
9403{
Udip Pant7e407812020-08-25 16:20:00 -07009404 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009405 /*
9406 * Validate that trace type programs use preallocated hash maps.
9407 *
9408 * For programs attached to PERF events this is mandatory as the
9409 * perf NMI can hit any arbitrary code sequence.
9410 *
9411 * All other trace types using preallocated hash maps are unsafe as
9412 * well because tracepoint or kprobes can be inside locked regions
9413 * of the memory allocator or at a place where a recursion into the
9414 * memory allocator would see inconsistent state.
9415 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01009416 * On RT enabled kernels run-time allocation of all trace type
9417 * programs is strictly prohibited due to lock type constraints. On
9418 * !RT kernels it is allowed for backwards compatibility reasons for
9419 * now, but warnings are emitted so developers are made aware of
9420 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009421 */
Udip Pant7e407812020-08-25 16:20:00 -07009422 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
9423 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009424 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009425 return -EINVAL;
9426 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01009427 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
9428 verbose(env, "trace type programs can only use preallocated hash map\n");
9429 return -EINVAL;
9430 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009431 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9432 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 -07009433 }
Jakub Kicinskia3884572018-01-11 20:29:09 -08009434
Udip Pant7e407812020-08-25 16:20:00 -07009435 if ((is_tracing_prog_type(prog_type) ||
9436 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009437 map_value_has_spin_lock(map)) {
9438 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9439 return -EINVAL;
9440 }
9441
Jakub Kicinskia3884572018-01-11 20:29:09 -08009442 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -07009443 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -08009444 verbose(env, "offload device mismatch between prog and map\n");
9445 return -EINVAL;
9446 }
9447
Martin KaFai Lau85d33df2020-01-08 16:35:05 -08009448 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9449 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9450 return -EINVAL;
9451 }
9452
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -07009453 if (prog->aux->sleepable)
9454 switch (map->map_type) {
9455 case BPF_MAP_TYPE_HASH:
9456 case BPF_MAP_TYPE_LRU_HASH:
9457 case BPF_MAP_TYPE_ARRAY:
9458 if (!is_preallocated_map(map)) {
9459 verbose(env,
9460 "Sleepable programs can only use preallocated hash maps\n");
9461 return -EINVAL;
9462 }
9463 break;
9464 default:
9465 verbose(env,
9466 "Sleepable programs can only use array and hash maps\n");
9467 return -EINVAL;
9468 }
9469
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009470 return 0;
9471}
9472
Roman Gushchinb741f162018-09-28 14:45:43 +00009473static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9474{
9475 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9476 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9477}
9478
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009479/* look for pseudo eBPF instructions that access map FDs and
9480 * replace them with actual map pointers
9481 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009482static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009483{
9484 struct bpf_insn *insn = env->prog->insnsi;
9485 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009486 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009487
Daniel Borkmannf1f77142017-01-13 23:38:15 +01009488 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +01009489 if (err)
9490 return err;
9491
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009492 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009493 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009494 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009495 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009496 return -EINVAL;
9497 }
9498
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009499 if (BPF_CLASS(insn->code) == BPF_STX &&
9500 ((BPF_MODE(insn->code) != BPF_MEM &&
9501 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009502 verbose(env, "BPF_STX uses reserved fields\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009503 return -EINVAL;
9504 }
9505
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009506 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009507 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009508 struct bpf_map *map;
9509 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009510 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009511
9512 if (i == insn_cnt - 1 || insn[1].code != 0 ||
9513 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9514 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009515 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009516 return -EINVAL;
9517 }
9518
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009519 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009520 /* valid generic load 64-bit imm */
9521 goto next_insn;
9522
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009523 /* In final convert_pseudo_ld_imm64() step, this is
9524 * converted into regular 64-bit imm load insn.
9525 */
9526 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9527 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9528 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9529 insn[1].imm != 0)) {
9530 verbose(env,
9531 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009532 return -EINVAL;
9533 }
9534
Daniel Borkmann20182392019-03-04 21:08:53 +01009535 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +01009536 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009537 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009538 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +01009539 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009540 return PTR_ERR(map);
9541 }
9542
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009543 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009544 if (err) {
9545 fdput(f);
9546 return err;
9547 }
9548
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009549 aux = &env->insn_aux_data[i];
9550 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9551 addr = (unsigned long)map;
9552 } else {
9553 u32 off = insn[1].imm;
9554
9555 if (off >= BPF_MAX_VAR_OFF) {
9556 verbose(env, "direct value offset of %u is not allowed\n", off);
9557 fdput(f);
9558 return -EINVAL;
9559 }
9560
9561 if (!map->ops->map_direct_value_addr) {
9562 verbose(env, "no direct value access support for this map type\n");
9563 fdput(f);
9564 return -EINVAL;
9565 }
9566
9567 err = map->ops->map_direct_value_addr(map, &addr, off);
9568 if (err) {
9569 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9570 map->value_size, off);
9571 fdput(f);
9572 return err;
9573 }
9574
9575 aux->map_off = off;
9576 addr += off;
9577 }
9578
9579 insn[0].imm = (u32)addr;
9580 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009581
9582 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009583 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009584 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009585 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009586 fdput(f);
9587 goto next_insn;
9588 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009589 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009590
9591 if (env->used_map_cnt >= MAX_USED_MAPS) {
9592 fdput(f);
9593 return -E2BIG;
9594 }
9595
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009596 /* hold the map. If the program is rejected by verifier,
9597 * the map will be released by release_maps() or it
9598 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -07009599 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009600 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -08009601 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009602
9603 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -07009604 env->used_maps[env->used_map_cnt++] = map;
9605
Roman Gushchinb741f162018-09-28 14:45:43 +00009606 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +01009607 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +00009608 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -07009609 fdput(f);
9610 return -EBUSY;
9611 }
9612
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009613 fdput(f);
9614next_insn:
9615 insn++;
9616 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +01009617 continue;
9618 }
9619
9620 /* Basic sanity check before we invest more work here. */
9621 if (!bpf_opcode_in_insntable(insn->code)) {
9622 verbose(env, "unknown opcode %02x\n", insn->code);
9623 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009624 }
9625 }
9626
9627 /* now all pseudo BPF_LD_IMM64 instructions load valid
9628 * 'struct bpf_map *' into a register instead of user map_fd.
9629 * These pointers will be used later by verifier to validate map access.
9630 */
9631 return 0;
9632}
9633
9634/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009635static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009636{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +01009637 __bpf_free_used_maps(env->prog->aux, env->used_maps,
9638 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009639}
9640
9641/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009642static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009643{
9644 struct bpf_insn *insn = env->prog->insnsi;
9645 int insn_cnt = env->prog->len;
9646 int i;
9647
9648 for (i = 0; i < insn_cnt; i++, insn++)
9649 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9650 insn->src_reg = 0;
9651}
9652
Alexei Starovoitov80419022017-03-15 18:26:41 -07009653/* single env->prog->insni[off] instruction was replaced with the range
9654 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9655 * [0, off) and [off, end) to new locations, so the patched range stays zero
9656 */
Jiong Wangb325fbc2019-05-24 23:25:13 +01009657static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9658 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -07009659{
9660 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009661 struct bpf_insn *insn = new_prog->insnsi;
9662 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009663 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -07009664
Jiong Wangb325fbc2019-05-24 23:25:13 +01009665 /* aux info at OFF always needs adjustment, no matter fast path
9666 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9667 * original insn at old prog.
9668 */
9669 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9670
Alexei Starovoitov80419022017-03-15 18:26:41 -07009671 if (cnt == 1)
9672 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009673 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -07009674 new_data = vzalloc(array_size(prog_len,
9675 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -07009676 if (!new_data)
9677 return -ENOMEM;
9678 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9679 memcpy(new_data + off + cnt - 1, old_data + off,
9680 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +01009681 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009682 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009683 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9684 }
Alexei Starovoitov80419022017-03-15 18:26:41 -07009685 env->insn_aux_data = new_data;
9686 vfree(old_data);
9687 return 0;
9688}
9689
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009690static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9691{
9692 int i;
9693
9694 if (len == 1)
9695 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -04009696 /* NOTE: fake 'exit' subprog should be updated as well. */
9697 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +00009698 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009699 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -04009700 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009701 }
9702}
9703
Maciej Fijalkowskia748c692020-09-16 23:10:05 +02009704static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
9705{
9706 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
9707 int i, sz = prog->aux->size_poke_tab;
9708 struct bpf_jit_poke_descriptor *desc;
9709
9710 for (i = 0; i < sz; i++) {
9711 desc = &tab[i];
9712 desc->insn_idx += len - 1;
9713 }
9714}
9715
Alexei Starovoitov80419022017-03-15 18:26:41 -07009716static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
9717 const struct bpf_insn *patch, u32 len)
9718{
9719 struct bpf_prog *new_prog;
9720
9721 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -07009722 if (IS_ERR(new_prog)) {
9723 if (PTR_ERR(new_prog) == -ERANGE)
9724 verbose(env,
9725 "insn %d cannot be patched due to 16-bit range\n",
9726 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -07009727 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -07009728 }
Jiong Wangb325fbc2019-05-24 23:25:13 +01009729 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -07009730 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009731 adjust_subprog_starts(env, off, len);
Maciej Fijalkowskia748c692020-09-16 23:10:05 +02009732 adjust_poke_descs(new_prog, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -07009733 return new_prog;
9734}
9735
Jakub Kicinski52875a02019-01-22 22:45:20 -08009736static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
9737 u32 off, u32 cnt)
9738{
9739 int i, j;
9740
9741 /* find first prog starting at or after off (first to remove) */
9742 for (i = 0; i < env->subprog_cnt; i++)
9743 if (env->subprog_info[i].start >= off)
9744 break;
9745 /* find first prog starting at or after off + cnt (first to stay) */
9746 for (j = i; j < env->subprog_cnt; j++)
9747 if (env->subprog_info[j].start >= off + cnt)
9748 break;
9749 /* if j doesn't start exactly at off + cnt, we are just removing
9750 * the front of previous prog
9751 */
9752 if (env->subprog_info[j].start != off + cnt)
9753 j--;
9754
9755 if (j > i) {
9756 struct bpf_prog_aux *aux = env->prog->aux;
9757 int move;
9758
9759 /* move fake 'exit' subprog as well */
9760 move = env->subprog_cnt + 1 - j;
9761
9762 memmove(env->subprog_info + i,
9763 env->subprog_info + j,
9764 sizeof(*env->subprog_info) * move);
9765 env->subprog_cnt -= j - i;
9766
9767 /* remove func_info */
9768 if (aux->func_info) {
9769 move = aux->func_info_cnt - j;
9770
9771 memmove(aux->func_info + i,
9772 aux->func_info + j,
9773 sizeof(*aux->func_info) * move);
9774 aux->func_info_cnt -= j - i;
9775 /* func_info->insn_off is set after all code rewrites,
9776 * in adjust_btf_func() - no need to adjust
9777 */
9778 }
9779 } else {
9780 /* convert i from "first prog to remove" to "first to adjust" */
9781 if (env->subprog_info[i].start == off)
9782 i++;
9783 }
9784
9785 /* update fake 'exit' subprog as well */
9786 for (; i <= env->subprog_cnt; i++)
9787 env->subprog_info[i].start -= cnt;
9788
9789 return 0;
9790}
9791
9792static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
9793 u32 cnt)
9794{
9795 struct bpf_prog *prog = env->prog;
9796 u32 i, l_off, l_cnt, nr_linfo;
9797 struct bpf_line_info *linfo;
9798
9799 nr_linfo = prog->aux->nr_linfo;
9800 if (!nr_linfo)
9801 return 0;
9802
9803 linfo = prog->aux->linfo;
9804
9805 /* find first line info to remove, count lines to be removed */
9806 for (i = 0; i < nr_linfo; i++)
9807 if (linfo[i].insn_off >= off)
9808 break;
9809
9810 l_off = i;
9811 l_cnt = 0;
9812 for (; i < nr_linfo; i++)
9813 if (linfo[i].insn_off < off + cnt)
9814 l_cnt++;
9815 else
9816 break;
9817
9818 /* First live insn doesn't match first live linfo, it needs to "inherit"
9819 * last removed linfo. prog is already modified, so prog->len == off
9820 * means no live instructions after (tail of the program was removed).
9821 */
9822 if (prog->len != off && l_cnt &&
9823 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
9824 l_cnt--;
9825 linfo[--i].insn_off = off + cnt;
9826 }
9827
9828 /* remove the line info which refer to the removed instructions */
9829 if (l_cnt) {
9830 memmove(linfo + l_off, linfo + i,
9831 sizeof(*linfo) * (nr_linfo - i));
9832
9833 prog->aux->nr_linfo -= l_cnt;
9834 nr_linfo = prog->aux->nr_linfo;
9835 }
9836
9837 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9838 for (i = l_off; i < nr_linfo; i++)
9839 linfo[i].insn_off -= cnt;
9840
9841 /* fix up all subprogs (incl. 'exit') which start >= off */
9842 for (i = 0; i <= env->subprog_cnt; i++)
9843 if (env->subprog_info[i].linfo_idx > l_off) {
9844 /* program may have started in the removed region but
9845 * may not be fully removed
9846 */
9847 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
9848 env->subprog_info[i].linfo_idx -= l_cnt;
9849 else
9850 env->subprog_info[i].linfo_idx = l_off;
9851 }
9852
9853 return 0;
9854}
9855
9856static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
9857{
9858 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9859 unsigned int orig_prog_len = env->prog->len;
9860 int err;
9861
Jakub Kicinski08ca90a2019-01-22 22:45:24 -08009862 if (bpf_prog_is_dev_bound(env->prog->aux))
9863 bpf_prog_offload_remove_insns(env, off, cnt);
9864
Jakub Kicinski52875a02019-01-22 22:45:20 -08009865 err = bpf_remove_insns(env->prog, off, cnt);
9866 if (err)
9867 return err;
9868
9869 err = adjust_subprog_starts_after_remove(env, off, cnt);
9870 if (err)
9871 return err;
9872
9873 err = bpf_adj_linfo_after_remove(env, off, cnt);
9874 if (err)
9875 return err;
9876
9877 memmove(aux_data + off, aux_data + off + cnt,
9878 sizeof(*aux_data) * (orig_prog_len - off - cnt));
9879
9880 return 0;
9881}
9882
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01009883/* The verifier does more data flow analysis than llvm and will not
9884 * explore branches that are dead at run time. Malicious programs can
9885 * have dead code too. Therefore replace all dead at-run-time code
9886 * with 'ja -1'.
9887 *
9888 * Just nops are not optimal, e.g. if they would sit at the end of the
9889 * program and through another bug we would manage to jump there, then
9890 * we'd execute beyond program memory otherwise. Returning exception
9891 * code also wouldn't work since we can have subprogs where the dead
9892 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009893 */
9894static void sanitize_dead_code(struct bpf_verifier_env *env)
9895{
9896 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01009897 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009898 struct bpf_insn *insn = env->prog->insnsi;
9899 const int insn_cnt = env->prog->len;
9900 int i;
9901
9902 for (i = 0; i < insn_cnt; i++) {
9903 if (aux_data[i].seen)
9904 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01009905 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009906 }
9907}
9908
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08009909static bool insn_is_cond_jump(u8 code)
9910{
9911 u8 op;
9912
Jiong Wang092ed092019-01-26 12:26:01 -05009913 if (BPF_CLASS(code) == BPF_JMP32)
9914 return true;
9915
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08009916 if (BPF_CLASS(code) != BPF_JMP)
9917 return false;
9918
9919 op = BPF_OP(code);
9920 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
9921}
9922
9923static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
9924{
9925 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9926 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9927 struct bpf_insn *insn = env->prog->insnsi;
9928 const int insn_cnt = env->prog->len;
9929 int i;
9930
9931 for (i = 0; i < insn_cnt; i++, insn++) {
9932 if (!insn_is_cond_jump(insn->code))
9933 continue;
9934
9935 if (!aux_data[i + 1].seen)
9936 ja.off = insn->off;
9937 else if (!aux_data[i + 1 + insn->off].seen)
9938 ja.off = 0;
9939 else
9940 continue;
9941
Jakub Kicinski08ca90a2019-01-22 22:45:24 -08009942 if (bpf_prog_is_dev_bound(env->prog->aux))
9943 bpf_prog_offload_replace_insn(env, i, &ja);
9944
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08009945 memcpy(insn, &ja, sizeof(ja));
9946 }
9947}
9948
Jakub Kicinski52875a02019-01-22 22:45:20 -08009949static int opt_remove_dead_code(struct bpf_verifier_env *env)
9950{
9951 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9952 int insn_cnt = env->prog->len;
9953 int i, err;
9954
9955 for (i = 0; i < insn_cnt; i++) {
9956 int j;
9957
9958 j = 0;
9959 while (i + j < insn_cnt && !aux_data[i + j].seen)
9960 j++;
9961 if (!j)
9962 continue;
9963
9964 err = verifier_remove_insns(env, i, j);
9965 if (err)
9966 return err;
9967 insn_cnt = env->prog->len;
9968 }
9969
9970 return 0;
9971}
9972
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -08009973static int opt_remove_nops(struct bpf_verifier_env *env)
9974{
9975 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9976 struct bpf_insn *insn = env->prog->insnsi;
9977 int insn_cnt = env->prog->len;
9978 int i, err;
9979
9980 for (i = 0; i < insn_cnt; i++) {
9981 if (memcmp(&insn[i], &ja, sizeof(ja)))
9982 continue;
9983
9984 err = verifier_remove_insns(env, i, 1);
9985 if (err)
9986 return err;
9987 insn_cnt--;
9988 i--;
9989 }
9990
9991 return 0;
9992}
9993
Jiong Wangd6c23082019-05-24 23:25:18 +01009994static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
9995 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009996{
Jiong Wangd6c23082019-05-24 23:25:18 +01009997 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009998 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +01009999 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010000 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010001 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +010010002 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010003
Jiong Wangd6c23082019-05-24 23:25:18 +010010004 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010005 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +010010006 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10007 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10008 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010009 for (i = 0; i < len; i++) {
10010 int adj_idx = i + delta;
10011 struct bpf_insn insn;
10012
Jiong Wangd6c23082019-05-24 23:25:18 +010010013 insn = insns[adj_idx];
10014 if (!aux[adj_idx].zext_dst) {
10015 u8 code, class;
10016 u32 imm_rnd;
10017
10018 if (!rnd_hi32)
10019 continue;
10020
10021 code = insn.code;
10022 class = BPF_CLASS(code);
10023 if (insn_no_def(&insn))
10024 continue;
10025
10026 /* NOTE: arg "reg" (the fourth one) is only used for
10027 * BPF_STX which has been ruled out in above
10028 * check, it is safe to pass NULL here.
10029 */
10030 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10031 if (class == BPF_LD &&
10032 BPF_MODE(code) == BPF_IMM)
10033 i++;
10034 continue;
10035 }
10036
10037 /* ctx load could be transformed into wider load. */
10038 if (class == BPF_LDX &&
10039 aux[adj_idx].ptr_type == PTR_TO_CTX)
10040 continue;
10041
10042 imm_rnd = get_random_int();
10043 rnd_hi32_patch[0] = insn;
10044 rnd_hi32_patch[1].imm = imm_rnd;
10045 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10046 patch = rnd_hi32_patch;
10047 patch_len = 4;
10048 goto apply_patch_buffer;
10049 }
10050
10051 if (!bpf_jit_needs_zext())
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010052 continue;
10053
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010054 zext_patch[0] = insn;
10055 zext_patch[1].dst_reg = insn.dst_reg;
10056 zext_patch[1].src_reg = insn.dst_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010010057 patch = zext_patch;
10058 patch_len = 2;
10059apply_patch_buffer:
10060 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010061 if (!new_prog)
10062 return -ENOMEM;
10063 env->prog = new_prog;
10064 insns = new_prog->insnsi;
10065 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010010066 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010067 }
10068
10069 return 0;
10070}
10071
Joe Stringerc64b7982018-10-02 13:35:33 -070010072/* convert load instructions that access fields of a context type into a
10073 * sequence of instructions that access fields of the underlying structure:
10074 * struct __sk_buff -> struct sk_buff
10075 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010076 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010077static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010078{
Jakub Kicinski00176a32017-10-16 16:40:54 -070010079 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010080 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010081 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010082 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010083 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010084 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010085 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010086 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010087
Daniel Borkmannb09928b2018-10-24 22:05:49 +020010088 if (ops->gen_prologue || env->seen_direct_write) {
10089 if (!ops->gen_prologue) {
10090 verbose(env, "bpf verifier is misconfigured\n");
10091 return -EINVAL;
10092 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010093 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10094 env->prog);
10095 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010096 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010097 return -EINVAL;
10098 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070010099 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010100 if (!new_prog)
10101 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070010102
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010103 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010104 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010105 }
10106 }
10107
Joe Stringerc64b7982018-10-02 13:35:33 -070010108 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010109 return 0;
10110
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010111 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010112
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010113 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070010114 bpf_convert_ctx_access_t convert_ctx_access;
10115
Daniel Borkmann62c79892017-01-12 11:51:33 +010010116 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10117 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10118 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070010119 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010120 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +010010121 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10122 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10123 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070010124 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010125 type = BPF_WRITE;
10126 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010127 continue;
10128
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070010129 if (type == BPF_WRITE &&
10130 env->insn_aux_data[i + delta].sanitize_stack_off) {
10131 struct bpf_insn patch[] = {
10132 /* Sanitize suspicious stack slot with zero.
10133 * There are no memory dependencies for this store,
10134 * since it's only using frame pointer and immediate
10135 * constant of zero
10136 */
10137 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
10138 env->insn_aux_data[i + delta].sanitize_stack_off,
10139 0),
10140 /* the original STX instruction will immediately
10141 * overwrite the same stack slot with appropriate value
10142 */
10143 *insn,
10144 };
10145
10146 cnt = ARRAY_SIZE(patch);
10147 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10148 if (!new_prog)
10149 return -ENOMEM;
10150
10151 delta += cnt - 1;
10152 env->prog = new_prog;
10153 insn = new_prog->insnsi + i + delta;
10154 continue;
10155 }
10156
Joe Stringerc64b7982018-10-02 13:35:33 -070010157 switch (env->insn_aux_data[i + delta].ptr_type) {
10158 case PTR_TO_CTX:
10159 if (!ops->convert_ctx_access)
10160 continue;
10161 convert_ctx_access = ops->convert_ctx_access;
10162 break;
10163 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080010164 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070010165 convert_ctx_access = bpf_sock_convert_ctx_access;
10166 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080010167 case PTR_TO_TCP_SOCK:
10168 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
10169 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070010170 case PTR_TO_XDP_SOCK:
10171 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
10172 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010173 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080010174 if (type == BPF_READ) {
10175 insn->code = BPF_LDX | BPF_PROBE_MEM |
10176 BPF_SIZE((insn)->code);
10177 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070010178 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010179 verbose(env, "Writes through BTF pointers are not allowed\n");
10180 return -EINVAL;
10181 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010182 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070010183 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010184 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070010185 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010186
Yonghong Song31fd8582017-06-13 15:52:13 -070010187 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010188 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070010189
10190 /* If the read access is a narrower load of the field,
10191 * convert to a 4/8-byte load, to minimum program type specific
10192 * convert_ctx_access changes. If conversion is successful,
10193 * we will apply proper mask to the result.
10194 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020010195 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010196 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
10197 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070010198 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020010199 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070010200
Daniel Borkmannf96da092017-07-02 02:13:27 +020010201 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010202 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020010203 return -EINVAL;
10204 }
10205
10206 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070010207 if (ctx_field_size == 4)
10208 size_code = BPF_W;
10209 else if (ctx_field_size == 8)
10210 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010211
Daniel Borkmannbc231052018-06-02 23:06:39 +020010212 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070010213 insn->code = BPF_LDX | BPF_MEM | size_code;
10214 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020010215
10216 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070010217 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
10218 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020010219 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
10220 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010221 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010222 return -EINVAL;
10223 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020010224
10225 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020010226 u8 shift = bpf_ctx_narrow_access_offset(
10227 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010228 if (ctx_field_size <= 4) {
10229 if (shift)
10230 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
10231 insn->dst_reg,
10232 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070010233 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020010234 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010235 } else {
10236 if (shift)
10237 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
10238 insn->dst_reg,
10239 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070010240 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020010241 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010242 }
Yonghong Song31fd8582017-06-13 15:52:13 -070010243 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010244
Alexei Starovoitov80419022017-03-15 18:26:41 -070010245 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010246 if (!new_prog)
10247 return -ENOMEM;
10248
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010249 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010250
10251 /* keep walking new program and skip insns we just inserted */
10252 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010253 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010254 }
10255
10256 return 0;
10257}
10258
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010259static int jit_subprogs(struct bpf_verifier_env *env)
10260{
10261 struct bpf_prog *prog = env->prog, **func, *tmp;
10262 int i, j, subprog_start, subprog_end = 0, len, subprog;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010263 struct bpf_map *map_ptr;
Daniel Borkmann7105e822017-12-20 13:42:57 +010010264 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010265 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070010266 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010267
Jiong Wangf910cef2018-05-02 16:17:17 -040010268 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010269 return 0;
10270
Daniel Borkmann7105e822017-12-20 13:42:57 +010010271 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010272 if (insn->code != (BPF_JMP | BPF_CALL) ||
10273 insn->src_reg != BPF_PSEUDO_CALL)
10274 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010275 /* Upon error here we cannot fall back to interpreter but
10276 * need a hard reject of the program. Thus -EFAULT is
10277 * propagated in any case.
10278 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010279 subprog = find_subprog(env, i + insn->imm + 1);
10280 if (subprog < 0) {
10281 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10282 i + insn->imm + 1);
10283 return -EFAULT;
10284 }
10285 /* temporarily remember subprog id inside insn instead of
10286 * aux_data, since next loop will split up all insns into funcs
10287 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010288 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010289 /* remember original imm in case JIT fails and fallback
10290 * to interpreter will be needed
10291 */
10292 env->insn_aux_data[i].call_imm = insn->imm;
10293 /* point imm to __bpf_call_base+1 from JITs point of view */
10294 insn->imm = 1;
10295 }
10296
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010297 err = bpf_prog_alloc_jited_linfo(prog);
10298 if (err)
10299 goto out_undo_insn;
10300
10301 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070010302 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010303 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010304 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010305
Jiong Wangf910cef2018-05-02 16:17:17 -040010306 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010307 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040010308 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010309
10310 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080010311 /* BPF_PROG_RUN doesn't call subprogs directly,
10312 * hence main prog stats include the runtime of subprogs.
10313 * subprogs don't have IDs and not reachable via prog_get_next_id
10314 * func[i]->aux->stats will never be accessed and stays NULL
10315 */
10316 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010317 if (!func[i])
10318 goto out_free;
10319 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
10320 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010010321 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010322 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010010323 if (bpf_prog_calc_tag(func[i]))
10324 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010325 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080010326 func[i]->aux->func_idx = i;
10327 /* the btf and func_info will be freed only at prog->aux */
10328 func[i]->aux->btf = prog->aux->btf;
10329 func[i]->aux->func_info = prog->aux->func_info;
10330
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010331 for (j = 0; j < prog->aux->size_poke_tab; j++) {
10332 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
10333 int ret;
10334
10335 if (!(insn_idx >= subprog_start &&
10336 insn_idx <= subprog_end))
10337 continue;
10338
10339 ret = bpf_jit_add_poke_descriptor(func[i],
10340 &prog->aux->poke_tab[j]);
10341 if (ret < 0) {
10342 verbose(env, "adding tail call poke descriptor failed\n");
10343 goto out_free;
10344 }
10345
10346 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
10347
10348 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
10349 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
10350 if (ret < 0) {
10351 verbose(env, "tracking tail call prog failed\n");
10352 goto out_free;
10353 }
10354 }
10355
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010356 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10357 * Long term would need debug info to populate names
10358 */
10359 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040010360 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010361 func[i]->jit_requested = 1;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010362 func[i]->aux->linfo = prog->aux->linfo;
10363 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
10364 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
10365 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070010366 num_exentries = 0;
10367 insn = func[i]->insnsi;
10368 for (j = 0; j < func[i]->len; j++, insn++) {
10369 if (BPF_CLASS(insn->code) == BPF_LDX &&
10370 BPF_MODE(insn->code) == BPF_PROBE_MEM)
10371 num_exentries++;
10372 }
10373 func[i]->aux->num_exentries = num_exentries;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +020010374 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010375 func[i] = bpf_int_jit_compile(func[i]);
10376 if (!func[i]->jited) {
10377 err = -ENOTSUPP;
10378 goto out_free;
10379 }
10380 cond_resched();
10381 }
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010382
10383 /* Untrack main program's aux structs so that during map_poke_run()
10384 * we will not stumble upon the unfilled poke descriptors; each
10385 * of the main program's poke descs got distributed across subprogs
10386 * and got tracked onto map, so we are sure that none of them will
10387 * be missed after the operation below
10388 */
10389 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10390 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10391
10392 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
10393 }
10394
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010395 /* at this point all bpf functions were successfully JITed
10396 * now populate all bpf_calls with correct addresses and
10397 * run last pass of JIT
10398 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010399 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010400 insn = func[i]->insnsi;
10401 for (j = 0; j < func[i]->len; j++, insn++) {
10402 if (insn->code != (BPF_JMP | BPF_CALL) ||
10403 insn->src_reg != BPF_PSEUDO_CALL)
10404 continue;
10405 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +090010406 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
10407 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010408 }
Sandipan Das2162fed2018-05-24 12:26:45 +053010409
10410 /* we use the aux data to keep a list of the start addresses
10411 * of the JITed images for each function in the program
10412 *
10413 * for some architectures, such as powerpc64, the imm field
10414 * might not be large enough to hold the offset of the start
10415 * address of the callee's JITed image from __bpf_call_base
10416 *
10417 * in such cases, we can lookup the start address of a callee
10418 * by using its subprog id, available from the off field of
10419 * the call instruction, as an index for this list
10420 */
10421 func[i]->aux->func = func;
10422 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010423 }
Jiong Wangf910cef2018-05-02 16:17:17 -040010424 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010425 old_bpf_func = func[i]->bpf_func;
10426 tmp = bpf_int_jit_compile(func[i]);
10427 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
10428 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010429 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010430 goto out_free;
10431 }
10432 cond_resched();
10433 }
10434
10435 /* finally lock prog and jit images for all functions and
10436 * populate kallsysm
10437 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010438 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010439 bpf_prog_lock_ro(func[i]);
10440 bpf_prog_kallsyms_add(func[i]);
10441 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010010442
10443 /* Last step: make now unused interpreter insns from main
10444 * prog consistent for later dump requests, so they can
10445 * later look the same as if they were interpreted only.
10446 */
10447 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Daniel Borkmann7105e822017-12-20 13:42:57 +010010448 if (insn->code != (BPF_JMP | BPF_CALL) ||
10449 insn->src_reg != BPF_PSEUDO_CALL)
10450 continue;
10451 insn->off = env->insn_aux_data[i].call_imm;
10452 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053010453 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010010454 }
10455
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010456 prog->jited = 1;
10457 prog->bpf_func = func[0]->bpf_func;
10458 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040010459 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010460 bpf_prog_free_unused_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010461 return 0;
10462out_free:
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010463 for (i = 0; i < env->subprog_cnt; i++) {
10464 if (!func[i])
10465 continue;
10466
10467 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
10468 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
10469 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
10470 }
10471 bpf_jit_free(func[i]);
10472 }
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010473 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010474out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010475 /* cleanup main prog to be interpreted */
10476 prog->jit_requested = 0;
10477 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10478 if (insn->code != (BPF_JMP | BPF_CALL) ||
10479 insn->src_reg != BPF_PSEUDO_CALL)
10480 continue;
10481 insn->off = 0;
10482 insn->imm = env->insn_aux_data[i].call_imm;
10483 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010484 bpf_prog_free_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010485 return err;
10486}
10487
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010488static int fixup_call_args(struct bpf_verifier_env *env)
10489{
David S. Miller19d28fb2018-01-11 21:27:54 -050010490#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010491 struct bpf_prog *prog = env->prog;
10492 struct bpf_insn *insn = prog->insnsi;
10493 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050010494#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010010495 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010496
Quentin Monnete4052d02018-10-07 12:56:58 +010010497 if (env->prog->jit_requested &&
10498 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050010499 err = jit_subprogs(env);
10500 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010501 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010502 if (err == -EFAULT)
10503 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050010504 }
10505#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020010506 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
10507 /* When JIT fails the progs with bpf2bpf calls and tail_calls
10508 * have to be rejected, since interpreter doesn't support them yet.
10509 */
10510 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10511 return -EINVAL;
10512 }
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010513 for (i = 0; i < prog->len; i++, insn++) {
10514 if (insn->code != (BPF_JMP | BPF_CALL) ||
10515 insn->src_reg != BPF_PSEUDO_CALL)
10516 continue;
10517 depth = get_callee_stack_depth(env, insn, i);
10518 if (depth < 0)
10519 return depth;
10520 bpf_patch_call_args(insn, depth);
10521 }
David S. Miller19d28fb2018-01-11 21:27:54 -050010522 err = 0;
10523#endif
10524 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010525}
10526
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010527/* fixup insn->imm field of bpf_call instructions
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010528 * and inline eligible helpers as explicit sequence of BPF instructions
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010529 *
10530 * this function is called after eBPF program passed verification
10531 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010532static int fixup_bpf_calls(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010533{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010534 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010535 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010536 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010537 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010538 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020010539 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010540 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010541 struct bpf_insn insn_buf[16];
10542 struct bpf_prog *new_prog;
10543 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010544 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010545
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010546 for (i = 0; i < insn_cnt; i++, insn++) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010010547 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10548 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10549 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080010550 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010010551 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10552 struct bpf_insn mask_and_div[] = {
10553 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10554 /* Rx div 0 -> 0 */
10555 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10556 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10557 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10558 *insn,
10559 };
10560 struct bpf_insn mask_and_mod[] = {
10561 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10562 /* Rx mod 0 -> Rx */
10563 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10564 *insn,
10565 };
10566 struct bpf_insn *patchlet;
10567
10568 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10569 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10570 patchlet = mask_and_div + (is64 ? 1 : 0);
10571 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10572 } else {
10573 patchlet = mask_and_mod + (is64 ? 1 : 0);
10574 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10575 }
10576
10577 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080010578 if (!new_prog)
10579 return -ENOMEM;
10580
10581 delta += cnt - 1;
10582 env->prog = prog = new_prog;
10583 insn = new_prog->insnsi + i + delta;
10584 continue;
10585 }
10586
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020010587 if (BPF_CLASS(insn->code) == BPF_LD &&
10588 (BPF_MODE(insn->code) == BPF_ABS ||
10589 BPF_MODE(insn->code) == BPF_IND)) {
10590 cnt = env->ops->gen_ld_abs(insn, insn_buf);
10591 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10592 verbose(env, "bpf verifier is misconfigured\n");
10593 return -EINVAL;
10594 }
10595
10596 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10597 if (!new_prog)
10598 return -ENOMEM;
10599
10600 delta += cnt - 1;
10601 env->prog = prog = new_prog;
10602 insn = new_prog->insnsi + i + delta;
10603 continue;
10604 }
10605
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010606 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10607 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10608 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10609 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10610 struct bpf_insn insn_buf[16];
10611 struct bpf_insn *patch = &insn_buf[0];
10612 bool issrc, isneg;
10613 u32 off_reg;
10614
10615 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010010616 if (!aux->alu_state ||
10617 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010618 continue;
10619
10620 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10621 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10622 BPF_ALU_SANITIZE_SRC;
10623
10624 off_reg = issrc ? insn->src_reg : insn->dst_reg;
10625 if (isneg)
10626 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10627 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10628 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10629 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10630 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10631 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10632 if (issrc) {
10633 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10634 off_reg);
10635 insn->src_reg = BPF_REG_AX;
10636 } else {
10637 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10638 BPF_REG_AX);
10639 }
10640 if (isneg)
10641 insn->code = insn->code == code_add ?
10642 code_sub : code_add;
10643 *patch++ = *insn;
10644 if (issrc && isneg)
10645 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10646 cnt = patch - insn_buf;
10647
10648 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10649 if (!new_prog)
10650 return -ENOMEM;
10651
10652 delta += cnt - 1;
10653 env->prog = prog = new_prog;
10654 insn = new_prog->insnsi + i + delta;
10655 continue;
10656 }
10657
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010658 if (insn->code != (BPF_JMP | BPF_CALL))
10659 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010660 if (insn->src_reg == BPF_PSEUDO_CALL)
10661 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010662
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010663 if (insn->imm == BPF_FUNC_get_route_realm)
10664 prog->dst_needed = 1;
10665 if (insn->imm == BPF_FUNC_get_prandom_u32)
10666 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050010667 if (insn->imm == BPF_FUNC_override_return)
10668 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010669 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040010670 /* If we tail call into other programs, we
10671 * cannot make any assumptions since they can
10672 * be replaced dynamically during runtime in
10673 * the program array.
10674 */
10675 prog->cb_access = 1;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020010676 if (!allow_tail_call_in_subprogs(env))
10677 prog->aux->stack_depth = MAX_BPF_STACK;
10678 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040010679
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010680 /* mark bpf_tail_call as different opcode to avoid
10681 * conditional branch in the interpeter for every normal
10682 * call and to prevent accidental JITing by JIT compiler
10683 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010684 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010685 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070010686 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010687
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010688 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070010689 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010010690 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010691 !bpf_map_key_poisoned(aux) &&
10692 !bpf_map_ptr_poisoned(aux) &&
10693 !bpf_map_ptr_unpriv(aux)) {
10694 struct bpf_jit_poke_descriptor desc = {
10695 .reason = BPF_POKE_REASON_TAIL_CALL,
10696 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10697 .tail_call.key = bpf_map_key_immediate(aux),
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010698 .insn_idx = i + delta,
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010699 };
10700
10701 ret = bpf_jit_add_poke_descriptor(prog, &desc);
10702 if (ret < 0) {
10703 verbose(env, "adding tail call poke descriptor failed\n");
10704 return ret;
10705 }
10706
10707 insn->imm = ret + 1;
10708 continue;
10709 }
10710
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010711 if (!bpf_map_ptr_unpriv(aux))
10712 continue;
10713
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010714 /* instead of changing every JIT dealing with tail_call
10715 * emit two extra insns:
10716 * if (index >= max_entries) goto out;
10717 * index &= array->index_mask;
10718 * to avoid out-of-bounds cpu speculation
10719 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010720 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000010721 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010722 return -EINVAL;
10723 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010724
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010725 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010726 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
10727 map_ptr->max_entries, 2);
10728 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
10729 container_of(map_ptr,
10730 struct bpf_array,
10731 map)->index_mask);
10732 insn_buf[2] = *insn;
10733 cnt = 3;
10734 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10735 if (!new_prog)
10736 return -ENOMEM;
10737
10738 delta += cnt - 1;
10739 env->prog = prog = new_prog;
10740 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010741 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010742 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010743
Daniel Borkmann89c63072017-08-19 03:12:45 +020010744 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020010745 * and other inlining handlers are currently limited to 64 bit
10746 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020010747 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080010748 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020010749 (insn->imm == BPF_FUNC_map_lookup_elem ||
10750 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020010751 insn->imm == BPF_FUNC_map_delete_elem ||
10752 insn->imm == BPF_FUNC_map_push_elem ||
10753 insn->imm == BPF_FUNC_map_pop_elem ||
10754 insn->imm == BPF_FUNC_map_peek_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010755 aux = &env->insn_aux_data[i + delta];
10756 if (bpf_map_ptr_poisoned(aux))
10757 goto patch_call_imm;
10758
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010759 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020010760 ops = map_ptr->ops;
10761 if (insn->imm == BPF_FUNC_map_lookup_elem &&
10762 ops->map_gen_lookup) {
10763 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
10764 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10765 verbose(env, "bpf verifier is misconfigured\n");
10766 return -EINVAL;
10767 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010768
Daniel Borkmann09772d92018-06-02 23:06:35 +020010769 new_prog = bpf_patch_insn_data(env, i + delta,
10770 insn_buf, cnt);
10771 if (!new_prog)
10772 return -ENOMEM;
10773
10774 delta += cnt - 1;
10775 env->prog = prog = new_prog;
10776 insn = new_prog->insnsi + i + delta;
10777 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010778 }
10779
Daniel Borkmann09772d92018-06-02 23:06:35 +020010780 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
10781 (void *(*)(struct bpf_map *map, void *key))NULL));
10782 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
10783 (int (*)(struct bpf_map *map, void *key))NULL));
10784 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
10785 (int (*)(struct bpf_map *map, void *key, void *value,
10786 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020010787 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
10788 (int (*)(struct bpf_map *map, void *value,
10789 u64 flags))NULL));
10790 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
10791 (int (*)(struct bpf_map *map, void *value))NULL));
10792 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
10793 (int (*)(struct bpf_map *map, void *value))NULL));
10794
Daniel Borkmann09772d92018-06-02 23:06:35 +020010795 switch (insn->imm) {
10796 case BPF_FUNC_map_lookup_elem:
10797 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
10798 __bpf_call_base;
10799 continue;
10800 case BPF_FUNC_map_update_elem:
10801 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
10802 __bpf_call_base;
10803 continue;
10804 case BPF_FUNC_map_delete_elem:
10805 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
10806 __bpf_call_base;
10807 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020010808 case BPF_FUNC_map_push_elem:
10809 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
10810 __bpf_call_base;
10811 continue;
10812 case BPF_FUNC_map_pop_elem:
10813 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
10814 __bpf_call_base;
10815 continue;
10816 case BPF_FUNC_map_peek_elem:
10817 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
10818 __bpf_call_base;
10819 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +020010820 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010821
Daniel Borkmann09772d92018-06-02 23:06:35 +020010822 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010823 }
10824
Martin KaFai Lau5576b992020-01-22 15:36:46 -080010825 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10826 insn->imm == BPF_FUNC_jiffies64) {
10827 struct bpf_insn ld_jiffies_addr[2] = {
10828 BPF_LD_IMM64(BPF_REG_0,
10829 (unsigned long)&jiffies),
10830 };
10831
10832 insn_buf[0] = ld_jiffies_addr[0];
10833 insn_buf[1] = ld_jiffies_addr[1];
10834 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
10835 BPF_REG_0, 0);
10836 cnt = 3;
10837
10838 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
10839 cnt);
10840 if (!new_prog)
10841 return -ENOMEM;
10842
10843 delta += cnt - 1;
10844 env->prog = prog = new_prog;
10845 insn = new_prog->insnsi + i + delta;
10846 continue;
10847 }
10848
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010849patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -070010850 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010851 /* all functions that have prototype and verifier allowed
10852 * programs to call them, must be real in-kernel functions
10853 */
10854 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010855 verbose(env,
10856 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010857 func_id_name(insn->imm), insn->imm);
10858 return -EFAULT;
10859 }
10860 insn->imm = fn->func - __bpf_call_base;
10861 }
10862
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010863 /* Since poke tab is now finalized, publish aux to tracker. */
10864 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10865 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10866 if (!map_ptr->ops->map_poke_track ||
10867 !map_ptr->ops->map_poke_untrack ||
10868 !map_ptr->ops->map_poke_run) {
10869 verbose(env, "bpf verifier is misconfigured\n");
10870 return -EINVAL;
10871 }
10872
10873 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
10874 if (ret < 0) {
10875 verbose(env, "tracking tail call prog failed\n");
10876 return ret;
10877 }
10878 }
10879
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010880 return 0;
10881}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010882
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010883static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010884{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010885 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010886 int i;
10887
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010888 sl = env->free_list;
10889 while (sl) {
10890 sln = sl->next;
10891 free_verifier_state(&sl->state, false);
10892 kfree(sl);
10893 sl = sln;
10894 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010895 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010896
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010897 if (!env->explored_states)
10898 return;
10899
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010900 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010901 sl = env->explored_states[i];
10902
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010903 while (sl) {
10904 sln = sl->next;
10905 free_verifier_state(&sl->state, false);
10906 kfree(sl);
10907 sl = sln;
10908 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010909 env->explored_states[i] = NULL;
10910 }
10911}
10912
10913/* The verifier is using insn_aux_data[] to store temporary data during
10914 * verification and to store information for passes that run after the
10915 * verification like dead code sanitization. do_check_common() for subprogram N
10916 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10917 * temporary data after do_check_common() finds that subprogram N cannot be
10918 * verified independently. pass_cnt counts the number of times
10919 * do_check_common() was run and insn->aux->seen tells the pass number
10920 * insn_aux_data was touched. These variables are compared to clear temporary
10921 * data from failed pass. For testing and experiments do_check_common() can be
10922 * run multiple times even when prior attempt to verify is unsuccessful.
10923 */
10924static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
10925{
10926 struct bpf_insn *insn = env->prog->insnsi;
10927 struct bpf_insn_aux_data *aux;
10928 int i, class;
10929
10930 for (i = 0; i < env->prog->len; i++) {
10931 class = BPF_CLASS(insn[i].code);
10932 if (class != BPF_LDX && class != BPF_STX)
10933 continue;
10934 aux = &env->insn_aux_data[i];
10935 if (aux->seen != env->pass_cnt)
10936 continue;
10937 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
10938 }
10939}
10940
10941static int do_check_common(struct bpf_verifier_env *env, int subprog)
10942{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010943 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010944 struct bpf_verifier_state *state;
10945 struct bpf_reg_state *regs;
10946 int ret, i;
10947
10948 env->prev_linfo = NULL;
10949 env->pass_cnt++;
10950
10951 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
10952 if (!state)
10953 return -ENOMEM;
10954 state->curframe = 0;
10955 state->speculative = false;
10956 state->branches = 1;
10957 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
10958 if (!state->frame[0]) {
10959 kfree(state);
10960 return -ENOMEM;
10961 }
10962 env->cur_state = state;
10963 init_func_state(env, state->frame[0],
10964 BPF_MAIN_FUNC /* callsite */,
10965 0 /* frameno */,
10966 subprog);
10967
10968 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080010969 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010970 ret = btf_prepare_func_args(env, subprog, regs);
10971 if (ret)
10972 goto out;
10973 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
10974 if (regs[i].type == PTR_TO_CTX)
10975 mark_reg_known_zero(env, regs, i);
10976 else if (regs[i].type == SCALAR_VALUE)
10977 mark_reg_unknown(env, regs, i);
10978 }
10979 } else {
10980 /* 1st arg to a function */
10981 regs[BPF_REG_1].type = PTR_TO_CTX;
10982 mark_reg_known_zero(env, regs, BPF_REG_1);
10983 ret = btf_check_func_arg_match(env, subprog, regs);
10984 if (ret == -EFAULT)
10985 /* unlikely verifier bug. abort.
10986 * ret == 0 and ret < 0 are sadly acceptable for
10987 * main() function due to backward compatibility.
10988 * Like socket filter program may be written as:
10989 * int bpf_prog(struct pt_regs *ctx)
10990 * and never dereference that ctx in the program.
10991 * 'struct pt_regs' is a type mismatch for socket
10992 * filter that should be using 'struct __sk_buff'.
10993 */
10994 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010995 }
10996
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010997 ret = do_check(env);
10998out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080010999 /* check for NULL is necessary, since cur_state can be freed inside
11000 * do_check() under memory pressure.
11001 */
11002 if (env->cur_state) {
11003 free_verifier_state(env->cur_state, true);
11004 env->cur_state = NULL;
11005 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070011006 while (!pop_stack(env, NULL, NULL, false));
11007 if (!ret && pop_log)
11008 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011009 free_states(env);
11010 if (ret)
11011 /* clean aux data in case subprog was rejected */
11012 sanitize_insn_aux_data(env);
11013 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011014}
11015
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011016/* Verify all global functions in a BPF program one by one based on their BTF.
11017 * All global functions must pass verification. Otherwise the whole program is rejected.
11018 * Consider:
11019 * int bar(int);
11020 * int foo(int f)
11021 * {
11022 * return bar(f);
11023 * }
11024 * int bar(int b)
11025 * {
11026 * ...
11027 * }
11028 * foo() will be verified first for R1=any_scalar_value. During verification it
11029 * will be assumed that bar() already verified successfully and call to bar()
11030 * from foo() will be checked for type match only. Later bar() will be verified
11031 * independently to check that it's safe for R1=any_scalar_value.
11032 */
11033static int do_check_subprogs(struct bpf_verifier_env *env)
11034{
11035 struct bpf_prog_aux *aux = env->prog->aux;
11036 int i, ret;
11037
11038 if (!aux->func_info)
11039 return 0;
11040
11041 for (i = 1; i < env->subprog_cnt; i++) {
11042 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11043 continue;
11044 env->insn_idx = env->subprog_info[i].start;
11045 WARN_ON_ONCE(env->insn_idx == 0);
11046 ret = do_check_common(env, i);
11047 if (ret) {
11048 return ret;
11049 } else if (env->log.level & BPF_LOG_LEVEL) {
11050 verbose(env,
11051 "Func#%d is safe for any args that match its prototype\n",
11052 i);
11053 }
11054 }
11055 return 0;
11056}
11057
11058static int do_check_main(struct bpf_verifier_env *env)
11059{
11060 int ret;
11061
11062 env->insn_idx = 0;
11063 ret = do_check_common(env, 0);
11064 if (!ret)
11065 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11066 return ret;
11067}
11068
11069
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011070static void print_verification_stats(struct bpf_verifier_env *env)
11071{
11072 int i;
11073
11074 if (env->log.level & BPF_LOG_STATS) {
11075 verbose(env, "verification time %lld usec\n",
11076 div_u64(env->verification_time, 1000));
11077 verbose(env, "stack depth ");
11078 for (i = 0; i < env->subprog_cnt; i++) {
11079 u32 depth = env->subprog_info[i].stack_depth;
11080
11081 verbose(env, "%d", depth);
11082 if (i + 1 < env->subprog_cnt)
11083 verbose(env, "+");
11084 }
11085 verbose(env, "\n");
11086 }
11087 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11088 "total_states %d peak_states %d mark_read %d\n",
11089 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11090 env->max_states_per_insn, env->total_states,
11091 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011092}
11093
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011094static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11095{
11096 const struct btf_type *t, *func_proto;
11097 const struct bpf_struct_ops *st_ops;
11098 const struct btf_member *member;
11099 struct bpf_prog *prog = env->prog;
11100 u32 btf_id, member_idx;
11101 const char *mname;
11102
11103 btf_id = prog->aux->attach_btf_id;
11104 st_ops = bpf_struct_ops_find(btf_id);
11105 if (!st_ops) {
11106 verbose(env, "attach_btf_id %u is not a supported struct\n",
11107 btf_id);
11108 return -ENOTSUPP;
11109 }
11110
11111 t = st_ops->type;
11112 member_idx = prog->expected_attach_type;
11113 if (member_idx >= btf_type_vlen(t)) {
11114 verbose(env, "attach to invalid member idx %u of struct %s\n",
11115 member_idx, st_ops->name);
11116 return -EINVAL;
11117 }
11118
11119 member = &btf_type_member(t)[member_idx];
11120 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11121 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11122 NULL);
11123 if (!func_proto) {
11124 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11125 mname, member_idx, st_ops->name);
11126 return -EINVAL;
11127 }
11128
11129 if (st_ops->check_member) {
11130 int err = st_ops->check_member(t, member);
11131
11132 if (err) {
11133 verbose(env, "attach to unsupported member %s of struct %s\n",
11134 mname, st_ops->name);
11135 return err;
11136 }
11137 }
11138
11139 prog->aux->attach_func_proto = func_proto;
11140 prog->aux->attach_func_name = mname;
11141 env->ops = st_ops->verifier_ops;
11142
11143 return 0;
11144}
KP Singh6ba43b72020-03-04 20:18:50 +010011145#define SECURITY_PREFIX "security_"
11146
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011147static int check_attach_modify_return(struct bpf_prog *prog, unsigned long addr)
KP Singh6ba43b72020-03-04 20:18:50 +010011148{
KP Singh69191752020-03-05 21:49:55 +010011149 if (within_error_injection_list(addr) ||
11150 !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
11151 sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010011152 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010011153
KP Singh6ba43b72020-03-04 20:18:50 +010011154 return -EINVAL;
11155}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011156
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011157/* non exhaustive list of sleepable bpf_lsm_*() functions */
11158BTF_SET_START(btf_sleepable_lsm_hooks)
11159#ifdef CONFIG_BPF_LSM
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011160BTF_ID(func, bpf_lsm_bprm_committed_creds)
Alexei Starovoitov29523c52020-08-31 09:31:32 -070011161#else
11162BTF_ID_UNUSED
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011163#endif
11164BTF_SET_END(btf_sleepable_lsm_hooks)
11165
11166static int check_sleepable_lsm_hook(u32 btf_id)
11167{
11168 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
11169}
11170
11171/* list of non-sleepable functions that are otherwise on
11172 * ALLOW_ERROR_INJECTION list
11173 */
11174BTF_SET_START(btf_non_sleepable_error_inject)
11175/* Three functions below can be called from sleepable and non-sleepable context.
11176 * Assume non-sleepable from bpf safety point of view.
11177 */
11178BTF_ID(func, __add_to_page_cache_locked)
11179BTF_ID(func, should_fail_alloc_page)
11180BTF_ID(func, should_failslab)
11181BTF_SET_END(btf_non_sleepable_error_inject)
11182
11183static int check_non_sleepable_error_inject(u32 btf_id)
11184{
11185 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11186}
11187
Martin KaFai Lau38207292019-10-24 17:18:11 -070011188static int check_attach_btf_id(struct bpf_verifier_env *env)
11189{
11190 struct bpf_prog *prog = env->prog;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011191 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011192 struct bpf_prog *tgt_prog = prog->aux->linked_prog;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011193 u32 btf_id = prog->aux->attach_btf_id;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011194 const char prefix[] = "btf_trace_";
Yonghong Song15d83c42020-05-09 10:59:00 -070011195 struct btf_func_model fmodel;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011196 int ret = 0, subprog = -1, i;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011197 struct bpf_trampoline *tr;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011198 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011199 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011200 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011201 struct btf *btf;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011202 long addr;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011203 u64 key;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011204
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011205 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
11206 prog->type != BPF_PROG_TYPE_LSM) {
11207 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11208 return -EINVAL;
11209 }
11210
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011211 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
11212 return check_struct_ops_btf_id(env);
11213
KP Singh9e4e01d2020-03-29 01:43:52 +010011214 if (prog->type != BPF_PROG_TYPE_TRACING &&
11215 prog->type != BPF_PROG_TYPE_LSM &&
11216 !prog_extension)
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011217 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011218
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011219 if (!btf_id) {
11220 verbose(env, "Tracing programs must provide btf_id\n");
11221 return -EINVAL;
11222 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011223 btf = bpf_prog_get_target_btf(prog);
11224 if (!btf) {
11225 verbose(env,
11226 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11227 return -EINVAL;
11228 }
11229 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011230 if (!t) {
11231 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
11232 return -EINVAL;
11233 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011234 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011235 if (!tname) {
11236 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
11237 return -EINVAL;
11238 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011239 if (tgt_prog) {
11240 struct bpf_prog_aux *aux = tgt_prog->aux;
11241
11242 for (i = 0; i < aux->func_info_cnt; i++)
11243 if (aux->func_info[i].type_id == btf_id) {
11244 subprog = i;
11245 break;
11246 }
11247 if (subprog == -1) {
11248 verbose(env, "Subprog %s doesn't exist\n", tname);
11249 return -EINVAL;
11250 }
11251 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011252 if (prog_extension) {
11253 if (conservative) {
11254 verbose(env,
11255 "Cannot replace static functions\n");
11256 return -EINVAL;
11257 }
11258 if (!prog->jit_requested) {
11259 verbose(env,
11260 "Extension programs should be JITed\n");
11261 return -EINVAL;
11262 }
11263 env->ops = bpf_verifier_ops[tgt_prog->type];
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020011264 prog->expected_attach_type = tgt_prog->expected_attach_type;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011265 }
11266 if (!tgt_prog->jited) {
11267 verbose(env, "Can attach to only JITed progs\n");
11268 return -EINVAL;
11269 }
11270 if (tgt_prog->type == prog->type) {
11271 /* Cannot fentry/fexit another fentry/fexit program.
11272 * Cannot attach program extension to another extension.
11273 * It's ok to attach fentry/fexit to extension program.
11274 */
11275 verbose(env, "Cannot recursively attach\n");
11276 return -EINVAL;
11277 }
11278 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
11279 prog_extension &&
11280 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
11281 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
11282 /* Program extensions can extend all program types
11283 * except fentry/fexit. The reason is the following.
11284 * The fentry/fexit programs are used for performance
11285 * analysis, stats and can be attached to any program
11286 * type except themselves. When extension program is
11287 * replacing XDP function it is necessary to allow
11288 * performance analysis of all functions. Both original
11289 * XDP program and its program extension. Hence
11290 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11291 * allowed. If extending of fentry/fexit was allowed it
11292 * would be possible to create long call chain
11293 * fentry->extension->fentry->extension beyond
11294 * reasonable stack size. Hence extending fentry is not
11295 * allowed.
11296 */
11297 verbose(env, "Cannot extend fentry/fexit\n");
11298 return -EINVAL;
11299 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011300 key = ((u64)aux->id) << 32 | btf_id;
11301 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011302 if (prog_extension) {
11303 verbose(env, "Cannot replace kernel functions\n");
11304 return -EINVAL;
11305 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011306 key = btf_id;
11307 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011308
11309 switch (prog->expected_attach_type) {
11310 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011311 if (tgt_prog) {
11312 verbose(env,
11313 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11314 return -EINVAL;
11315 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070011316 if (!btf_type_is_typedef(t)) {
11317 verbose(env, "attach_btf_id %u is not a typedef\n",
11318 btf_id);
11319 return -EINVAL;
11320 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011321 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Martin KaFai Lau38207292019-10-24 17:18:11 -070011322 verbose(env, "attach_btf_id %u points to wrong type name %s\n",
11323 btf_id, tname);
11324 return -EINVAL;
11325 }
11326 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011327 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011328 if (!btf_type_is_ptr(t))
11329 /* should never happen in valid vmlinux build */
11330 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011331 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011332 if (!btf_type_is_func_proto(t))
11333 /* should never happen in valid vmlinux build */
11334 return -EINVAL;
11335
11336 /* remember two read only pointers that are valid for
11337 * the life time of the kernel
11338 */
11339 prog->aux->attach_func_name = tname;
11340 prog->aux->attach_func_proto = t;
11341 prog->aux->attach_btf_trace = true;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011342 return 0;
Yonghong Song15d83c42020-05-09 10:59:00 -070011343 case BPF_TRACE_ITER:
11344 if (!btf_type_is_func(t)) {
11345 verbose(env, "attach_btf_id %u is not a function\n",
11346 btf_id);
11347 return -EINVAL;
11348 }
11349 t = btf_type_by_id(btf, t->type);
11350 if (!btf_type_is_func_proto(t))
11351 return -EINVAL;
11352 prog->aux->attach_func_name = tname;
11353 prog->aux->attach_func_proto = t;
11354 if (!bpf_iter_prog_supported(prog))
11355 return -EINVAL;
11356 ret = btf_distill_func_proto(&env->log, btf, t,
11357 tname, &fmodel);
11358 return ret;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011359 default:
11360 if (!prog_extension)
11361 return -EINVAL;
11362 /* fallthrough */
KP Singhae240822020-03-04 20:18:49 +010011363 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010011364 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011365 case BPF_TRACE_FENTRY:
11366 case BPF_TRACE_FEXIT:
KP Singh9e4e01d2020-03-29 01:43:52 +010011367 prog->aux->attach_func_name = tname;
11368 if (prog->type == BPF_PROG_TYPE_LSM) {
11369 ret = bpf_lsm_verify_prog(&env->log, prog);
11370 if (ret < 0)
11371 return ret;
11372 }
11373
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011374 if (!btf_type_is_func(t)) {
11375 verbose(env, "attach_btf_id %u is not a function\n",
11376 btf_id);
11377 return -EINVAL;
11378 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011379 if (prog_extension &&
11380 btf_check_type_match(env, prog, btf, t))
11381 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011382 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011383 if (!btf_type_is_func_proto(t))
11384 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011385 tr = bpf_trampoline_lookup(key);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011386 if (!tr)
11387 return -ENOMEM;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011388 /* t is either vmlinux type or another program's type */
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011389 prog->aux->attach_func_proto = t;
11390 mutex_lock(&tr->mutex);
11391 if (tr->func.addr) {
11392 prog->aux->trampoline = tr;
11393 goto out;
11394 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011395 if (tgt_prog && conservative) {
11396 prog->aux->attach_func_proto = NULL;
11397 t = NULL;
11398 }
11399 ret = btf_distill_func_proto(&env->log, btf, t,
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011400 tname, &tr->func.model);
11401 if (ret < 0)
11402 goto out;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011403 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080011404 if (subprog == 0)
11405 addr = (long) tgt_prog->bpf_func;
11406 else
11407 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011408 } else {
11409 addr = kallsyms_lookup_name(tname);
11410 if (!addr) {
11411 verbose(env,
11412 "The address of function %s cannot be found\n",
11413 tname);
11414 ret = -ENOENT;
11415 goto out;
11416 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011417 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011418
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011419 if (prog->aux->sleepable) {
11420 ret = -EINVAL;
11421 switch (prog->type) {
11422 case BPF_PROG_TYPE_TRACING:
11423 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11424 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11425 */
11426 if (!check_non_sleepable_error_inject(btf_id) &&
11427 within_error_injection_list(addr))
11428 ret = 0;
11429 break;
11430 case BPF_PROG_TYPE_LSM:
11431 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11432 * Only some of them are sleepable.
11433 */
11434 if (check_sleepable_lsm_hook(btf_id))
11435 ret = 0;
11436 break;
11437 default:
11438 break;
11439 }
11440 if (ret)
11441 verbose(env, "%s is not sleepable\n",
11442 prog->aux->attach_func_name);
11443 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011444 ret = check_attach_modify_return(prog, addr);
11445 if (ret)
11446 verbose(env, "%s() is not modifiable\n",
11447 prog->aux->attach_func_name);
11448 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011449 if (ret)
11450 goto out;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011451 tr->func.addr = (void *)addr;
11452 prog->aux->trampoline = tr;
11453out:
11454 mutex_unlock(&tr->mutex);
11455 if (ret)
11456 bpf_trampoline_put(tr);
11457 return ret;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011458 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070011459}
11460
Yonghong Song838e9692018-11-19 15:29:11 -080011461int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
11462 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011463{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011464 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011465 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070011466 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011467 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011468 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011469
Arnd Bergmanneba0c922017-11-02 12:05:52 +010011470 /* no program is valid */
11471 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
11472 return -EINVAL;
11473
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011474 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011475 * allocate/free it every time bpf_check() is called
11476 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011477 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011478 if (!env)
11479 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011480 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011481
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011482 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070011483 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011484 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011485 ret = -ENOMEM;
11486 if (!env->insn_aux_data)
11487 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011488 for (i = 0; i < len; i++)
11489 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011490 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070011491 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011492 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011493
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011494 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
11495 mutex_lock(&bpf_verifier_lock);
11496 if (!btf_vmlinux)
11497 btf_vmlinux = btf_parse_vmlinux();
11498 mutex_unlock(&bpf_verifier_lock);
11499 }
11500
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011501 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070011502 if (!is_priv)
11503 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011504
11505 if (attr->log_level || attr->log_buf || attr->log_size) {
11506 /* user requested verbose verifier output
11507 * and supplied buffer to store the verification trace
11508 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070011509 log->level = attr->log_level;
11510 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
11511 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011512
11513 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070011514 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070011515 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011516 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011517 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011518 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020011519
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011520 if (IS_ERR(btf_vmlinux)) {
11521 /* Either gcc or pahole or kernel are broken. */
11522 verbose(env, "in-kernel BTF is malformed\n");
11523 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011524 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011525 }
11526
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020011527 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
11528 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070011529 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080011530 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
11531 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011532
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011533 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070011534 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011535 env->bypass_spec_v1 = bpf_bypass_spec_v1();
11536 env->bypass_spec_v4 = bpf_bypass_spec_v4();
11537 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011538
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070011539 if (is_priv)
11540 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
11541
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011542 ret = replace_map_fd_with_map_ptr(env);
11543 if (ret < 0)
11544 goto skip_full_check;
11545
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070011546 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Quentin Monneta40a2632018-11-09 13:03:31 +000011547 ret = bpf_prog_offload_verifier_prep(env->prog);
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070011548 if (ret)
11549 goto skip_full_check;
11550 }
11551
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011552 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011553 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011554 GFP_USER);
11555 ret = -ENOMEM;
11556 if (!env->explored_states)
11557 goto skip_full_check;
11558
Martin KaFai Laud9762e82018-12-13 10:41:48 -080011559 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070011560 if (ret < 0)
11561 goto skip_full_check;
11562
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011563 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080011564 if (ret < 0)
11565 goto skip_full_check;
11566
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011567 ret = check_attach_btf_id(env);
11568 if (ret)
11569 goto skip_full_check;
11570
Martin KaFai Laud9762e82018-12-13 10:41:48 -080011571 ret = check_cfg(env);
11572 if (ret < 0)
11573 goto skip_full_check;
11574
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011575 ret = do_check_subprogs(env);
11576 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011577
Quentin Monnetc941ce92018-10-07 12:56:47 +010011578 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11579 ret = bpf_prog_offload_finalize(env);
11580
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011581skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011582 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011583
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011584 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080011585 ret = check_max_stack_depth(env);
11586
Jakub Kicinski9b38c402018-12-19 22:13:06 -080011587 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011588 if (is_priv) {
11589 if (ret == 0)
11590 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080011591 if (ret == 0)
11592 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080011593 if (ret == 0)
11594 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080011595 } else {
11596 if (ret == 0)
11597 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011598 }
11599
Jakub Kicinski9b38c402018-12-19 22:13:06 -080011600 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011601 /* program is valid, convert *(u32*)(ctx + off) accesses */
11602 ret = convert_ctx_accesses(env);
11603
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011604 if (ret == 0)
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011605 ret = fixup_bpf_calls(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011606
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011607 /* do 32-bit optimization after insn patching has done so those patched
11608 * insns could be handled correctly.
11609 */
Jiong Wangd6c23082019-05-24 23:25:18 +010011610 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11611 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11612 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11613 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011614 }
11615
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011616 if (ret == 0)
11617 ret = fixup_call_args(env);
11618
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011619 env->verification_time = ktime_get_ns() - start_time;
11620 print_verification_stats(env);
11621
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011622 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011623 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011624 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011625 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011626 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011627 }
11628
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011629 if (ret == 0 && env->used_map_cnt) {
11630 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011631 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11632 sizeof(env->used_maps[0]),
11633 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011634
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011635 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011636 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011637 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011638 }
11639
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011640 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011641 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011642 env->prog->aux->used_map_cnt = env->used_map_cnt;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011643
11644 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11645 * bpf_ld_imm64 instructions
11646 */
11647 convert_pseudo_ld_imm64(env);
11648 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011649
Yonghong Songba64e7d2018-11-24 23:20:44 -080011650 if (ret == 0)
11651 adjust_btf_func(env);
11652
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011653err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011654 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011655 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070011656 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011657 */
11658 release_maps(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020011659
11660 /* extension progs temporarily inherit the attach_type of their targets
11661 for verification purposes, so set it back to zero before returning
11662 */
11663 if (env->prog->type == BPF_PROG_TYPE_EXT)
11664 env->prog->expected_attach_type = 0;
11665
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011666 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011667err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070011668 if (!is_priv)
11669 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011670 vfree(env->insn_aux_data);
11671err_free_env:
11672 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011673 return ret;
11674}