blob: fe4965079773076128aed596ecba103315dcb3d5 [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
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100438static bool arg_type_may_be_null(enum bpf_arg_type type)
439{
440 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
441 type == ARG_PTR_TO_MEM_OR_NULL ||
442 type == ARG_PTR_TO_CTX_OR_NULL ||
443 type == ARG_PTR_TO_SOCKET_OR_NULL ||
444 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
445}
446
Joe Stringerfd978bf72018-10-02 13:35:35 -0700447/* Determine whether the function releases some resources allocated by another
448 * function call. The first reference type argument will be assumed to be
449 * released by release_reference().
450 */
451static bool is_release_function(enum bpf_func_id func_id)
452{
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700453 return func_id == BPF_FUNC_sk_release ||
454 func_id == BPF_FUNC_ringbuf_submit ||
455 func_id == BPF_FUNC_ringbuf_discard;
Joe Stringer840b9612018-10-02 13:35:32 -0700456}
457
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200458static bool may_be_acquire_function(enum bpf_func_id func_id)
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800459{
460 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800461 func_id == BPF_FUNC_sk_lookup_udp ||
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200462 func_id == BPF_FUNC_skc_lookup_tcp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700463 func_id == BPF_FUNC_map_lookup_elem ||
464 func_id == BPF_FUNC_ringbuf_reserve;
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200465}
466
467static bool is_acquire_function(enum bpf_func_id func_id,
468 const struct bpf_map *map)
469{
470 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
471
472 if (func_id == BPF_FUNC_sk_lookup_tcp ||
473 func_id == BPF_FUNC_sk_lookup_udp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700474 func_id == BPF_FUNC_skc_lookup_tcp ||
475 func_id == BPF_FUNC_ringbuf_reserve)
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200476 return true;
477
478 if (func_id == BPF_FUNC_map_lookup_elem &&
479 (map_type == BPF_MAP_TYPE_SOCKMAP ||
480 map_type == BPF_MAP_TYPE_SOCKHASH))
481 return true;
482
483 return false;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800484}
485
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700486static bool is_ptr_cast_function(enum bpf_func_id func_id)
487{
488 return func_id == BPF_FUNC_tcp_sock ||
Martin KaFai Lau1df8f552020-09-24 17:03:50 -0700489 func_id == BPF_FUNC_sk_fullsock ||
490 func_id == BPF_FUNC_skc_to_tcp_sock ||
491 func_id == BPF_FUNC_skc_to_tcp6_sock ||
492 func_id == BPF_FUNC_skc_to_udp6_sock ||
493 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
494 func_id == BPF_FUNC_skc_to_tcp_request_sock;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700495}
496
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700497/* string representation of 'enum bpf_reg_type' */
498static const char * const reg_type_str[] = {
499 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100500 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700501 [PTR_TO_CTX] = "ctx",
502 [CONST_PTR_TO_MAP] = "map_ptr",
503 [PTR_TO_MAP_VALUE] = "map_value",
504 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700505 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700506 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200507 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700508 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700509 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700510 [PTR_TO_SOCKET] = "sock",
511 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800512 [PTR_TO_SOCK_COMMON] = "sock_common",
513 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800514 [PTR_TO_TCP_SOCK] = "tcp_sock",
515 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700516 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700517 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700518 [PTR_TO_BTF_ID] = "ptr_",
Yonghong Songb121b342020-05-09 10:59:12 -0700519 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700520 [PTR_TO_MEM] = "mem",
521 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
Yonghong Songafbf21d2020-07-23 11:41:11 -0700522 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
523 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
524 [PTR_TO_RDWR_BUF] = "rdwr_buf",
525 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700526};
527
Edward Cree8efea212018-08-22 20:02:44 +0100528static char slot_type_char[] = {
529 [STACK_INVALID] = '?',
530 [STACK_SPILL] = 'r',
531 [STACK_MISC] = 'm',
532 [STACK_ZERO] = '0',
533};
534
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800535static void print_liveness(struct bpf_verifier_env *env,
536 enum bpf_reg_liveness live)
537{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800538 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800539 verbose(env, "_");
540 if (live & REG_LIVE_READ)
541 verbose(env, "r");
542 if (live & REG_LIVE_WRITTEN)
543 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800544 if (live & REG_LIVE_DONE)
545 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800546}
547
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800548static struct bpf_func_state *func(struct bpf_verifier_env *env,
549 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700550{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800551 struct bpf_verifier_state *cur = env->cur_state;
552
553 return cur->frame[reg->frameno];
554}
555
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700556const char *kernel_type_name(u32 id)
557{
558 return btf_name_by_offset(btf_vmlinux,
559 btf_type_by_id(btf_vmlinux, id)->name_off);
560}
561
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800562static void print_verifier_state(struct bpf_verifier_env *env,
563 const struct bpf_func_state *state)
564{
565 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700566 enum bpf_reg_type t;
567 int i;
568
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800569 if (state->frameno)
570 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700571 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700572 reg = &state->regs[i];
573 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700574 if (t == NOT_INIT)
575 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800576 verbose(env, " R%d", i);
577 print_liveness(env, reg->live);
578 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700579 if (t == SCALAR_VALUE && reg->precise)
580 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100581 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
582 tnum_is_const(reg->var_off)) {
583 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700584 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100585 } else {
Yonghong Songb121b342020-05-09 10:59:12 -0700586 if (t == PTR_TO_BTF_ID || t == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700587 verbose(env, "%s", kernel_type_name(reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700588 verbose(env, "(id=%d", reg->id);
589 if (reg_type_may_be_refcounted_or_null(t))
590 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100591 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700592 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200593 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700594 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100595 else if (t == CONST_PTR_TO_MAP ||
596 t == PTR_TO_MAP_VALUE ||
597 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700598 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100599 reg->map_ptr->key_size,
600 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100601 if (tnum_is_const(reg->var_off)) {
602 /* Typically an immediate SCALAR_VALUE, but
603 * could be a pointer whose offset is too big
604 * for reg->off
605 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700606 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100607 } else {
608 if (reg->smin_value != reg->umin_value &&
609 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700610 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100611 (long long)reg->smin_value);
612 if (reg->smax_value != reg->umax_value &&
613 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700614 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100615 (long long)reg->smax_value);
616 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700617 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100618 (unsigned long long)reg->umin_value);
619 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700620 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100621 (unsigned long long)reg->umax_value);
622 if (!tnum_is_unknown(reg->var_off)) {
623 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100624
Edward Cree7d1238f2017-08-07 15:26:56 +0100625 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700626 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100627 }
John Fastabend3f50f132020-03-30 14:36:39 -0700628 if (reg->s32_min_value != reg->smin_value &&
629 reg->s32_min_value != S32_MIN)
630 verbose(env, ",s32_min_value=%d",
631 (int)(reg->s32_min_value));
632 if (reg->s32_max_value != reg->smax_value &&
633 reg->s32_max_value != S32_MAX)
634 verbose(env, ",s32_max_value=%d",
635 (int)(reg->s32_max_value));
636 if (reg->u32_min_value != reg->umin_value &&
637 reg->u32_min_value != U32_MIN)
638 verbose(env, ",u32_min_value=%d",
639 (int)(reg->u32_min_value));
640 if (reg->u32_max_value != reg->umax_value &&
641 reg->u32_max_value != U32_MAX)
642 verbose(env, ",u32_max_value=%d",
643 (int)(reg->u32_max_value));
Edward Creef1174f72017-08-07 15:26:19 +0100644 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700645 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100646 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700647 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700648 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100649 char types_buf[BPF_REG_SIZE + 1];
650 bool valid = false;
651 int j;
652
653 for (j = 0; j < BPF_REG_SIZE; j++) {
654 if (state->stack[i].slot_type[j] != STACK_INVALID)
655 valid = true;
656 types_buf[j] = slot_type_char[
657 state->stack[i].slot_type[j]];
658 }
659 types_buf[BPF_REG_SIZE] = 0;
660 if (!valid)
661 continue;
662 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
663 print_liveness(env, state->stack[i].spilled_ptr.live);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700664 if (state->stack[i].slot_type[0] == STACK_SPILL) {
665 reg = &state->stack[i].spilled_ptr;
666 t = reg->type;
667 verbose(env, "=%s", reg_type_str[t]);
668 if (t == SCALAR_VALUE && reg->precise)
669 verbose(env, "P");
670 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
671 verbose(env, "%lld", reg->var_off.value + reg->off);
672 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100673 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700674 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700675 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700676 if (state->acquired_refs && state->refs[0].id) {
677 verbose(env, " refs=%d", state->refs[0].id);
678 for (i = 1; i < state->acquired_refs; i++)
679 if (state->refs[i].id)
680 verbose(env, ",%d", state->refs[i].id);
681 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700682 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700683}
684
Joe Stringer84dbf352018-10-02 13:35:34 -0700685#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
686static int copy_##NAME##_state(struct bpf_func_state *dst, \
687 const struct bpf_func_state *src) \
688{ \
689 if (!src->FIELD) \
690 return 0; \
691 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
692 /* internal bug, make state invalid to reject the program */ \
693 memset(dst, 0, sizeof(*dst)); \
694 return -EFAULT; \
695 } \
696 memcpy(dst->FIELD, src->FIELD, \
697 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
698 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700699}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700700/* copy_reference_state() */
701COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700702/* copy_stack_state() */
703COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
704#undef COPY_STATE_FN
705
706#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
707static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
708 bool copy_old) \
709{ \
710 u32 old_size = state->COUNT; \
711 struct bpf_##NAME##_state *new_##FIELD; \
712 int slot = size / SIZE; \
713 \
714 if (size <= old_size || !size) { \
715 if (copy_old) \
716 return 0; \
717 state->COUNT = slot * SIZE; \
718 if (!size && old_size) { \
719 kfree(state->FIELD); \
720 state->FIELD = NULL; \
721 } \
722 return 0; \
723 } \
724 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
725 GFP_KERNEL); \
726 if (!new_##FIELD) \
727 return -ENOMEM; \
728 if (copy_old) { \
729 if (state->FIELD) \
730 memcpy(new_##FIELD, state->FIELD, \
731 sizeof(*new_##FIELD) * (old_size / SIZE)); \
732 memset(new_##FIELD + old_size / SIZE, 0, \
733 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
734 } \
735 state->COUNT = slot * SIZE; \
736 kfree(state->FIELD); \
737 state->FIELD = new_##FIELD; \
738 return 0; \
739}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700740/* realloc_reference_state() */
741REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700742/* realloc_stack_state() */
743REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
744#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700745
746/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
747 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800748 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700749 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
750 * which realloc_stack_state() copies over. It points to previous
751 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700752 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700753static int realloc_func_state(struct bpf_func_state *state, int stack_size,
754 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700755{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700756 int err = realloc_reference_state(state, refs_size, copy_old);
757 if (err)
758 return err;
759 return realloc_stack_state(state, stack_size, copy_old);
760}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700761
Joe Stringerfd978bf72018-10-02 13:35:35 -0700762/* Acquire a pointer id from the env and update the state->refs to include
763 * this new pointer reference.
764 * On success, returns a valid pointer id to associate with the register
765 * On failure, returns a negative errno.
766 */
767static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
768{
769 struct bpf_func_state *state = cur_func(env);
770 int new_ofs = state->acquired_refs;
771 int id, err;
772
773 err = realloc_reference_state(state, state->acquired_refs + 1, true);
774 if (err)
775 return err;
776 id = ++env->id_gen;
777 state->refs[new_ofs].id = id;
778 state->refs[new_ofs].insn_idx = insn_idx;
779
780 return id;
781}
782
783/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800784static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700785{
786 int i, last_idx;
787
Joe Stringerfd978bf72018-10-02 13:35:35 -0700788 last_idx = state->acquired_refs - 1;
789 for (i = 0; i < state->acquired_refs; i++) {
790 if (state->refs[i].id == ptr_id) {
791 if (last_idx && i != last_idx)
792 memcpy(&state->refs[i], &state->refs[last_idx],
793 sizeof(*state->refs));
794 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
795 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700796 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700797 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700798 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800799 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700800}
801
802static int transfer_reference_state(struct bpf_func_state *dst,
803 struct bpf_func_state *src)
804{
805 int err = realloc_reference_state(dst, src->acquired_refs, false);
806 if (err)
807 return err;
808 err = copy_reference_state(dst, src);
809 if (err)
810 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700811 return 0;
812}
813
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800814static void free_func_state(struct bpf_func_state *state)
815{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800816 if (!state)
817 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700818 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800819 kfree(state->stack);
820 kfree(state);
821}
822
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700823static void clear_jmp_history(struct bpf_verifier_state *state)
824{
825 kfree(state->jmp_history);
826 state->jmp_history = NULL;
827 state->jmp_history_cnt = 0;
828}
829
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700830static void free_verifier_state(struct bpf_verifier_state *state,
831 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700832{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800833 int i;
834
835 for (i = 0; i <= state->curframe; i++) {
836 free_func_state(state->frame[i]);
837 state->frame[i] = NULL;
838 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700839 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700840 if (free_self)
841 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700842}
843
844/* copy verifier state from src to dst growing dst stack space
845 * when necessary to accommodate larger src stack
846 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800847static int copy_func_state(struct bpf_func_state *dst,
848 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700849{
850 int err;
851
Joe Stringerfd978bf72018-10-02 13:35:35 -0700852 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
853 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700854 if (err)
855 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700856 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
857 err = copy_reference_state(dst, src);
858 if (err)
859 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700860 return copy_stack_state(dst, src);
861}
862
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800863static int copy_verifier_state(struct bpf_verifier_state *dst_state,
864 const struct bpf_verifier_state *src)
865{
866 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700867 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800868 int i, err;
869
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700870 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
871 kfree(dst_state->jmp_history);
872 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
873 if (!dst_state->jmp_history)
874 return -ENOMEM;
875 }
876 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
877 dst_state->jmp_history_cnt = src->jmp_history_cnt;
878
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800879 /* if dst has more stack frames then src frame, free them */
880 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
881 free_func_state(dst_state->frame[i]);
882 dst_state->frame[i] = NULL;
883 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100884 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800885 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800886 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700887 dst_state->branches = src->branches;
888 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700889 dst_state->first_insn_idx = src->first_insn_idx;
890 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800891 for (i = 0; i <= src->curframe; i++) {
892 dst = dst_state->frame[i];
893 if (!dst) {
894 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
895 if (!dst)
896 return -ENOMEM;
897 dst_state->frame[i] = dst;
898 }
899 err = copy_func_state(dst, src->frame[i]);
900 if (err)
901 return err;
902 }
903 return 0;
904}
905
Alexei Starovoitov25897262019-06-15 12:12:20 -0700906static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
907{
908 while (st) {
909 u32 br = --st->branches;
910
911 /* WARN_ON(br > 1) technically makes sense here,
912 * but see comment in push_stack(), hence:
913 */
914 WARN_ONCE((int)br < 0,
915 "BUG update_branch_counts:branches_to_explore=%d\n",
916 br);
917 if (br)
918 break;
919 st = st->parent;
920 }
921}
922
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700923static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700924 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700925{
926 struct bpf_verifier_state *cur = env->cur_state;
927 struct bpf_verifier_stack_elem *elem, *head = env->head;
928 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700929
930 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700931 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700932
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700933 if (cur) {
934 err = copy_verifier_state(cur, &head->st);
935 if (err)
936 return err;
937 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700938 if (pop_log)
939 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700940 if (insn_idx)
941 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700942 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700943 *prev_insn_idx = head->prev_insn_idx;
944 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700945 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700946 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700947 env->head = elem;
948 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700949 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700950}
951
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100952static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100953 int insn_idx, int prev_insn_idx,
954 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700955{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700956 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100957 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700958 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700959
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700960 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700961 if (!elem)
962 goto err;
963
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700964 elem->insn_idx = insn_idx;
965 elem->prev_insn_idx = prev_insn_idx;
966 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700967 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700968 env->head = elem;
969 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700970 err = copy_verifier_state(&elem->st, cur);
971 if (err)
972 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100973 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700974 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
975 verbose(env, "The sequence of %d jumps is too complex.\n",
976 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700977 goto err;
978 }
Alexei Starovoitov25897262019-06-15 12:12:20 -0700979 if (elem->st.parent) {
980 ++elem->st.parent->branches;
981 /* WARN_ON(branches > 2) technically makes sense here,
982 * but
983 * 1. speculative states will bump 'branches' for non-branch
984 * instructions
985 * 2. is_state_visited() heuristics may decide not to create
986 * a new state for a sequence of branches and all such current
987 * and cloned states will be pointing to a single parent state
988 * which might have large 'branches' count.
989 */
990 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700991 return &elem->st;
992err:
Alexei Starovoitov58963512018-01-08 07:51:17 -0800993 free_verifier_state(env->cur_state, true);
994 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700995 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700996 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700997 return NULL;
998}
999
1000#define CALLER_SAVED_REGS 6
1001static const int caller_saved[CALLER_SAVED_REGS] = {
1002 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1003};
1004
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001005static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1006 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +01001007
Edward Creeb03c9f92017-08-07 15:26:36 +01001008/* Mark the unknown part of a register (variable offset or scalar value) as
1009 * known to have the value @imm.
1010 */
1011static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1012{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001013 /* Clear id, off, and union(map_ptr, range) */
1014 memset(((u8 *)reg) + sizeof(reg->type), 0,
1015 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
Edward Creeb03c9f92017-08-07 15:26:36 +01001016 reg->var_off = tnum_const(imm);
1017 reg->smin_value = (s64)imm;
1018 reg->smax_value = (s64)imm;
1019 reg->umin_value = imm;
1020 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001021
1022 reg->s32_min_value = (s32)imm;
1023 reg->s32_max_value = (s32)imm;
1024 reg->u32_min_value = (u32)imm;
1025 reg->u32_max_value = (u32)imm;
1026}
1027
1028static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1029{
1030 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1031 reg->s32_min_value = (s32)imm;
1032 reg->s32_max_value = (s32)imm;
1033 reg->u32_min_value = (u32)imm;
1034 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001035}
1036
Edward Creef1174f72017-08-07 15:26:19 +01001037/* Mark the 'variable offset' part of a register as zero. This should be
1038 * used only on registers holding a pointer type.
1039 */
1040static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1041{
Edward Creeb03c9f92017-08-07 15:26:36 +01001042 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001043}
1044
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001045static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1046{
1047 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001048 reg->type = SCALAR_VALUE;
1049}
1050
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001051static void mark_reg_known_zero(struct bpf_verifier_env *env,
1052 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001053{
1054 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001055 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001056 /* Something bad happened, let's kill all regs */
1057 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001058 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001059 return;
1060 }
1061 __mark_reg_known_zero(regs + regno);
1062}
1063
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001064static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1065{
1066 return type_is_pkt_pointer(reg->type);
1067}
1068
1069static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1070{
1071 return reg_is_pkt_pointer(reg) ||
1072 reg->type == PTR_TO_PACKET_END;
1073}
1074
1075/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1076static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1077 enum bpf_reg_type which)
1078{
1079 /* The register can already have a range from prior markings.
1080 * This is fine as long as it hasn't been advanced from its
1081 * origin.
1082 */
1083 return reg->type == which &&
1084 reg->id == 0 &&
1085 reg->off == 0 &&
1086 tnum_equals_const(reg->var_off, 0);
1087}
1088
John Fastabend3f50f132020-03-30 14:36:39 -07001089/* Reset the min/max bounds of a register */
1090static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1091{
1092 reg->smin_value = S64_MIN;
1093 reg->smax_value = S64_MAX;
1094 reg->umin_value = 0;
1095 reg->umax_value = U64_MAX;
1096
1097 reg->s32_min_value = S32_MIN;
1098 reg->s32_max_value = S32_MAX;
1099 reg->u32_min_value = 0;
1100 reg->u32_max_value = U32_MAX;
1101}
1102
1103static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1104{
1105 reg->smin_value = S64_MIN;
1106 reg->smax_value = S64_MAX;
1107 reg->umin_value = 0;
1108 reg->umax_value = U64_MAX;
1109}
1110
1111static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1112{
1113 reg->s32_min_value = S32_MIN;
1114 reg->s32_max_value = S32_MAX;
1115 reg->u32_min_value = 0;
1116 reg->u32_max_value = U32_MAX;
1117}
1118
1119static void __update_reg32_bounds(struct bpf_reg_state *reg)
1120{
1121 struct tnum var32_off = tnum_subreg(reg->var_off);
1122
1123 /* min signed is max(sign bit) | min(other bits) */
1124 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1125 var32_off.value | (var32_off.mask & S32_MIN));
1126 /* max signed is min(sign bit) | max(other bits) */
1127 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1128 var32_off.value | (var32_off.mask & S32_MAX));
1129 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1130 reg->u32_max_value = min(reg->u32_max_value,
1131 (u32)(var32_off.value | var32_off.mask));
1132}
1133
1134static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001135{
1136 /* min signed is max(sign bit) | min(other bits) */
1137 reg->smin_value = max_t(s64, reg->smin_value,
1138 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1139 /* max signed is min(sign bit) | max(other bits) */
1140 reg->smax_value = min_t(s64, reg->smax_value,
1141 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1142 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1143 reg->umax_value = min(reg->umax_value,
1144 reg->var_off.value | reg->var_off.mask);
1145}
1146
John Fastabend3f50f132020-03-30 14:36:39 -07001147static void __update_reg_bounds(struct bpf_reg_state *reg)
1148{
1149 __update_reg32_bounds(reg);
1150 __update_reg64_bounds(reg);
1151}
1152
Edward Creeb03c9f92017-08-07 15:26:36 +01001153/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001154static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1155{
1156 /* Learn sign from signed bounds.
1157 * If we cannot cross the sign boundary, then signed and unsigned bounds
1158 * are the same, so combine. This works even in the negative case, e.g.
1159 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1160 */
1161 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1162 reg->s32_min_value = reg->u32_min_value =
1163 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1164 reg->s32_max_value = reg->u32_max_value =
1165 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1166 return;
1167 }
1168 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1169 * boundary, so we must be careful.
1170 */
1171 if ((s32)reg->u32_max_value >= 0) {
1172 /* Positive. We can't learn anything from the smin, but smax
1173 * is positive, hence safe.
1174 */
1175 reg->s32_min_value = reg->u32_min_value;
1176 reg->s32_max_value = reg->u32_max_value =
1177 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1178 } else if ((s32)reg->u32_min_value < 0) {
1179 /* Negative. We can't learn anything from the smax, but smin
1180 * is negative, hence safe.
1181 */
1182 reg->s32_min_value = reg->u32_min_value =
1183 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1184 reg->s32_max_value = reg->u32_max_value;
1185 }
1186}
1187
1188static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001189{
1190 /* Learn sign from signed bounds.
1191 * If we cannot cross the sign boundary, then signed and unsigned bounds
1192 * are the same, so combine. This works even in the negative case, e.g.
1193 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1194 */
1195 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1196 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1197 reg->umin_value);
1198 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1199 reg->umax_value);
1200 return;
1201 }
1202 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1203 * boundary, so we must be careful.
1204 */
1205 if ((s64)reg->umax_value >= 0) {
1206 /* Positive. We can't learn anything from the smin, but smax
1207 * is positive, hence safe.
1208 */
1209 reg->smin_value = reg->umin_value;
1210 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1211 reg->umax_value);
1212 } else if ((s64)reg->umin_value < 0) {
1213 /* Negative. We can't learn anything from the smax, but smin
1214 * is negative, hence safe.
1215 */
1216 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1217 reg->umin_value);
1218 reg->smax_value = reg->umax_value;
1219 }
1220}
1221
John Fastabend3f50f132020-03-30 14:36:39 -07001222static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1223{
1224 __reg32_deduce_bounds(reg);
1225 __reg64_deduce_bounds(reg);
1226}
1227
Edward Creeb03c9f92017-08-07 15:26:36 +01001228/* Attempts to improve var_off based on unsigned min/max information */
1229static void __reg_bound_offset(struct bpf_reg_state *reg)
1230{
John Fastabend3f50f132020-03-30 14:36:39 -07001231 struct tnum var64_off = tnum_intersect(reg->var_off,
1232 tnum_range(reg->umin_value,
1233 reg->umax_value));
1234 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1235 tnum_range(reg->u32_min_value,
1236 reg->u32_max_value));
1237
1238 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001239}
1240
John Fastabend3f50f132020-03-30 14:36:39 -07001241static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001242{
John Fastabend3f50f132020-03-30 14:36:39 -07001243 reg->umin_value = reg->u32_min_value;
1244 reg->umax_value = reg->u32_max_value;
1245 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1246 * but must be positive otherwise set to worse case bounds
1247 * and refine later from tnum.
1248 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001249 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001250 reg->smax_value = reg->s32_max_value;
1251 else
1252 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001253 if (reg->s32_min_value >= 0)
1254 reg->smin_value = reg->s32_min_value;
1255 else
1256 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001257}
1258
1259static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1260{
1261 /* special case when 64-bit register has upper 32-bit register
1262 * zeroed. Typically happens after zext or <<32, >>32 sequence
1263 * allowing us to use 32-bit bounds directly,
1264 */
1265 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1266 __reg_assign_32_into_64(reg);
1267 } else {
1268 /* Otherwise the best we can do is push lower 32bit known and
1269 * unknown bits into register (var_off set from jmp logic)
1270 * then learn as much as possible from the 64-bit tnum
1271 * known and unknown bits. The previous smin/smax bounds are
1272 * invalid here because of jmp32 compare so mark them unknown
1273 * so they do not impact tnum bounds calculation.
1274 */
1275 __mark_reg64_unbounded(reg);
1276 __update_reg_bounds(reg);
1277 }
1278
1279 /* Intersecting with the old var_off might have improved our bounds
1280 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1281 * then new var_off is (0; 0x7f...fc) which improves our umax.
1282 */
1283 __reg_deduce_bounds(reg);
1284 __reg_bound_offset(reg);
1285 __update_reg_bounds(reg);
1286}
1287
1288static bool __reg64_bound_s32(s64 a)
1289{
1290 if (a > S32_MIN && a < S32_MAX)
1291 return true;
1292 return false;
1293}
1294
1295static bool __reg64_bound_u32(u64 a)
1296{
1297 if (a > U32_MIN && a < U32_MAX)
1298 return true;
1299 return false;
1300}
1301
1302static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1303{
1304 __mark_reg32_unbounded(reg);
1305
1306 if (__reg64_bound_s32(reg->smin_value))
1307 reg->s32_min_value = (s32)reg->smin_value;
1308 if (__reg64_bound_s32(reg->smax_value))
1309 reg->s32_max_value = (s32)reg->smax_value;
1310 if (__reg64_bound_u32(reg->umin_value))
1311 reg->u32_min_value = (u32)reg->umin_value;
1312 if (__reg64_bound_u32(reg->umax_value))
1313 reg->u32_max_value = (u32)reg->umax_value;
1314
1315 /* Intersecting with the old var_off might have improved our bounds
1316 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1317 * then new var_off is (0; 0x7f...fc) which improves our umax.
1318 */
1319 __reg_deduce_bounds(reg);
1320 __reg_bound_offset(reg);
1321 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001322}
1323
Edward Creef1174f72017-08-07 15:26:19 +01001324/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001325static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1326 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001327{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001328 /*
1329 * Clear type, id, off, and union(map_ptr, range) and
1330 * padding between 'type' and union
1331 */
1332 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001333 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001334 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001335 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001336 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001337 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001338}
1339
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001340static void mark_reg_unknown(struct bpf_verifier_env *env,
1341 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001342{
1343 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001344 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001345 /* Something bad happened, let's kill all regs except FP */
1346 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001347 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001348 return;
1349 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001350 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001351}
1352
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001353static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1354 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001355{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001356 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001357 reg->type = NOT_INIT;
1358}
1359
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001360static void mark_reg_not_init(struct bpf_verifier_env *env,
1361 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001362{
Edward Creef1174f72017-08-07 15:26:19 +01001363 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001364 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001365 /* Something bad happened, let's kill all regs except FP */
1366 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001367 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001368 return;
1369 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001370 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001371}
1372
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001373static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1374 struct bpf_reg_state *regs, u32 regno,
1375 enum bpf_reg_type reg_type, u32 btf_id)
1376{
1377 if (reg_type == SCALAR_VALUE) {
1378 mark_reg_unknown(env, regs, regno);
1379 return;
1380 }
1381 mark_reg_known_zero(env, regs, regno);
1382 regs[regno].type = PTR_TO_BTF_ID;
1383 regs[regno].btf_id = btf_id;
1384}
1385
Jiong Wang5327ed32019-05-24 23:25:12 +01001386#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001387static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001388 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001389{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001390 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001391 int i;
1392
Edward Creedc503a82017-08-15 20:34:35 +01001393 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001394 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001395 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001396 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001397 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001398 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001399
1400 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001401 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001402 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001403 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001404}
1405
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001406#define BPF_MAIN_FUNC (-1)
1407static void init_func_state(struct bpf_verifier_env *env,
1408 struct bpf_func_state *state,
1409 int callsite, int frameno, int subprogno)
1410{
1411 state->callsite = callsite;
1412 state->frameno = frameno;
1413 state->subprogno = subprogno;
1414 init_reg_state(env, state);
1415}
1416
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001417enum reg_arg_type {
1418 SRC_OP, /* register is used as source operand */
1419 DST_OP, /* register is used as destination operand */
1420 DST_OP_NO_MARK /* same as above, check only, don't mark */
1421};
1422
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001423static int cmp_subprogs(const void *a, const void *b)
1424{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001425 return ((struct bpf_subprog_info *)a)->start -
1426 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001427}
1428
1429static int find_subprog(struct bpf_verifier_env *env, int off)
1430{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001431 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001432
Jiong Wang9c8105b2018-05-02 16:17:18 -04001433 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1434 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001435 if (!p)
1436 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001437 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001438
1439}
1440
1441static int add_subprog(struct bpf_verifier_env *env, int off)
1442{
1443 int insn_cnt = env->prog->len;
1444 int ret;
1445
1446 if (off >= insn_cnt || off < 0) {
1447 verbose(env, "call to invalid destination\n");
1448 return -EINVAL;
1449 }
1450 ret = find_subprog(env, off);
1451 if (ret >= 0)
1452 return 0;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001453 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001454 verbose(env, "too many subprograms\n");
1455 return -E2BIG;
1456 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04001457 env->subprog_info[env->subprog_cnt++].start = off;
1458 sort(env->subprog_info, env->subprog_cnt,
1459 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001460 return 0;
1461}
1462
1463static int check_subprogs(struct bpf_verifier_env *env)
1464{
1465 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001466 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001467 struct bpf_insn *insn = env->prog->insnsi;
1468 int insn_cnt = env->prog->len;
1469
Jiong Wangf910cef2018-05-02 16:17:17 -04001470 /* Add entry function. */
1471 ret = add_subprog(env, 0);
1472 if (ret < 0)
1473 return ret;
1474
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001475 /* determine subprog starts. The end is one before the next starts */
1476 for (i = 0; i < insn_cnt; i++) {
1477 if (insn[i].code != (BPF_JMP | BPF_CALL))
1478 continue;
1479 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1480 continue;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001481 if (!env->bpf_capable) {
1482 verbose(env,
1483 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001484 return -EPERM;
1485 }
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001486 ret = add_subprog(env, i + insn[i].imm + 1);
1487 if (ret < 0)
1488 return ret;
1489 }
1490
Jiong Wang4cb3d992018-05-02 16:17:19 -04001491 /* Add a fake 'exit' subprog which could simplify subprog iteration
1492 * logic. 'subprog_cnt' should not be increased.
1493 */
1494 subprog[env->subprog_cnt].start = insn_cnt;
1495
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001496 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001497 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001498 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001499
1500 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001501 subprog_start = subprog[cur_subprog].start;
1502 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001503 for (i = 0; i < insn_cnt; i++) {
1504 u8 code = insn[i].code;
1505
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02001506 if (code == (BPF_JMP | BPF_CALL) &&
1507 insn[i].imm == BPF_FUNC_tail_call &&
1508 insn[i].src_reg != BPF_PSEUDO_CALL)
1509 subprog[cur_subprog].has_tail_call = true;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07001510 if (BPF_CLASS(code) == BPF_LD &&
1511 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1512 subprog[cur_subprog].has_ld_abs = true;
Jiong Wang092ed092019-01-26 12:26:01 -05001513 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001514 goto next;
1515 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1516 goto next;
1517 off = i + insn[i].off + 1;
1518 if (off < subprog_start || off >= subprog_end) {
1519 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1520 return -EINVAL;
1521 }
1522next:
1523 if (i == subprog_end - 1) {
1524 /* to avoid fall-through from one subprog into another
1525 * the last insn of the subprog should be either exit
1526 * or unconditional jump back
1527 */
1528 if (code != (BPF_JMP | BPF_EXIT) &&
1529 code != (BPF_JMP | BPF_JA)) {
1530 verbose(env, "last insn is not an exit or jmp\n");
1531 return -EINVAL;
1532 }
1533 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001534 cur_subprog++;
1535 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001536 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001537 }
1538 }
1539 return 0;
1540}
1541
Edward Cree679c7822018-08-22 20:02:19 +01001542/* Parentage chain of this register (or stack slot) should take care of all
1543 * issues like callee-saved registers, stack slot allocation time, etc.
1544 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001545static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001546 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001547 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001548{
1549 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001550 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001551
1552 while (parent) {
1553 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001554 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001555 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001556 if (parent->live & REG_LIVE_DONE) {
1557 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1558 reg_type_str[parent->type],
1559 parent->var_off.value, parent->off);
1560 return -EFAULT;
1561 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001562 /* The first condition is more likely to be true than the
1563 * second, checked it first.
1564 */
1565 if ((parent->live & REG_LIVE_READ) == flag ||
1566 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001567 /* The parentage chain never changes and
1568 * this parent was already marked as LIVE_READ.
1569 * There is no need to keep walking the chain again and
1570 * keep re-marking all parents as LIVE_READ.
1571 * This case happens when the same register is read
1572 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001573 * Also, if parent has the stronger REG_LIVE_READ64 set,
1574 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001575 */
1576 break;
Edward Creedc503a82017-08-15 20:34:35 +01001577 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001578 parent->live |= flag;
1579 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1580 if (flag == REG_LIVE_READ64)
1581 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001582 state = parent;
1583 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001584 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001585 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001586 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001587
1588 if (env->longest_mark_read_walk < cnt)
1589 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001590 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001591}
1592
Jiong Wang5327ed32019-05-24 23:25:12 +01001593/* This function is supposed to be used by the following 32-bit optimization
1594 * code only. It returns TRUE if the source or destination register operates
1595 * on 64-bit, otherwise return FALSE.
1596 */
1597static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1598 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1599{
1600 u8 code, class, op;
1601
1602 code = insn->code;
1603 class = BPF_CLASS(code);
1604 op = BPF_OP(code);
1605 if (class == BPF_JMP) {
1606 /* BPF_EXIT for "main" will reach here. Return TRUE
1607 * conservatively.
1608 */
1609 if (op == BPF_EXIT)
1610 return true;
1611 if (op == BPF_CALL) {
1612 /* BPF to BPF call will reach here because of marking
1613 * caller saved clobber with DST_OP_NO_MARK for which we
1614 * don't care the register def because they are anyway
1615 * marked as NOT_INIT already.
1616 */
1617 if (insn->src_reg == BPF_PSEUDO_CALL)
1618 return false;
1619 /* Helper call will reach here because of arg type
1620 * check, conservatively return TRUE.
1621 */
1622 if (t == SRC_OP)
1623 return true;
1624
1625 return false;
1626 }
1627 }
1628
1629 if (class == BPF_ALU64 || class == BPF_JMP ||
1630 /* BPF_END always use BPF_ALU class. */
1631 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1632 return true;
1633
1634 if (class == BPF_ALU || class == BPF_JMP32)
1635 return false;
1636
1637 if (class == BPF_LDX) {
1638 if (t != SRC_OP)
1639 return BPF_SIZE(code) == BPF_DW;
1640 /* LDX source must be ptr. */
1641 return true;
1642 }
1643
1644 if (class == BPF_STX) {
1645 if (reg->type != SCALAR_VALUE)
1646 return true;
1647 return BPF_SIZE(code) == BPF_DW;
1648 }
1649
1650 if (class == BPF_LD) {
1651 u8 mode = BPF_MODE(code);
1652
1653 /* LD_IMM64 */
1654 if (mode == BPF_IMM)
1655 return true;
1656
1657 /* Both LD_IND and LD_ABS return 32-bit data. */
1658 if (t != SRC_OP)
1659 return false;
1660
1661 /* Implicit ctx ptr. */
1662 if (regno == BPF_REG_6)
1663 return true;
1664
1665 /* Explicit source could be any width. */
1666 return true;
1667 }
1668
1669 if (class == BPF_ST)
1670 /* The only source register for BPF_ST is a ptr. */
1671 return true;
1672
1673 /* Conservatively return true at default. */
1674 return true;
1675}
1676
Jiong Wangb325fbc2019-05-24 23:25:13 +01001677/* Return TRUE if INSN doesn't have explicit value define. */
1678static bool insn_no_def(struct bpf_insn *insn)
1679{
1680 u8 class = BPF_CLASS(insn->code);
1681
1682 return (class == BPF_JMP || class == BPF_JMP32 ||
1683 class == BPF_STX || class == BPF_ST);
1684}
1685
1686/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1687static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1688{
1689 if (insn_no_def(insn))
1690 return false;
1691
1692 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1693}
1694
Jiong Wang5327ed32019-05-24 23:25:12 +01001695static void mark_insn_zext(struct bpf_verifier_env *env,
1696 struct bpf_reg_state *reg)
1697{
1698 s32 def_idx = reg->subreg_def;
1699
1700 if (def_idx == DEF_NOT_SUBREG)
1701 return;
1702
1703 env->insn_aux_data[def_idx - 1].zext_dst = true;
1704 /* The dst will be zero extended, so won't be sub-register anymore. */
1705 reg->subreg_def = DEF_NOT_SUBREG;
1706}
1707
Edward Creedc503a82017-08-15 20:34:35 +01001708static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001709 enum reg_arg_type t)
1710{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001711 struct bpf_verifier_state *vstate = env->cur_state;
1712 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01001713 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01001714 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01001715 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01001716
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001717 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001718 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001719 return -EINVAL;
1720 }
1721
Jiong Wangc342dc12019-04-12 22:59:37 +01001722 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01001723 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001724 if (t == SRC_OP) {
1725 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01001726 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001727 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001728 return -EACCES;
1729 }
Edward Cree679c7822018-08-22 20:02:19 +01001730 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01001731 if (regno == BPF_REG_FP)
1732 return 0;
1733
Jiong Wang5327ed32019-05-24 23:25:12 +01001734 if (rw64)
1735 mark_insn_zext(env, reg);
1736
1737 return mark_reg_read(env, reg, reg->parent,
1738 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001739 } else {
1740 /* check whether register used as dest operand can be written to */
1741 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001742 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001743 return -EACCES;
1744 }
Jiong Wangc342dc12019-04-12 22:59:37 +01001745 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01001746 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001747 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001748 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001749 }
1750 return 0;
1751}
1752
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001753/* for any branch, call, exit record the history of jmps in the given state */
1754static int push_jmp_history(struct bpf_verifier_env *env,
1755 struct bpf_verifier_state *cur)
1756{
1757 u32 cnt = cur->jmp_history_cnt;
1758 struct bpf_idx_pair *p;
1759
1760 cnt++;
1761 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1762 if (!p)
1763 return -ENOMEM;
1764 p[cnt - 1].idx = env->insn_idx;
1765 p[cnt - 1].prev_idx = env->prev_insn_idx;
1766 cur->jmp_history = p;
1767 cur->jmp_history_cnt = cnt;
1768 return 0;
1769}
1770
1771/* Backtrack one insn at a time. If idx is not at the top of recorded
1772 * history then previous instruction came from straight line execution.
1773 */
1774static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1775 u32 *history)
1776{
1777 u32 cnt = *history;
1778
1779 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1780 i = st->jmp_history[cnt - 1].prev_idx;
1781 (*history)--;
1782 } else {
1783 i--;
1784 }
1785 return i;
1786}
1787
1788/* For given verifier state backtrack_insn() is called from the last insn to
1789 * the first insn. Its purpose is to compute a bitmask of registers and
1790 * stack slots that needs precision in the parent verifier state.
1791 */
1792static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1793 u32 *reg_mask, u64 *stack_mask)
1794{
1795 const struct bpf_insn_cbs cbs = {
1796 .cb_print = verbose,
1797 .private_data = env,
1798 };
1799 struct bpf_insn *insn = env->prog->insnsi + idx;
1800 u8 class = BPF_CLASS(insn->code);
1801 u8 opcode = BPF_OP(insn->code);
1802 u8 mode = BPF_MODE(insn->code);
1803 u32 dreg = 1u << insn->dst_reg;
1804 u32 sreg = 1u << insn->src_reg;
1805 u32 spi;
1806
1807 if (insn->code == 0)
1808 return 0;
1809 if (env->log.level & BPF_LOG_LEVEL) {
1810 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1811 verbose(env, "%d: ", idx);
1812 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1813 }
1814
1815 if (class == BPF_ALU || class == BPF_ALU64) {
1816 if (!(*reg_mask & dreg))
1817 return 0;
1818 if (opcode == BPF_MOV) {
1819 if (BPF_SRC(insn->code) == BPF_X) {
1820 /* dreg = sreg
1821 * dreg needs precision after this insn
1822 * sreg needs precision before this insn
1823 */
1824 *reg_mask &= ~dreg;
1825 *reg_mask |= sreg;
1826 } else {
1827 /* dreg = K
1828 * dreg needs precision after this insn.
1829 * Corresponding register is already marked
1830 * as precise=true in this verifier state.
1831 * No further markings in parent are necessary
1832 */
1833 *reg_mask &= ~dreg;
1834 }
1835 } else {
1836 if (BPF_SRC(insn->code) == BPF_X) {
1837 /* dreg += sreg
1838 * both dreg and sreg need precision
1839 * before this insn
1840 */
1841 *reg_mask |= sreg;
1842 } /* else dreg += K
1843 * dreg still needs precision before this insn
1844 */
1845 }
1846 } else if (class == BPF_LDX) {
1847 if (!(*reg_mask & dreg))
1848 return 0;
1849 *reg_mask &= ~dreg;
1850
1851 /* scalars can only be spilled into stack w/o losing precision.
1852 * Load from any other memory can be zero extended.
1853 * The desire to keep that precision is already indicated
1854 * by 'precise' mark in corresponding register of this state.
1855 * No further tracking necessary.
1856 */
1857 if (insn->src_reg != BPF_REG_FP)
1858 return 0;
1859 if (BPF_SIZE(insn->code) != BPF_DW)
1860 return 0;
1861
1862 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1863 * that [fp - off] slot contains scalar that needs to be
1864 * tracked with precision
1865 */
1866 spi = (-insn->off - 1) / BPF_REG_SIZE;
1867 if (spi >= 64) {
1868 verbose(env, "BUG spi %d\n", spi);
1869 WARN_ONCE(1, "verifier backtracking bug");
1870 return -EFAULT;
1871 }
1872 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001873 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001874 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001875 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001876 * to access memory. It means backtracking
1877 * encountered a case of pointer subtraction.
1878 */
1879 return -ENOTSUPP;
1880 /* scalars can only be spilled into stack */
1881 if (insn->dst_reg != BPF_REG_FP)
1882 return 0;
1883 if (BPF_SIZE(insn->code) != BPF_DW)
1884 return 0;
1885 spi = (-insn->off - 1) / BPF_REG_SIZE;
1886 if (spi >= 64) {
1887 verbose(env, "BUG spi %d\n", spi);
1888 WARN_ONCE(1, "verifier backtracking bug");
1889 return -EFAULT;
1890 }
1891 if (!(*stack_mask & (1ull << spi)))
1892 return 0;
1893 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001894 if (class == BPF_STX)
1895 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001896 } else if (class == BPF_JMP || class == BPF_JMP32) {
1897 if (opcode == BPF_CALL) {
1898 if (insn->src_reg == BPF_PSEUDO_CALL)
1899 return -ENOTSUPP;
1900 /* regular helper call sets R0 */
1901 *reg_mask &= ~1;
1902 if (*reg_mask & 0x3f) {
1903 /* if backtracing was looking for registers R1-R5
1904 * they should have been found already.
1905 */
1906 verbose(env, "BUG regs %x\n", *reg_mask);
1907 WARN_ONCE(1, "verifier backtracking bug");
1908 return -EFAULT;
1909 }
1910 } else if (opcode == BPF_EXIT) {
1911 return -ENOTSUPP;
1912 }
1913 } else if (class == BPF_LD) {
1914 if (!(*reg_mask & dreg))
1915 return 0;
1916 *reg_mask &= ~dreg;
1917 /* It's ld_imm64 or ld_abs or ld_ind.
1918 * For ld_imm64 no further tracking of precision
1919 * into parent is necessary
1920 */
1921 if (mode == BPF_IND || mode == BPF_ABS)
1922 /* to be analyzed */
1923 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001924 }
1925 return 0;
1926}
1927
1928/* the scalar precision tracking algorithm:
1929 * . at the start all registers have precise=false.
1930 * . scalar ranges are tracked as normal through alu and jmp insns.
1931 * . once precise value of the scalar register is used in:
1932 * . ptr + scalar alu
1933 * . if (scalar cond K|scalar)
1934 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1935 * backtrack through the verifier states and mark all registers and
1936 * stack slots with spilled constants that these scalar regisers
1937 * should be precise.
1938 * . during state pruning two registers (or spilled stack slots)
1939 * are equivalent if both are not precise.
1940 *
1941 * Note the verifier cannot simply walk register parentage chain,
1942 * since many different registers and stack slots could have been
1943 * used to compute single precise scalar.
1944 *
1945 * The approach of starting with precise=true for all registers and then
1946 * backtrack to mark a register as not precise when the verifier detects
1947 * that program doesn't care about specific value (e.g., when helper
1948 * takes register as ARG_ANYTHING parameter) is not safe.
1949 *
1950 * It's ok to walk single parentage chain of the verifier states.
1951 * It's possible that this backtracking will go all the way till 1st insn.
1952 * All other branches will be explored for needing precision later.
1953 *
1954 * The backtracking needs to deal with cases like:
1955 * 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)
1956 * r9 -= r8
1957 * r5 = r9
1958 * if r5 > 0x79f goto pc+7
1959 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1960 * r5 += 1
1961 * ...
1962 * call bpf_perf_event_output#25
1963 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1964 *
1965 * and this case:
1966 * r6 = 1
1967 * call foo // uses callee's r6 inside to compute r0
1968 * r0 += r6
1969 * if r0 == 0 goto
1970 *
1971 * to track above reg_mask/stack_mask needs to be independent for each frame.
1972 *
1973 * Also if parent's curframe > frame where backtracking started,
1974 * the verifier need to mark registers in both frames, otherwise callees
1975 * may incorrectly prune callers. This is similar to
1976 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1977 *
1978 * For now backtracking falls back into conservative marking.
1979 */
1980static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1981 struct bpf_verifier_state *st)
1982{
1983 struct bpf_func_state *func;
1984 struct bpf_reg_state *reg;
1985 int i, j;
1986
1987 /* big hammer: mark all scalars precise in this path.
1988 * pop_stack may still get !precise scalars.
1989 */
1990 for (; st; st = st->parent)
1991 for (i = 0; i <= st->curframe; i++) {
1992 func = st->frame[i];
1993 for (j = 0; j < BPF_REG_FP; j++) {
1994 reg = &func->regs[j];
1995 if (reg->type != SCALAR_VALUE)
1996 continue;
1997 reg->precise = true;
1998 }
1999 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2000 if (func->stack[j].slot_type[0] != STACK_SPILL)
2001 continue;
2002 reg = &func->stack[j].spilled_ptr;
2003 if (reg->type != SCALAR_VALUE)
2004 continue;
2005 reg->precise = true;
2006 }
2007 }
2008}
2009
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002010static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2011 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002012{
2013 struct bpf_verifier_state *st = env->cur_state;
2014 int first_idx = st->first_insn_idx;
2015 int last_idx = env->insn_idx;
2016 struct bpf_func_state *func;
2017 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002018 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2019 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002020 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002021 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002022 int i, err;
2023
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002024 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002025 return 0;
2026
2027 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002028 if (regno >= 0) {
2029 reg = &func->regs[regno];
2030 if (reg->type != SCALAR_VALUE) {
2031 WARN_ONCE(1, "backtracing misuse");
2032 return -EFAULT;
2033 }
2034 if (!reg->precise)
2035 new_marks = true;
2036 else
2037 reg_mask = 0;
2038 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002039 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002040
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002041 while (spi >= 0) {
2042 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2043 stack_mask = 0;
2044 break;
2045 }
2046 reg = &func->stack[spi].spilled_ptr;
2047 if (reg->type != SCALAR_VALUE) {
2048 stack_mask = 0;
2049 break;
2050 }
2051 if (!reg->precise)
2052 new_marks = true;
2053 else
2054 stack_mask = 0;
2055 reg->precise = true;
2056 break;
2057 }
2058
2059 if (!new_marks)
2060 return 0;
2061 if (!reg_mask && !stack_mask)
2062 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002063 for (;;) {
2064 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002065 u32 history = st->jmp_history_cnt;
2066
2067 if (env->log.level & BPF_LOG_LEVEL)
2068 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2069 for (i = last_idx;;) {
2070 if (skip_first) {
2071 err = 0;
2072 skip_first = false;
2073 } else {
2074 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2075 }
2076 if (err == -ENOTSUPP) {
2077 mark_all_scalars_precise(env, st);
2078 return 0;
2079 } else if (err) {
2080 return err;
2081 }
2082 if (!reg_mask && !stack_mask)
2083 /* Found assignment(s) into tracked register in this state.
2084 * Since this state is already marked, just return.
2085 * Nothing to be tracked further in the parent state.
2086 */
2087 return 0;
2088 if (i == first_idx)
2089 break;
2090 i = get_prev_insn_idx(st, i, &history);
2091 if (i >= env->prog->len) {
2092 /* This can happen if backtracking reached insn 0
2093 * and there are still reg_mask or stack_mask
2094 * to backtrack.
2095 * It means the backtracking missed the spot where
2096 * particular register was initialized with a constant.
2097 */
2098 verbose(env, "BUG backtracking idx %d\n", i);
2099 WARN_ONCE(1, "verifier backtracking bug");
2100 return -EFAULT;
2101 }
2102 }
2103 st = st->parent;
2104 if (!st)
2105 break;
2106
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002107 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002108 func = st->frame[st->curframe];
2109 bitmap_from_u64(mask, reg_mask);
2110 for_each_set_bit(i, mask, 32) {
2111 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002112 if (reg->type != SCALAR_VALUE) {
2113 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002114 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002115 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002116 if (!reg->precise)
2117 new_marks = true;
2118 reg->precise = true;
2119 }
2120
2121 bitmap_from_u64(mask, stack_mask);
2122 for_each_set_bit(i, mask, 64) {
2123 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002124 /* the sequence of instructions:
2125 * 2: (bf) r3 = r10
2126 * 3: (7b) *(u64 *)(r3 -8) = r0
2127 * 4: (79) r4 = *(u64 *)(r10 -8)
2128 * doesn't contain jmps. It's backtracked
2129 * as a single block.
2130 * During backtracking insn 3 is not recognized as
2131 * stack access, so at the end of backtracking
2132 * stack slot fp-8 is still marked in stack_mask.
2133 * However the parent state may not have accessed
2134 * fp-8 and it's "unallocated" stack space.
2135 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002136 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002137 mark_all_scalars_precise(env, st);
2138 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002139 }
2140
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002141 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2142 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002143 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002144 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002145 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002146 if (reg->type != SCALAR_VALUE) {
2147 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002148 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002149 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002150 if (!reg->precise)
2151 new_marks = true;
2152 reg->precise = true;
2153 }
2154 if (env->log.level & BPF_LOG_LEVEL) {
2155 print_verifier_state(env, func);
2156 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2157 new_marks ? "didn't have" : "already had",
2158 reg_mask, stack_mask);
2159 }
2160
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002161 if (!reg_mask && !stack_mask)
2162 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002163 if (!new_marks)
2164 break;
2165
2166 last_idx = st->last_insn_idx;
2167 first_idx = st->first_insn_idx;
2168 }
2169 return 0;
2170}
2171
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002172static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2173{
2174 return __mark_chain_precision(env, regno, -1);
2175}
2176
2177static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2178{
2179 return __mark_chain_precision(env, -1, spi);
2180}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002181
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002182static bool is_spillable_regtype(enum bpf_reg_type type)
2183{
2184 switch (type) {
2185 case PTR_TO_MAP_VALUE:
2186 case PTR_TO_MAP_VALUE_OR_NULL:
2187 case PTR_TO_STACK:
2188 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002189 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002190 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002191 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002192 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002193 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002194 case PTR_TO_SOCKET:
2195 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002196 case PTR_TO_SOCK_COMMON:
2197 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002198 case PTR_TO_TCP_SOCK:
2199 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002200 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002201 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002202 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002203 case PTR_TO_RDONLY_BUF:
2204 case PTR_TO_RDONLY_BUF_OR_NULL:
2205 case PTR_TO_RDWR_BUF:
2206 case PTR_TO_RDWR_BUF_OR_NULL:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002207 return true;
2208 default:
2209 return false;
2210 }
2211}
2212
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002213/* Does this register contain a constant zero? */
2214static bool register_is_null(struct bpf_reg_state *reg)
2215{
2216 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2217}
2218
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002219static bool register_is_const(struct bpf_reg_state *reg)
2220{
2221 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2222}
2223
Jann Horn6e7e63c2020-04-17 02:00:06 +02002224static bool __is_pointer_value(bool allow_ptr_leaks,
2225 const struct bpf_reg_state *reg)
2226{
2227 if (allow_ptr_leaks)
2228 return false;
2229
2230 return reg->type != SCALAR_VALUE;
2231}
2232
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002233static void save_register_state(struct bpf_func_state *state,
2234 int spi, struct bpf_reg_state *reg)
2235{
2236 int i;
2237
2238 state->stack[spi].spilled_ptr = *reg;
2239 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2240
2241 for (i = 0; i < BPF_REG_SIZE; i++)
2242 state->stack[spi].slot_type[i] = STACK_SPILL;
2243}
2244
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002245/* check_stack_read/write functions track spill/fill of registers,
2246 * stack boundary and alignment are checked in check_mem_access()
2247 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002248static int check_stack_write(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002249 struct bpf_func_state *state, /* func where register points to */
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002250 int off, int size, int value_regno, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002251{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002252 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002253 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002254 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002255 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002256
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002257 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07002258 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002259 if (err)
2260 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002261 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2262 * so it's aligned access and [off, off + size) are within stack limits
2263 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002264 if (!env->allow_ptr_leaks &&
2265 state->stack[spi].slot_type[0] == STACK_SPILL &&
2266 size != BPF_REG_SIZE) {
2267 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2268 return -EACCES;
2269 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002270
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002271 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002272 if (value_regno >= 0)
2273 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002274
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002275 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002276 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002277 if (dst_reg != BPF_REG_FP) {
2278 /* The backtracking logic can only recognize explicit
2279 * stack slot address like [fp - 8]. Other spill of
2280 * scalar via different register has to be conervative.
2281 * Backtrack from here and mark all registers as precise
2282 * that contributed into 'reg' being a constant.
2283 */
2284 err = mark_chain_precision(env, value_regno);
2285 if (err)
2286 return err;
2287 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002288 save_register_state(state, spi, reg);
2289 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002290 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002291 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002292 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002293 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002294 return -EACCES;
2295 }
2296
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002297 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002298 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2299 return -EINVAL;
2300 }
2301
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002302 if (!env->bypass_spec_v4) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002303 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002304
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002305 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2306 register_is_const(&state->stack[spi].spilled_ptr))
2307 sanitize = true;
2308 for (i = 0; i < BPF_REG_SIZE; i++)
2309 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2310 sanitize = true;
2311 break;
2312 }
2313 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002314 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2315 int soff = (-spi - 1) * BPF_REG_SIZE;
2316
2317 /* detected reuse of integer stack slot with a pointer
2318 * which means either llvm is reusing stack slot or
2319 * an attacker is trying to exploit CVE-2018-3639
2320 * (speculative store bypass)
2321 * Have to sanitize that slot with preemptive
2322 * store of zero.
2323 */
2324 if (*poff && *poff != soff) {
2325 /* disallow programs where single insn stores
2326 * into two different stack slots, since verifier
2327 * cannot sanitize them
2328 */
2329 verbose(env,
2330 "insn %d cannot access two stack slots fp%d and fp%d",
2331 insn_idx, *poff, soff);
2332 return -EINVAL;
2333 }
2334 *poff = soff;
2335 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002336 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002337 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002338 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002339 u8 type = STACK_MISC;
2340
Edward Cree679c7822018-08-22 20:02:19 +01002341 /* regular write of data into stack destroys any spilled ptr */
2342 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002343 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2344 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2345 for (i = 0; i < BPF_REG_SIZE; i++)
2346 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002347
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002348 /* only mark the slot as written if all 8 bytes were written
2349 * otherwise read propagation may incorrectly stop too soon
2350 * when stack slots are partially written.
2351 * This heuristic means that read propagation will be
2352 * conservative, since it will add reg_live_read marks
2353 * to stack slots all the way to first state when programs
2354 * writes+reads less than 8 bytes
2355 */
2356 if (size == BPF_REG_SIZE)
2357 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2358
2359 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002360 if (reg && register_is_null(reg)) {
2361 /* backtracking doesn't work for STACK_ZERO yet. */
2362 err = mark_chain_precision(env, value_regno);
2363 if (err)
2364 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002365 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002366 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002367
Jiong Wang0bae2d42018-12-15 03:34:40 -05002368 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002369 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002370 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002371 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002372 }
2373 return 0;
2374}
2375
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002376static int check_stack_read(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002377 struct bpf_func_state *reg_state /* func where register points to */,
2378 int off, int size, int value_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002379{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002380 struct bpf_verifier_state *vstate = env->cur_state;
2381 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002382 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002383 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002384 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002385
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002386 if (reg_state->allocated_stack <= slot) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002387 verbose(env, "invalid read from stack off %d+0 size %d\n",
2388 off, size);
2389 return -EACCES;
2390 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002391 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002392 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002393
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002394 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002395 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002396 if (reg->type != SCALAR_VALUE) {
2397 verbose_linfo(env, env->insn_idx, "; ");
2398 verbose(env, "invalid size of register fill\n");
2399 return -EACCES;
2400 }
2401 if (value_regno >= 0) {
2402 mark_reg_unknown(env, state->regs, value_regno);
2403 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2404 }
2405 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2406 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002407 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002408 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002409 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002410 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002411 return -EACCES;
2412 }
2413 }
2414
Edward Creedc503a82017-08-15 20:34:35 +01002415 if (value_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002416 /* restore register state from stack */
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002417 state->regs[value_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002418 /* mark reg as written since spilled pointer state likely
2419 * has its liveness marks cleared by is_state_visited()
2420 * which resets stack/reg liveness for state transitions
2421 */
2422 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02002423 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2424 /* If value_regno==-1, the caller is asking us whether
2425 * it is acceptable to use this value as a SCALAR_VALUE
2426 * (e.g. for XADD).
2427 * We must not allow unprivileged callers to do that
2428 * with spilled pointers.
2429 */
2430 verbose(env, "leaking pointer from stack off %d\n",
2431 off);
2432 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01002433 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002434 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002435 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002436 int zeros = 0;
2437
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002438 for (i = 0; i < size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002439 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2440 continue;
2441 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2442 zeros++;
2443 continue;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002444 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002445 verbose(env, "invalid read from stack off %d+%d size %d\n",
2446 off, i, size);
2447 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002448 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002449 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002450 if (value_regno >= 0) {
2451 if (zeros == size) {
2452 /* any size read into register is zero extended,
2453 * so the whole register == const_zero
2454 */
2455 __mark_reg_const_zero(&state->regs[value_regno]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002456 /* backtracking doesn't support STACK_ZERO yet,
2457 * so mark it precise here, so that later
2458 * backtracking can stop here.
2459 * Backtracking may not need this if this register
2460 * doesn't participate in pointer adjustment.
2461 * Forward propagation of precise flag is not
2462 * necessary either. This mark is only to stop
2463 * backtracking. Any register that contributed
2464 * to const 0 was marked precise before spill.
2465 */
2466 state->regs[value_regno].precise = true;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002467 } else {
2468 /* have read misc data from the stack */
2469 mark_reg_unknown(env, state->regs, value_regno);
2470 }
2471 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2472 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002473 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002474 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002475}
2476
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002477static int check_stack_access(struct bpf_verifier_env *env,
2478 const struct bpf_reg_state *reg,
2479 int off, int size)
2480{
2481 /* Stack accesses must be at a fixed offset, so that we
2482 * can determine what type of data were returned. See
2483 * check_stack_read().
2484 */
2485 if (!tnum_is_const(reg->var_off)) {
2486 char tn_buf[48];
2487
2488 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrey Ignatov1fbd20f2019-04-03 23:22:43 -07002489 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002490 tn_buf, off, size);
2491 return -EACCES;
2492 }
2493
2494 if (off >= 0 || off < -MAX_BPF_STACK) {
2495 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2496 return -EACCES;
2497 }
2498
2499 return 0;
2500}
2501
Daniel Borkmann591fe982019-04-09 23:20:05 +02002502static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2503 int off, int size, enum bpf_access_type type)
2504{
2505 struct bpf_reg_state *regs = cur_regs(env);
2506 struct bpf_map *map = regs[regno].map_ptr;
2507 u32 cap = bpf_map_flags_to_cap(map);
2508
2509 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2510 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2511 map->value_size, off, size);
2512 return -EACCES;
2513 }
2514
2515 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2516 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2517 map->value_size, off, size);
2518 return -EACCES;
2519 }
2520
2521 return 0;
2522}
2523
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002524/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2525static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2526 int off, int size, u32 mem_size,
2527 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002528{
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002529 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2530 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002531
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002532 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2533 return 0;
2534
2535 reg = &cur_regs(env)[regno];
2536 switch (reg->type) {
2537 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002538 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002539 mem_size, off, size);
2540 break;
2541 case PTR_TO_PACKET:
2542 case PTR_TO_PACKET_META:
2543 case PTR_TO_PACKET_END:
2544 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2545 off, size, regno, reg->id, off, mem_size);
2546 break;
2547 case PTR_TO_MEM:
2548 default:
2549 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2550 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002551 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002552
2553 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002554}
2555
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002556/* check read/write into a memory region with possible variable offset */
2557static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2558 int off, int size, u32 mem_size,
2559 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002560{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002561 struct bpf_verifier_state *vstate = env->cur_state;
2562 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002563 struct bpf_reg_state *reg = &state->regs[regno];
2564 int err;
2565
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002566 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01002567 * need to try adding each of min_value and max_value to off
2568 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002569 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002570 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002571 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002572
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002573 /* The minimum value is only important with signed
2574 * comparisons where we can't assume the floor of a
2575 * value is 0. If we are using signed variables for our
2576 * index'es we need to make sure that whatever we use
2577 * will have a set floor within our range.
2578 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002579 if (reg->smin_value < 0 &&
2580 (reg->smin_value == S64_MIN ||
2581 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2582 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002583 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 -08002584 regno);
2585 return -EACCES;
2586 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002587 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2588 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002589 if (err) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002590 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002591 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002592 return err;
2593 }
2594
Edward Creeb03c9f92017-08-07 15:26:36 +01002595 /* If we haven't set a max value then we need to bail since we can't be
2596 * sure we won't do bad things.
2597 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002598 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002599 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002600 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002601 regno);
2602 return -EACCES;
2603 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002604 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2605 mem_size, zero_size_allowed);
2606 if (err) {
2607 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002608 regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002609 return err;
2610 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002611
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002612 return 0;
2613}
2614
2615/* check read/write into a map element with possible variable offset */
2616static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2617 int off, int size, bool zero_size_allowed)
2618{
2619 struct bpf_verifier_state *vstate = env->cur_state;
2620 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2621 struct bpf_reg_state *reg = &state->regs[regno];
2622 struct bpf_map *map = reg->map_ptr;
2623 int err;
2624
2625 err = check_mem_region_access(env, regno, off, size, map->value_size,
2626 zero_size_allowed);
2627 if (err)
2628 return err;
2629
2630 if (map_value_has_spin_lock(map)) {
2631 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002632
2633 /* if any part of struct bpf_spin_lock can be touched by
2634 * load/store reject this program.
2635 * To check that [x1, x2) overlaps with [y1, y2)
2636 * it is sufficient to check x1 < y2 && y1 < x2.
2637 */
2638 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2639 lock < reg->umax_value + off + size) {
2640 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2641 return -EACCES;
2642 }
2643 }
Edward Creef1174f72017-08-07 15:26:19 +01002644 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002645}
2646
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002647#define MAX_PACKET_OFF 0xffff
2648
Udip Pant7e407812020-08-25 16:20:00 -07002649static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2650{
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +02002651 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
Udip Pant7e407812020-08-25 16:20:00 -07002652}
2653
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01002654static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002655 const struct bpf_call_arg_meta *meta,
2656 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002657{
Udip Pant7e407812020-08-25 16:20:00 -07002658 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2659
2660 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002661 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002662 case BPF_PROG_TYPE_LWT_IN:
2663 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01002664 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07002665 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002666 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02002667 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002668 if (t == BPF_WRITE)
2669 return false;
Alexander Alemayhu7e57fbb2017-02-14 00:02:35 +01002670 /* fallthrough */
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002671
2672 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002673 case BPF_PROG_TYPE_SCHED_CLS:
2674 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002675 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002676 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07002677 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07002678 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002679 if (meta)
2680 return meta->pkt_access;
2681
2682 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002683 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07002684
2685 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2686 if (t == BPF_WRITE)
2687 env->seen_direct_write = true;
2688
2689 return true;
2690
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002691 default:
2692 return false;
2693 }
2694}
2695
Edward Creef1174f72017-08-07 15:26:19 +01002696static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002697 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01002698{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002699 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01002700 struct bpf_reg_state *reg = &regs[regno];
2701 int err;
2702
2703 /* We may have added a variable offset to the packet pointer; but any
2704 * reg->range we have comes after that. We are only checking the fixed
2705 * offset.
2706 */
2707
2708 /* We don't allow negative numbers, because we aren't tracking enough
2709 * detail to prove they're safe.
2710 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002711 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002712 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 +01002713 regno);
2714 return -EACCES;
2715 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002716 err = __check_mem_access(env, regno, off, size, reg->range,
2717 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01002718 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002719 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01002720 return err;
2721 }
Jiong Wange6478152018-11-08 04:08:42 -05002722
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002723 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05002724 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2725 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002726 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05002727 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2728 */
2729 env->prog->aux->max_pkt_offset =
2730 max_t(u32, env->prog->aux->max_pkt_offset,
2731 off + reg->umax_value + size - 1);
2732
Edward Creef1174f72017-08-07 15:26:19 +01002733 return err;
2734}
2735
2736/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07002737static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002738 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2739 u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002740{
Daniel Borkmannf96da092017-07-02 02:13:27 +02002741 struct bpf_insn_access_aux info = {
2742 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002743 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02002744 };
Yonghong Song31fd8582017-06-13 15:52:13 -07002745
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07002746 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07002747 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02002748 /* A non zero info.ctx_field_size indicates that this field is a
2749 * candidate for later verifier transformation to load the whole
2750 * field and then apply a mask when accessed with a narrower
2751 * access than actual ctx access size. A zero info.ctx_field_size
2752 * will only allow for whole field access and rejects any other
2753 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07002754 */
Yonghong Song23994632017-06-22 15:07:39 -07002755 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07002756
Yonghong Songb121b342020-05-09 10:59:12 -07002757 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002758 *btf_id = info.btf_id;
2759 else
2760 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002761 /* remember the offset of last byte accessed in ctx */
2762 if (env->prog->aux->max_ctx_offset < off + size)
2763 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002764 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002765 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002766
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002767 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002768 return -EACCES;
2769}
2770
Petar Penkovd58e4682018-09-14 07:46:18 -07002771static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2772 int size)
2773{
2774 if (size < 0 || off < 0 ||
2775 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2776 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2777 off, size);
2778 return -EACCES;
2779 }
2780 return 0;
2781}
2782
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002783static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2784 u32 regno, int off, int size,
2785 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07002786{
2787 struct bpf_reg_state *regs = cur_regs(env);
2788 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002789 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002790 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07002791
2792 if (reg->smin_value < 0) {
2793 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2794 regno);
2795 return -EACCES;
2796 }
2797
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002798 switch (reg->type) {
2799 case PTR_TO_SOCK_COMMON:
2800 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2801 break;
2802 case PTR_TO_SOCKET:
2803 valid = bpf_sock_is_valid_access(off, size, t, &info);
2804 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002805 case PTR_TO_TCP_SOCK:
2806 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2807 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002808 case PTR_TO_XDP_SOCK:
2809 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2810 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002811 default:
2812 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07002813 }
2814
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002815
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002816 if (valid) {
2817 env->insn_aux_data[insn_idx].ctx_field_size =
2818 info.ctx_field_size;
2819 return 0;
2820 }
2821
2822 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2823 regno, reg_type_str[reg->type], off, size);
2824
2825 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07002826}
2827
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002828static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2829{
2830 return cur_regs(env) + regno;
2831}
2832
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002833static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2834{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002835 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002836}
2837
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002838static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2839{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002840 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002841
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002842 return reg->type == PTR_TO_CTX;
2843}
2844
2845static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2846{
2847 const struct bpf_reg_state *reg = reg_state(env, regno);
2848
2849 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002850}
2851
Daniel Borkmannca369602018-02-23 22:29:05 +01002852static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2853{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002854 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01002855
2856 return type_is_pkt_pointer(reg->type);
2857}
2858
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02002859static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2860{
2861 const struct bpf_reg_state *reg = reg_state(env, regno);
2862
2863 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2864 return reg->type == PTR_TO_FLOW_KEYS;
2865}
2866
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002867static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2868 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07002869 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002870{
Edward Creef1174f72017-08-07 15:26:19 +01002871 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07002872 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07002873
2874 /* Byte size accesses are always allowed. */
2875 if (!strict || size == 1)
2876 return 0;
2877
David S. Millere4eda882017-05-22 12:27:07 -04002878 /* For platforms that do not have a Kconfig enabling
2879 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2880 * NET_IP_ALIGN is universally set to '2'. And on platforms
2881 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2882 * to this code only in strict mode where we want to emulate
2883 * the NET_IP_ALIGN==2 checking. Therefore use an
2884 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07002885 */
David S. Millere4eda882017-05-22 12:27:07 -04002886 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01002887
2888 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2889 if (!tnum_is_aligned(reg_off, size)) {
2890 char tn_buf[48];
2891
2892 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002893 verbose(env,
2894 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002895 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002896 return -EACCES;
2897 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002898
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002899 return 0;
2900}
2901
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002902static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2903 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01002904 const char *pointer_desc,
2905 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002906{
Edward Creef1174f72017-08-07 15:26:19 +01002907 struct tnum reg_off;
2908
2909 /* Byte size accesses are always allowed. */
2910 if (!strict || size == 1)
2911 return 0;
2912
2913 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2914 if (!tnum_is_aligned(reg_off, size)) {
2915 char tn_buf[48];
2916
2917 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002918 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002919 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002920 return -EACCES;
2921 }
2922
2923 return 0;
2924}
2925
David S. Millere07b98d2017-05-10 11:38:07 -07002926static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01002927 const struct bpf_reg_state *reg, int off,
2928 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002929{
Daniel Borkmannca369602018-02-23 22:29:05 +01002930 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01002931 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07002932
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002933 switch (reg->type) {
2934 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002935 case PTR_TO_PACKET_META:
2936 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2937 * right in front, treat it the very same way.
2938 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002939 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07002940 case PTR_TO_FLOW_KEYS:
2941 pointer_desc = "flow keys ";
2942 break;
Edward Creef1174f72017-08-07 15:26:19 +01002943 case PTR_TO_MAP_VALUE:
2944 pointer_desc = "value ";
2945 break;
2946 case PTR_TO_CTX:
2947 pointer_desc = "context ";
2948 break;
2949 case PTR_TO_STACK:
2950 pointer_desc = "stack ";
Jann Horna5ec6ae2017-12-18 20:11:58 -08002951 /* The stack spill tracking logic in check_stack_write()
2952 * and check_stack_read() relies on stack accesses being
2953 * aligned.
2954 */
2955 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01002956 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07002957 case PTR_TO_SOCKET:
2958 pointer_desc = "sock ";
2959 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002960 case PTR_TO_SOCK_COMMON:
2961 pointer_desc = "sock_common ";
2962 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002963 case PTR_TO_TCP_SOCK:
2964 pointer_desc = "tcp_sock ";
2965 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002966 case PTR_TO_XDP_SOCK:
2967 pointer_desc = "xdp_sock ";
2968 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002969 default:
Edward Creef1174f72017-08-07 15:26:19 +01002970 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002971 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002972 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2973 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002974}
2975
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002976static int update_stack_depth(struct bpf_verifier_env *env,
2977 const struct bpf_func_state *func,
2978 int off)
2979{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002980 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002981
2982 if (stack >= -off)
2983 return 0;
2984
2985 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04002986 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002987 return 0;
2988}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002989
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002990/* starting from main bpf function walk all instructions of the function
2991 * and recursively walk all callees that given function can call.
2992 * Ignore jump and exit insns.
2993 * Since recursion is prevented by check_cfg() this algorithm
2994 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2995 */
2996static int check_max_stack_depth(struct bpf_verifier_env *env)
2997{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002998 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2999 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003000 struct bpf_insn *insn = env->prog->insnsi;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003001 bool tail_call_reachable = false;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003002 int ret_insn[MAX_CALL_FRAMES];
3003 int ret_prog[MAX_CALL_FRAMES];
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003004 int j;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003005
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003006process_func:
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02003007 /* protect against potential stack overflow that might happen when
3008 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3009 * depth for such case down to 256 so that the worst case scenario
3010 * would result in 8k stack size (32 which is tailcall limit * 256 =
3011 * 8k).
3012 *
3013 * To get the idea what might happen, see an example:
3014 * func1 -> sub rsp, 128
3015 * subfunc1 -> sub rsp, 256
3016 * tailcall1 -> add rsp, 256
3017 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3018 * subfunc2 -> sub rsp, 64
3019 * subfunc22 -> sub rsp, 128
3020 * tailcall2 -> add rsp, 128
3021 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3022 *
3023 * tailcall will unwind the current stack frame but it will not get rid
3024 * of caller's stack as shown on the example above.
3025 */
3026 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3027 verbose(env,
3028 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3029 depth);
3030 return -EACCES;
3031 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003032 /* round up to 32-bytes, since this is granularity
3033 * of interpreter stack size
3034 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003035 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003036 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003037 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003038 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003039 return -EACCES;
3040 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003041continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04003042 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003043 for (; i < subprog_end; i++) {
3044 if (insn[i].code != (BPF_JMP | BPF_CALL))
3045 continue;
3046 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3047 continue;
3048 /* remember insn and function to return to */
3049 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003050 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003051
3052 /* find the callee */
3053 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003054 idx = find_subprog(env, i);
3055 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003056 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3057 i);
3058 return -EFAULT;
3059 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003060
3061 if (subprog[idx].has_tail_call)
3062 tail_call_reachable = true;
3063
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003064 frame++;
3065 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003066 verbose(env, "the call stack of %d frames is too deep !\n",
3067 frame);
3068 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003069 }
3070 goto process_func;
3071 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003072 /* if tail call got detected across bpf2bpf calls then mark each of the
3073 * currently present subprog frames as tail call reachable subprogs;
3074 * this info will be utilized by JIT so that we will be preserving the
3075 * tail call counter throughout bpf2bpf calls combined with tailcalls
3076 */
3077 if (tail_call_reachable)
3078 for (j = 0; j < frame; j++)
3079 subprog[ret_prog[j]].tail_call_reachable = true;
3080
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003081 /* end of for() loop means the last insn of the 'subprog'
3082 * was reached. Doesn't matter whether it was JA or EXIT
3083 */
3084 if (frame == 0)
3085 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003086 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003087 frame--;
3088 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003089 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003090 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003091}
3092
David S. Miller19d28fb2018-01-11 21:27:54 -05003093#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003094static int get_callee_stack_depth(struct bpf_verifier_env *env,
3095 const struct bpf_insn *insn, int idx)
3096{
3097 int start = idx + insn->imm + 1, subprog;
3098
3099 subprog = find_subprog(env, start);
3100 if (subprog < 0) {
3101 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3102 start);
3103 return -EFAULT;
3104 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04003105 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003106}
David S. Miller19d28fb2018-01-11 21:27:54 -05003107#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003108
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003109int check_ctx_reg(struct bpf_verifier_env *env,
3110 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02003111{
3112 /* Access to ctx or passing it to a helper is only allowed in
3113 * its original, unmodified form.
3114 */
3115
3116 if (reg->off) {
3117 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3118 regno, reg->off);
3119 return -EACCES;
3120 }
3121
3122 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3123 char tn_buf[48];
3124
3125 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3126 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3127 return -EACCES;
3128 }
3129
3130 return 0;
3131}
3132
Yonghong Songafbf21d2020-07-23 11:41:11 -07003133static int __check_buffer_access(struct bpf_verifier_env *env,
3134 const char *buf_info,
3135 const struct bpf_reg_state *reg,
3136 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07003137{
3138 if (off < 0) {
3139 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003140 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003141 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07003142 return -EACCES;
3143 }
3144 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3145 char tn_buf[48];
3146
3147 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3148 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003149 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07003150 regno, off, tn_buf);
3151 return -EACCES;
3152 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07003153
3154 return 0;
3155}
3156
3157static int check_tp_buffer_access(struct bpf_verifier_env *env,
3158 const struct bpf_reg_state *reg,
3159 int regno, int off, int size)
3160{
3161 int err;
3162
3163 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3164 if (err)
3165 return err;
3166
Matt Mullins9df1c282019-04-26 11:49:47 -07003167 if (off + size > env->prog->aux->max_tp_access)
3168 env->prog->aux->max_tp_access = off + size;
3169
3170 return 0;
3171}
3172
Yonghong Songafbf21d2020-07-23 11:41:11 -07003173static int check_buffer_access(struct bpf_verifier_env *env,
3174 const struct bpf_reg_state *reg,
3175 int regno, int off, int size,
3176 bool zero_size_allowed,
3177 const char *buf_info,
3178 u32 *max_access)
3179{
3180 int err;
3181
3182 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3183 if (err)
3184 return err;
3185
3186 if (off + size > *max_access)
3187 *max_access = off + size;
3188
3189 return 0;
3190}
3191
John Fastabend3f50f132020-03-30 14:36:39 -07003192/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3193static void zext_32_to_64(struct bpf_reg_state *reg)
3194{
3195 reg->var_off = tnum_subreg(reg->var_off);
3196 __reg_assign_32_into_64(reg);
3197}
Matt Mullins9df1c282019-04-26 11:49:47 -07003198
Jann Horn0c17d1d2017-12-18 20:11:55 -08003199/* truncate register to smaller size (in bytes)
3200 * must be called with size < BPF_REG_SIZE
3201 */
3202static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3203{
3204 u64 mask;
3205
3206 /* clear high bits in bit representation */
3207 reg->var_off = tnum_cast(reg->var_off, size);
3208
3209 /* fix arithmetic bounds */
3210 mask = ((u64)1 << (size * 8)) - 1;
3211 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3212 reg->umin_value &= mask;
3213 reg->umax_value &= mask;
3214 } else {
3215 reg->umin_value = 0;
3216 reg->umax_value = mask;
3217 }
3218 reg->smin_value = reg->umin_value;
3219 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07003220
3221 /* If size is smaller than 32bit register the 32bit register
3222 * values are also truncated so we push 64-bit bounds into
3223 * 32-bit bounds. Above were truncated < 32-bits already.
3224 */
3225 if (size >= 4)
3226 return;
3227 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08003228}
3229
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003230static bool bpf_map_is_rdonly(const struct bpf_map *map)
3231{
3232 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3233}
3234
3235static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3236{
3237 void *ptr;
3238 u64 addr;
3239 int err;
3240
3241 err = map->ops->map_direct_value_addr(map, &addr, off);
3242 if (err)
3243 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07003244 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003245
3246 switch (size) {
3247 case sizeof(u8):
3248 *val = (u64)*(u8 *)ptr;
3249 break;
3250 case sizeof(u16):
3251 *val = (u64)*(u16 *)ptr;
3252 break;
3253 case sizeof(u32):
3254 *val = (u64)*(u32 *)ptr;
3255 break;
3256 case sizeof(u64):
3257 *val = *(u64 *)ptr;
3258 break;
3259 default:
3260 return -EINVAL;
3261 }
3262 return 0;
3263}
3264
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003265static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3266 struct bpf_reg_state *regs,
3267 int regno, int off, int size,
3268 enum bpf_access_type atype,
3269 int value_regno)
3270{
3271 struct bpf_reg_state *reg = regs + regno;
3272 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3273 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3274 u32 btf_id;
3275 int ret;
3276
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003277 if (off < 0) {
3278 verbose(env,
3279 "R%d is ptr_%s invalid negative access: off=%d\n",
3280 regno, tname, off);
3281 return -EACCES;
3282 }
3283 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3284 char tn_buf[48];
3285
3286 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3287 verbose(env,
3288 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3289 regno, tname, off, tn_buf);
3290 return -EACCES;
3291 }
3292
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003293 if (env->ops->btf_struct_access) {
3294 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3295 atype, &btf_id);
3296 } else {
3297 if (atype != BPF_READ) {
3298 verbose(env, "only read is supported\n");
3299 return -EACCES;
3300 }
3301
3302 ret = btf_struct_access(&env->log, t, off, size, atype,
3303 &btf_id);
3304 }
3305
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003306 if (ret < 0)
3307 return ret;
3308
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003309 if (atype == BPF_READ && value_regno >= 0)
3310 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003311
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003312 return 0;
3313}
3314
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003315static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3316 struct bpf_reg_state *regs,
3317 int regno, int off, int size,
3318 enum bpf_access_type atype,
3319 int value_regno)
3320{
3321 struct bpf_reg_state *reg = regs + regno;
3322 struct bpf_map *map = reg->map_ptr;
3323 const struct btf_type *t;
3324 const char *tname;
3325 u32 btf_id;
3326 int ret;
3327
3328 if (!btf_vmlinux) {
3329 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3330 return -ENOTSUPP;
3331 }
3332
3333 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3334 verbose(env, "map_ptr access not supported for map type %d\n",
3335 map->map_type);
3336 return -ENOTSUPP;
3337 }
3338
3339 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3340 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3341
3342 if (!env->allow_ptr_to_map_access) {
3343 verbose(env,
3344 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3345 tname);
3346 return -EPERM;
3347 }
3348
3349 if (off < 0) {
3350 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3351 regno, tname, off);
3352 return -EACCES;
3353 }
3354
3355 if (atype != BPF_READ) {
3356 verbose(env, "only read from %s is supported\n", tname);
3357 return -EACCES;
3358 }
3359
3360 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3361 if (ret < 0)
3362 return ret;
3363
3364 if (value_regno >= 0)
3365 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3366
3367 return 0;
3368}
3369
3370
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003371/* check whether memory at (regno + off) is accessible for t = (read | write)
3372 * if t==write, value_regno is a register which value is stored into memory
3373 * if t==read, value_regno is a register which will receive the value from memory
3374 * if t==write && value_regno==-1, some unknown value is stored into memory
3375 * if t==read && value_regno==-1, don't care what we read from memory
3376 */
Daniel Borkmannca369602018-02-23 22:29:05 +01003377static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3378 int off, int bpf_size, enum bpf_access_type t,
3379 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003380{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003381 struct bpf_reg_state *regs = cur_regs(env);
3382 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003383 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003384 int size, err = 0;
3385
3386 size = bpf_size_to_bytes(bpf_size);
3387 if (size < 0)
3388 return size;
3389
Edward Creef1174f72017-08-07 15:26:19 +01003390 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01003391 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003392 if (err)
3393 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003394
Edward Creef1174f72017-08-07 15:26:19 +01003395 /* for access checks, reg->off is just part of off */
3396 off += reg->off;
3397
3398 if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003399 if (t == BPF_WRITE && value_regno >= 0 &&
3400 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003401 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003402 return -EACCES;
3403 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02003404 err = check_map_access_type(env, regno, off, size, t);
3405 if (err)
3406 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003407 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003408 if (!err && t == BPF_READ && value_regno >= 0) {
3409 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003410
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003411 /* if map is read-only, track its contents as scalars */
3412 if (tnum_is_const(reg->var_off) &&
3413 bpf_map_is_rdonly(map) &&
3414 map->ops->map_direct_value_addr) {
3415 int map_off = off + reg->var_off.value;
3416 u64 val = 0;
3417
3418 err = bpf_map_direct_read(map, map_off, size,
3419 &val);
3420 if (err)
3421 return err;
3422
3423 regs[value_regno].type = SCALAR_VALUE;
3424 __mark_reg_known(&regs[value_regno], val);
3425 } else {
3426 mark_reg_unknown(env, regs, value_regno);
3427 }
3428 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003429 } else if (reg->type == PTR_TO_MEM) {
3430 if (t == BPF_WRITE && value_regno >= 0 &&
3431 is_pointer_value(env, value_regno)) {
3432 verbose(env, "R%d leaks addr into mem\n", value_regno);
3433 return -EACCES;
3434 }
3435 err = check_mem_region_access(env, regno, off, size,
3436 reg->mem_size, false);
3437 if (!err && t == BPF_READ && value_regno >= 0)
3438 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07003439 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01003440 enum bpf_reg_type reg_type = SCALAR_VALUE;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003441 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07003442
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003443 if (t == BPF_WRITE && value_regno >= 0 &&
3444 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003445 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003446 return -EACCES;
3447 }
Edward Creef1174f72017-08-07 15:26:19 +01003448
Daniel Borkmann58990d12018-06-07 17:40:03 +02003449 err = check_ctx_reg(env, reg, regno);
3450 if (err < 0)
3451 return err;
3452
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003453 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3454 if (err)
3455 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003456 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01003457 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003458 * PTR_TO_PACKET[_META,_END]. In the latter
3459 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01003460 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003461 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003462 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003463 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003464 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003465 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003466 if (reg_type_may_be_null(reg_type))
3467 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01003468 /* A load of ctx field could have different
3469 * actual load size with the one encoded in the
3470 * insn. When the dst is PTR, it is for sure not
3471 * a sub-register.
3472 */
3473 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07003474 if (reg_type == PTR_TO_BTF_ID ||
3475 reg_type == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003476 regs[value_regno].btf_id = btf_id;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003477 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003478 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003479 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003480
Edward Creef1174f72017-08-07 15:26:19 +01003481 } else if (reg->type == PTR_TO_STACK) {
Edward Creef1174f72017-08-07 15:26:19 +01003482 off += reg->var_off.value;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003483 err = check_stack_access(env, reg, off, size);
3484 if (err)
3485 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003486
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003487 state = func(env, reg);
3488 err = update_stack_depth(env, state, off);
3489 if (err)
3490 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003491
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003492 if (t == BPF_WRITE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003493 err = check_stack_write(env, state, off, size,
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07003494 value_regno, insn_idx);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003495 else
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003496 err = check_stack_read(env, state, off, size,
3497 value_regno);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003498 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003499 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003500 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003501 return -EACCES;
3502 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003503 if (t == BPF_WRITE && value_regno >= 0 &&
3504 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003505 verbose(env, "R%d leaks addr into packet\n",
3506 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003507 return -EACCES;
3508 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08003509 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003510 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003511 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07003512 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3513 if (t == BPF_WRITE && value_regno >= 0 &&
3514 is_pointer_value(env, value_regno)) {
3515 verbose(env, "R%d leaks addr into flow keys\n",
3516 value_regno);
3517 return -EACCES;
3518 }
3519
3520 err = check_flow_keys_access(env, off, size);
3521 if (!err && t == BPF_READ && value_regno >= 0)
3522 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003523 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07003524 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003525 verbose(env, "R%d cannot write into %s\n",
3526 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07003527 return -EACCES;
3528 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003529 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07003530 if (!err && value_regno >= 0)
3531 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07003532 } else if (reg->type == PTR_TO_TP_BUFFER) {
3533 err = check_tp_buffer_access(env, reg, regno, off, size);
3534 if (!err && t == BPF_READ && value_regno >= 0)
3535 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003536 } else if (reg->type == PTR_TO_BTF_ID) {
3537 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3538 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003539 } else if (reg->type == CONST_PTR_TO_MAP) {
3540 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3541 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07003542 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3543 if (t == BPF_WRITE) {
3544 verbose(env, "R%d cannot write into %s\n",
3545 regno, reg_type_str[reg->type]);
3546 return -EACCES;
3547 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003548 err = check_buffer_access(env, reg, regno, off, size, false,
3549 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003550 &env->prog->aux->max_rdonly_access);
3551 if (!err && value_regno >= 0)
3552 mark_reg_unknown(env, regs, value_regno);
3553 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003554 err = check_buffer_access(env, reg, regno, off, size, false,
3555 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003556 &env->prog->aux->max_rdwr_access);
3557 if (!err && t == BPF_READ && value_regno >= 0)
3558 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003559 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003560 verbose(env, "R%d invalid mem access '%s'\n", regno,
3561 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003562 return -EACCES;
3563 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003564
Edward Creef1174f72017-08-07 15:26:19 +01003565 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003566 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01003567 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08003568 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003569 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003570 return err;
3571}
3572
Yonghong Song31fd8582017-06-13 15:52:13 -07003573static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003574{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003575 int err;
3576
3577 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3578 insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003579 verbose(env, "BPF_XADD uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003580 return -EINVAL;
3581 }
3582
3583 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003584 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003585 if (err)
3586 return err;
3587
3588 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003589 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003590 if (err)
3591 return err;
3592
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003593 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003594 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003595 return -EACCES;
3596 }
3597
Daniel Borkmannca369602018-02-23 22:29:05 +01003598 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003599 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003600 is_flow_key_reg(env, insn->dst_reg) ||
3601 is_sk_reg(env, insn->dst_reg)) {
Daniel Borkmannca369602018-02-23 22:29:05 +01003602 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003603 insn->dst_reg,
3604 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003605 return -EACCES;
3606 }
3607
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003608 /* check whether atomic_add can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003609 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003610 BPF_SIZE(insn->code), BPF_READ, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003611 if (err)
3612 return err;
3613
3614 /* check whether atomic_add can write into the same memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003615 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003616 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003617}
3618
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003619static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3620 int off, int access_size,
3621 bool zero_size_allowed)
3622{
3623 struct bpf_reg_state *reg = reg_state(env, regno);
3624
3625 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3626 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3627 if (tnum_is_const(reg->var_off)) {
3628 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3629 regno, off, access_size);
3630 } else {
3631 char tn_buf[48];
3632
3633 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3634 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3635 regno, tn_buf, access_size);
3636 }
3637 return -EACCES;
3638 }
3639 return 0;
3640}
3641
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003642/* when register 'regno' is passed into function that will read 'access_size'
3643 * bytes from that pointer, make sure that it's within stack boundary
Edward Creef1174f72017-08-07 15:26:19 +01003644 * and all elements of stack are initialized.
3645 * Unlike most pointer bounds-checking functions, this one doesn't take an
3646 * 'off' argument, so it has to add in reg->off itself.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003647 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003648static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
Daniel Borkmann435faee12016-04-13 00:10:51 +02003649 int access_size, bool zero_size_allowed,
3650 struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003651{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003652 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003653 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003654 int err, min_off, max_off, i, j, slot, spi;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003655
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003656 if (tnum_is_const(reg->var_off)) {
3657 min_off = max_off = reg->var_off.value + reg->off;
3658 err = __check_stack_boundary(env, regno, min_off, access_size,
3659 zero_size_allowed);
3660 if (err)
3661 return err;
3662 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07003663 /* Variable offset is prohibited for unprivileged mode for
3664 * simplicity since it requires corresponding support in
3665 * Spectre masking for stack ALU.
3666 * See also retrieve_ptr_limit().
3667 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07003668 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07003669 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01003670
Andrey Ignatov088ec262019-04-03 23:22:39 -07003671 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3672 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3673 regno, tn_buf);
3674 return -EACCES;
3675 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07003676 /* Only initialized buffer on stack is allowed to be accessed
3677 * with variable offset. With uninitialized buffer it's hard to
3678 * guarantee that whole memory is marked as initialized on
3679 * helper return since specific bounds are unknown what may
3680 * cause uninitialized stack leaking.
3681 */
3682 if (meta && meta->raw_mode)
3683 meta = NULL;
3684
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003685 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3686 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3687 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3688 regno);
3689 return -EACCES;
3690 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003691 min_off = reg->smin_value + reg->off;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003692 max_off = reg->smax_value + reg->off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003693 err = __check_stack_boundary(env, regno, min_off, access_size,
3694 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003695 if (err) {
3696 verbose(env, "R%d min value is outside of stack bound\n",
3697 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003698 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003699 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003700 err = __check_stack_boundary(env, regno, max_off, access_size,
3701 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003702 if (err) {
3703 verbose(env, "R%d max value is outside of stack bound\n",
3704 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003705 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003706 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003707 }
3708
Daniel Borkmann435faee12016-04-13 00:10:51 +02003709 if (meta && meta->raw_mode) {
3710 meta->access_size = access_size;
3711 meta->regno = regno;
3712 return 0;
3713 }
3714
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003715 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003716 u8 *stype;
3717
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003718 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003719 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003720 if (state->allocated_stack <= slot)
3721 goto err;
3722 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3723 if (*stype == STACK_MISC)
3724 goto mark;
3725 if (*stype == STACK_ZERO) {
3726 /* helper can write anything into the stack */
3727 *stype = STACK_MISC;
3728 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003729 }
Yonghong Song1d68f222020-05-09 10:59:15 -07003730
3731 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3732 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3733 goto mark;
3734
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003735 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3736 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003737 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003738 for (j = 0; j < BPF_REG_SIZE; j++)
3739 state->stack[spi].slot_type[j] = STACK_MISC;
3740 goto mark;
3741 }
3742
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003743err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003744 if (tnum_is_const(reg->var_off)) {
3745 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3746 min_off, i - min_off, access_size);
3747 } else {
3748 char tn_buf[48];
3749
3750 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3751 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3752 tn_buf, i - min_off, access_size);
3753 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003754 return -EACCES;
3755mark:
3756 /* reading any byte out of 8-byte 'spill_slot' will cause
3757 * the whole slot to be marked as 'read'
3758 */
Edward Cree679c7822018-08-22 20:02:19 +01003759 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01003760 state->stack[spi].spilled_ptr.parent,
3761 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003762 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003763 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003764}
3765
Gianluca Borello06c1c042017-01-09 10:19:49 -08003766static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3767 int access_size, bool zero_size_allowed,
3768 struct bpf_call_arg_meta *meta)
3769{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003770 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08003771
Edward Creef1174f72017-08-07 15:26:19 +01003772 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08003773 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003774 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08003775 return check_packet_access(env, regno, reg->off, access_size,
3776 zero_size_allowed);
Gianluca Borello06c1c042017-01-09 10:19:49 -08003777 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02003778 if (check_map_access_type(env, regno, reg->off, access_size,
3779 meta && meta->raw_mode ? BPF_WRITE :
3780 BPF_READ))
3781 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003782 return check_map_access(env, regno, reg->off, access_size,
3783 zero_size_allowed);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003784 case PTR_TO_MEM:
3785 return check_mem_region_access(env, regno, reg->off,
3786 access_size, reg->mem_size,
3787 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07003788 case PTR_TO_RDONLY_BUF:
3789 if (meta && meta->raw_mode)
3790 return -EACCES;
3791 return check_buffer_access(env, reg, regno, reg->off,
3792 access_size, zero_size_allowed,
3793 "rdonly",
3794 &env->prog->aux->max_rdonly_access);
3795 case PTR_TO_RDWR_BUF:
3796 return check_buffer_access(env, reg, regno, reg->off,
3797 access_size, zero_size_allowed,
3798 "rdwr",
3799 &env->prog->aux->max_rdwr_access);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01003800 case PTR_TO_STACK:
Gianluca Borello06c1c042017-01-09 10:19:49 -08003801 return check_stack_boundary(env, regno, access_size,
3802 zero_size_allowed, meta);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01003803 default: /* scalar_value or invalid ptr */
3804 /* Allow zero-byte read from NULL, regardless of pointer type */
3805 if (zero_size_allowed && access_size == 0 &&
3806 register_is_null(reg))
3807 return 0;
3808
3809 verbose(env, "R%d type=%s expected=%s\n", regno,
3810 reg_type_str[reg->type],
3811 reg_type_str[PTR_TO_STACK]);
3812 return -EACCES;
Gianluca Borello06c1c042017-01-09 10:19:49 -08003813 }
3814}
3815
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003816/* Implementation details:
3817 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3818 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3819 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3820 * value_or_null->value transition, since the verifier only cares about
3821 * the range of access to valid map value pointer and doesn't care about actual
3822 * address of the map element.
3823 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3824 * reg->id > 0 after value_or_null->value transition. By doing so
3825 * two bpf_map_lookups will be considered two different pointers that
3826 * point to different bpf_spin_locks.
3827 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3828 * dead-locks.
3829 * Since only one bpf_spin_lock is allowed the checks are simpler than
3830 * reg_is_refcounted() logic. The verifier needs to remember only
3831 * one spin_lock instead of array of acquired_refs.
3832 * cur_state->active_spin_lock remembers which map value element got locked
3833 * and clears it after bpf_spin_unlock.
3834 */
3835static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3836 bool is_lock)
3837{
3838 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3839 struct bpf_verifier_state *cur = env->cur_state;
3840 bool is_const = tnum_is_const(reg->var_off);
3841 struct bpf_map *map = reg->map_ptr;
3842 u64 val = reg->var_off.value;
3843
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003844 if (!is_const) {
3845 verbose(env,
3846 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3847 regno);
3848 return -EINVAL;
3849 }
3850 if (!map->btf) {
3851 verbose(env,
3852 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3853 map->name);
3854 return -EINVAL;
3855 }
3856 if (!map_value_has_spin_lock(map)) {
3857 if (map->spin_lock_off == -E2BIG)
3858 verbose(env,
3859 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3860 map->name);
3861 else if (map->spin_lock_off == -ENOENT)
3862 verbose(env,
3863 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3864 map->name);
3865 else
3866 verbose(env,
3867 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3868 map->name);
3869 return -EINVAL;
3870 }
3871 if (map->spin_lock_off != val + reg->off) {
3872 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3873 val + reg->off);
3874 return -EINVAL;
3875 }
3876 if (is_lock) {
3877 if (cur->active_spin_lock) {
3878 verbose(env,
3879 "Locking two bpf_spin_locks are not allowed\n");
3880 return -EINVAL;
3881 }
3882 cur->active_spin_lock = reg->id;
3883 } else {
3884 if (!cur->active_spin_lock) {
3885 verbose(env, "bpf_spin_unlock without taking a lock\n");
3886 return -EINVAL;
3887 }
3888 if (cur->active_spin_lock != reg->id) {
3889 verbose(env, "bpf_spin_unlock of different lock\n");
3890 return -EINVAL;
3891 }
3892 cur->active_spin_lock = 0;
3893 }
3894 return 0;
3895}
3896
Daniel Borkmann90133412018-01-20 01:24:29 +01003897static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3898{
3899 return type == ARG_PTR_TO_MEM ||
3900 type == ARG_PTR_TO_MEM_OR_NULL ||
3901 type == ARG_PTR_TO_UNINIT_MEM;
3902}
3903
3904static bool arg_type_is_mem_size(enum bpf_arg_type type)
3905{
3906 return type == ARG_CONST_SIZE ||
3907 type == ARG_CONST_SIZE_OR_ZERO;
3908}
3909
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003910static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3911{
3912 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3913}
3914
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003915static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3916{
3917 return type == ARG_PTR_TO_INT ||
3918 type == ARG_PTR_TO_LONG;
3919}
3920
3921static int int_ptr_type_to_size(enum bpf_arg_type type)
3922{
3923 if (type == ARG_PTR_TO_INT)
3924 return sizeof(u32);
3925 else if (type == ARG_PTR_TO_LONG)
3926 return sizeof(u64);
3927
3928 return -EINVAL;
3929}
3930
Lorenz Bauer912f4422020-08-21 11:29:46 +01003931static int resolve_map_arg_type(struct bpf_verifier_env *env,
3932 const struct bpf_call_arg_meta *meta,
3933 enum bpf_arg_type *arg_type)
3934{
3935 if (!meta->map_ptr) {
3936 /* kernel subsystem misconfigured verifier */
3937 verbose(env, "invalid map_ptr to access map->type\n");
3938 return -EACCES;
3939 }
3940
3941 switch (meta->map_ptr->map_type) {
3942 case BPF_MAP_TYPE_SOCKMAP:
3943 case BPF_MAP_TYPE_SOCKHASH:
3944 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
Lorenz Bauer6550f2d2020-09-28 10:08:02 +01003945 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
Lorenz Bauer912f4422020-08-21 11:29:46 +01003946 } else {
3947 verbose(env, "invalid arg_type for sockmap/sockhash\n");
3948 return -EINVAL;
3949 }
3950 break;
3951
3952 default:
3953 break;
3954 }
3955 return 0;
3956}
3957
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01003958struct bpf_reg_types {
3959 const enum bpf_reg_type types[10];
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07003960 u32 *btf_id;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01003961};
3962
3963static const struct bpf_reg_types map_key_value_types = {
3964 .types = {
3965 PTR_TO_STACK,
3966 PTR_TO_PACKET,
3967 PTR_TO_PACKET_META,
3968 PTR_TO_MAP_VALUE,
3969 },
3970};
3971
3972static const struct bpf_reg_types sock_types = {
3973 .types = {
3974 PTR_TO_SOCK_COMMON,
3975 PTR_TO_SOCKET,
3976 PTR_TO_TCP_SOCK,
3977 PTR_TO_XDP_SOCK,
3978 },
3979};
3980
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07003981static const struct bpf_reg_types btf_id_sock_common_types = {
3982 .types = {
3983 PTR_TO_SOCK_COMMON,
3984 PTR_TO_SOCKET,
3985 PTR_TO_TCP_SOCK,
3986 PTR_TO_XDP_SOCK,
3987 PTR_TO_BTF_ID,
3988 },
3989 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
3990};
3991
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01003992static const struct bpf_reg_types mem_types = {
3993 .types = {
3994 PTR_TO_STACK,
3995 PTR_TO_PACKET,
3996 PTR_TO_PACKET_META,
3997 PTR_TO_MAP_VALUE,
3998 PTR_TO_MEM,
3999 PTR_TO_RDONLY_BUF,
4000 PTR_TO_RDWR_BUF,
4001 },
4002};
4003
4004static const struct bpf_reg_types int_ptr_types = {
4005 .types = {
4006 PTR_TO_STACK,
4007 PTR_TO_PACKET,
4008 PTR_TO_PACKET_META,
4009 PTR_TO_MAP_VALUE,
4010 },
4011};
4012
4013static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4014static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4015static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4016static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4017static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4018static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4019static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4020
Lorenz Bauer0789e13b2020-09-23 17:01:55 +01004021static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004022 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4023 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4024 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4025 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4026 [ARG_CONST_SIZE] = &scalar_types,
4027 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4028 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4029 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4030 [ARG_PTR_TO_CTX] = &context_types,
4031 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4032 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004033 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004034 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4035 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4036 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4037 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4038 [ARG_PTR_TO_MEM] = &mem_types,
4039 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4040 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4041 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4042 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4043 [ARG_PTR_TO_INT] = &int_ptr_types,
4044 [ARG_PTR_TO_LONG] = &int_ptr_types,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004045};
4046
4047static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004048 enum bpf_arg_type arg_type,
4049 const u32 *arg_btf_id)
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004050{
4051 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4052 enum bpf_reg_type expected, type = reg->type;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004053 const struct bpf_reg_types *compatible;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004054 int i, j;
4055
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004056 compatible = compatible_reg_types[arg_type];
4057 if (!compatible) {
4058 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4059 return -EFAULT;
4060 }
4061
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004062 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4063 expected = compatible->types[i];
4064 if (expected == NOT_INIT)
4065 break;
4066
4067 if (type == expected)
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004068 goto found;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004069 }
4070
4071 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4072 for (j = 0; j + 1 < i; j++)
4073 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4074 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4075 return -EACCES;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004076
4077found:
4078 if (type == PTR_TO_BTF_ID) {
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004079 if (!arg_btf_id) {
4080 if (!compatible->btf_id) {
4081 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4082 return -EFAULT;
4083 }
4084 arg_btf_id = compatible->btf_id;
4085 }
4086
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004087 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4088 *arg_btf_id)) {
4089 verbose(env, "R%d is of type %s but %s is expected\n",
4090 regno, kernel_type_name(reg->btf_id),
4091 kernel_type_name(*arg_btf_id));
4092 return -EACCES;
4093 }
4094
4095 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4096 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4097 regno);
4098 return -EACCES;
4099 }
4100 }
4101
4102 return 0;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004103}
4104
Yonghong Songaf7ec132020-06-23 16:08:09 -07004105static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4106 struct bpf_call_arg_meta *meta,
4107 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004108{
Yonghong Songaf7ec132020-06-23 16:08:09 -07004109 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004110 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Yonghong Songaf7ec132020-06-23 16:08:09 -07004111 enum bpf_arg_type arg_type = fn->arg_type[arg];
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004112 enum bpf_reg_type type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004113 int err = 0;
4114
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004115 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004116 return 0;
4117
Edward Creedc503a82017-08-15 20:34:35 +01004118 err = check_reg_arg(env, regno, SRC_OP);
4119 if (err)
4120 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004121
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004122 if (arg_type == ARG_ANYTHING) {
4123 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004124 verbose(env, "R%d leaks addr into helper function\n",
4125 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004126 return -EACCES;
4127 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004128 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004129 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004130
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004131 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004132 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004133 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004134 return -EACCES;
4135 }
4136
Lorenz Bauer912f4422020-08-21 11:29:46 +01004137 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4138 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4139 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4140 err = resolve_map_arg_type(env, meta, &arg_type);
4141 if (err)
4142 return err;
4143 }
4144
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004145 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4146 /* A NULL register has a SCALAR_VALUE type, so skip
4147 * type checking.
4148 */
4149 goto skip_type_check;
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004150
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004151 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004152 if (err)
4153 return err;
4154
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004155 if (type == PTR_TO_CTX) {
Lorenz Bauerfeec7042020-09-21 13:12:23 +01004156 err = check_ctx_reg(env, reg, regno);
4157 if (err < 0)
4158 return err;
Lorenz Bauerd7b94542020-09-21 13:12:21 +01004159 }
4160
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004161skip_type_check:
Lorenz Bauer02f7c952020-09-21 13:12:22 +01004162 if (reg->ref_obj_id) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004163 if (meta->ref_obj_id) {
4164 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4165 regno, reg->ref_obj_id,
4166 meta->ref_obj_id);
4167 return -EFAULT;
4168 }
4169 meta->ref_obj_id = reg->ref_obj_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004170 }
4171
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004172 if (arg_type == ARG_CONST_MAP_PTR) {
4173 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004174 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004175 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4176 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4177 * check that [key, key + map->key_size) are within
4178 * stack limits and initialized
4179 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004180 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004181 /* in function declaration map_ptr must come before
4182 * map_key, so that it's verified and known before
4183 * we have to check map_key here. Otherwise it means
4184 * that kernel subsystem misconfigured verifier
4185 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004186 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004187 return -EACCES;
4188 }
Paul Chaignond71962f2018-04-24 15:07:54 +02004189 err = check_helper_mem_access(env, regno,
4190 meta->map_ptr->key_size, false,
4191 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004192 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004193 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4194 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004195 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004196 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4197 * check [value, value + map->value_size) validity
4198 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004199 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004200 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004201 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004202 return -EACCES;
4203 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004204 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02004205 err = check_helper_mem_access(env, regno,
4206 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004207 meta);
Lorenz Bauerc18f0b62020-09-21 13:12:25 +01004208 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4209 if (meta->func_id == BPF_FUNC_spin_lock) {
4210 if (process_spin_lock(env, regno, true))
4211 return -EACCES;
4212 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4213 if (process_spin_lock(env, regno, false))
4214 return -EACCES;
4215 } else {
4216 verbose(env, "verifier internal error\n");
4217 return -EFAULT;
4218 }
Lorenz Bauera2bbe7c2020-09-21 13:12:24 +01004219 } else if (arg_type_is_mem_ptr(arg_type)) {
4220 /* The access to this pointer is only checked when we hit the
4221 * next is_mem_size argument below.
4222 */
4223 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
Daniel Borkmann90133412018-01-20 01:24:29 +01004224 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004225 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004226
John Fastabend10060502020-03-30 14:36:19 -07004227 /* This is used to refine r0 return value bounds for helpers
4228 * that enforce this value as an upper bound on return values.
4229 * See do_refine_retval_range() for helpers that can refine
4230 * the return value. C type of helper is u32 so we pull register
4231 * bound from umax_value however, if negative verifier errors
4232 * out. Only upper bounds can be learned because retval is an
4233 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07004234 */
John Fastabend10060502020-03-30 14:36:19 -07004235 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004236
Edward Creef1174f72017-08-07 15:26:19 +01004237 /* The register is SCALAR_VALUE; the access check
4238 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08004239 */
Edward Creef1174f72017-08-07 15:26:19 +01004240 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08004241 /* For unprivileged variable accesses, disable raw
4242 * mode so that the program is required to
4243 * initialize all the memory that the helper could
4244 * just partially fill up.
4245 */
4246 meta = NULL;
4247
Edward Creeb03c9f92017-08-07 15:26:36 +01004248 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004249 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004250 regno);
4251 return -EACCES;
4252 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08004253
Edward Creeb03c9f92017-08-07 15:26:36 +01004254 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004255 err = check_helper_mem_access(env, regno - 1, 0,
4256 zero_size_allowed,
4257 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004258 if (err)
4259 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004260 }
Edward Creef1174f72017-08-07 15:26:19 +01004261
Edward Creeb03c9f92017-08-07 15:26:36 +01004262 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004263 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004264 regno);
4265 return -EACCES;
4266 }
4267 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01004268 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01004269 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07004270 if (!err)
4271 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004272 } else if (arg_type_is_alloc_size(arg_type)) {
4273 if (!tnum_is_const(reg->var_off)) {
4274 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4275 regno);
4276 return -EACCES;
4277 }
4278 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004279 } else if (arg_type_is_int_ptr(arg_type)) {
4280 int size = int_ptr_type_to_size(arg_type);
4281
4282 err = check_helper_mem_access(env, regno, size, false, meta);
4283 if (err)
4284 return err;
4285 err = check_ptr_alignment(env, reg, 0, size, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004286 }
4287
4288 return err;
4289}
4290
Lorenz Bauer01262402020-08-21 11:29:47 +01004291static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4292{
4293 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07004294 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01004295
4296 if (func_id != BPF_FUNC_map_update_elem)
4297 return false;
4298
4299 /* It's not possible to get access to a locked struct sock in these
4300 * contexts, so updating is safe.
4301 */
4302 switch (type) {
4303 case BPF_PROG_TYPE_TRACING:
4304 if (eatype == BPF_TRACE_ITER)
4305 return true;
4306 break;
4307 case BPF_PROG_TYPE_SOCKET_FILTER:
4308 case BPF_PROG_TYPE_SCHED_CLS:
4309 case BPF_PROG_TYPE_SCHED_ACT:
4310 case BPF_PROG_TYPE_XDP:
4311 case BPF_PROG_TYPE_SK_REUSEPORT:
4312 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4313 case BPF_PROG_TYPE_SK_LOOKUP:
4314 return true;
4315 default:
4316 break;
4317 }
4318
4319 verbose(env, "cannot update sockmap in this context\n");
4320 return false;
4321}
4322
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004323static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4324{
4325 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4326}
4327
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004328static int check_map_func_compatibility(struct bpf_verifier_env *env,
4329 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00004330{
Kaixu Xia35578d72015-08-06 07:02:35 +00004331 if (!map)
4332 return 0;
4333
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004334 /* We need a two way check, first is from map perspective ... */
4335 switch (map->map_type) {
4336 case BPF_MAP_TYPE_PROG_ARRAY:
4337 if (func_id != BPF_FUNC_tail_call)
4338 goto error;
4339 break;
4340 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4341 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07004342 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004343 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004344 func_id != BPF_FUNC_perf_event_read_value &&
4345 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004346 goto error;
4347 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004348 case BPF_MAP_TYPE_RINGBUF:
4349 if (func_id != BPF_FUNC_ringbuf_output &&
4350 func_id != BPF_FUNC_ringbuf_reserve &&
4351 func_id != BPF_FUNC_ringbuf_submit &&
4352 func_id != BPF_FUNC_ringbuf_discard &&
4353 func_id != BPF_FUNC_ringbuf_query)
4354 goto error;
4355 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004356 case BPF_MAP_TYPE_STACK_TRACE:
4357 if (func_id != BPF_FUNC_get_stackid)
4358 goto error;
4359 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07004360 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04004361 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004362 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004363 goto error;
4364 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004365 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00004366 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07004367 if (func_id != BPF_FUNC_get_local_storage)
4368 goto error;
4369 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07004370 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004371 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02004372 if (func_id != BPF_FUNC_redirect_map &&
4373 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07004374 goto error;
4375 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004376 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4377 * appear.
4378 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02004379 case BPF_MAP_TYPE_CPUMAP:
4380 if (func_id != BPF_FUNC_redirect_map)
4381 goto error;
4382 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07004383 case BPF_MAP_TYPE_XSKMAP:
4384 if (func_id != BPF_FUNC_redirect_map &&
4385 func_id != BPF_FUNC_map_lookup_elem)
4386 goto error;
4387 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004388 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07004389 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004390 if (func_id != BPF_FUNC_map_lookup_elem)
4391 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07004392 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004393 case BPF_MAP_TYPE_SOCKMAP:
4394 if (func_id != BPF_FUNC_sk_redirect_map &&
4395 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07004396 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004397 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004398 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004399 func_id != BPF_FUNC_map_lookup_elem &&
4400 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07004401 goto error;
4402 break;
John Fastabend81110382018-05-14 10:00:17 -07004403 case BPF_MAP_TYPE_SOCKHASH:
4404 if (func_id != BPF_FUNC_sk_redirect_hash &&
4405 func_id != BPF_FUNC_sock_hash_update &&
4406 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004407 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004408 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004409 func_id != BPF_FUNC_map_lookup_elem &&
4410 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07004411 goto error;
4412 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004413 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4414 if (func_id != BPF_FUNC_sk_select_reuseport)
4415 goto error;
4416 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004417 case BPF_MAP_TYPE_QUEUE:
4418 case BPF_MAP_TYPE_STACK:
4419 if (func_id != BPF_FUNC_map_peek_elem &&
4420 func_id != BPF_FUNC_map_pop_elem &&
4421 func_id != BPF_FUNC_map_push_elem)
4422 goto error;
4423 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004424 case BPF_MAP_TYPE_SK_STORAGE:
4425 if (func_id != BPF_FUNC_sk_storage_get &&
4426 func_id != BPF_FUNC_sk_storage_delete)
4427 goto error;
4428 break;
KP Singh8ea63682020-08-25 20:29:17 +02004429 case BPF_MAP_TYPE_INODE_STORAGE:
4430 if (func_id != BPF_FUNC_inode_storage_get &&
4431 func_id != BPF_FUNC_inode_storage_delete)
4432 goto error;
4433 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004434 default:
4435 break;
4436 }
4437
4438 /* ... and second from the function itself. */
4439 switch (func_id) {
4440 case BPF_FUNC_tail_call:
4441 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4442 goto error;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004443 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4444 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004445 return -EINVAL;
4446 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004447 break;
4448 case BPF_FUNC_perf_event_read:
4449 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07004450 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004451 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004452 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004453 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4454 goto error;
4455 break;
4456 case BPF_FUNC_get_stackid:
4457 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4458 goto error;
4459 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004460 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02004461 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004462 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4463 goto error;
4464 break;
John Fastabend97f91a72017-07-17 09:29:18 -07004465 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02004466 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004467 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004468 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4469 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07004470 goto error;
4471 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004472 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07004473 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07004474 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07004475 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4476 goto error;
4477 break;
John Fastabend81110382018-05-14 10:00:17 -07004478 case BPF_FUNC_sk_redirect_hash:
4479 case BPF_FUNC_msg_redirect_hash:
4480 case BPF_FUNC_sock_hash_update:
4481 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07004482 goto error;
4483 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004484 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00004485 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4486 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07004487 goto error;
4488 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004489 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004490 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4491 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4492 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004493 goto error;
4494 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004495 case BPF_FUNC_map_peek_elem:
4496 case BPF_FUNC_map_pop_elem:
4497 case BPF_FUNC_map_push_elem:
4498 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4499 map->map_type != BPF_MAP_TYPE_STACK)
4500 goto error;
4501 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004502 case BPF_FUNC_sk_storage_get:
4503 case BPF_FUNC_sk_storage_delete:
4504 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4505 goto error;
4506 break;
KP Singh8ea63682020-08-25 20:29:17 +02004507 case BPF_FUNC_inode_storage_get:
4508 case BPF_FUNC_inode_storage_delete:
4509 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4510 goto error;
4511 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004512 default:
4513 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00004514 }
4515
4516 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004517error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004518 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004519 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004520 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00004521}
4522
Daniel Borkmann90133412018-01-20 01:24:29 +01004523static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004524{
4525 int count = 0;
4526
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004527 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004528 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004529 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004530 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004531 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004532 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004533 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004534 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004535 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004536 count++;
4537
Daniel Borkmann90133412018-01-20 01:24:29 +01004538 /* We only support one arg being in raw mode at the moment,
4539 * which is sufficient for the helper functions we have
4540 * right now.
4541 */
4542 return count <= 1;
4543}
4544
4545static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4546 enum bpf_arg_type arg_next)
4547{
4548 return (arg_type_is_mem_ptr(arg_curr) &&
4549 !arg_type_is_mem_size(arg_next)) ||
4550 (!arg_type_is_mem_ptr(arg_curr) &&
4551 arg_type_is_mem_size(arg_next));
4552}
4553
4554static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4555{
4556 /* bpf_xxx(..., buf, len) call will access 'len'
4557 * bytes from memory 'buf'. Both arg types need
4558 * to be paired, so make sure there's no buggy
4559 * helper function specification.
4560 */
4561 if (arg_type_is_mem_size(fn->arg1_type) ||
4562 arg_type_is_mem_ptr(fn->arg5_type) ||
4563 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4564 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4565 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4566 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4567 return false;
4568
4569 return true;
4570}
4571
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004572static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004573{
4574 int count = 0;
4575
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004576 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004577 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004578 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004579 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004580 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004581 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004582 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004583 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004584 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004585 count++;
4586
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004587 /* A reference acquiring function cannot acquire
4588 * another refcounted ptr.
4589 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004590 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004591 return false;
4592
Joe Stringerfd978bf72018-10-02 13:35:35 -07004593 /* We only support one arg being unreferenced at the moment,
4594 * which is sufficient for the helper functions we have right now.
4595 */
4596 return count <= 1;
4597}
4598
Lorenz Bauer9436ef62020-09-21 13:12:20 +01004599static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4600{
4601 int i;
4602
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004603 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
Lorenz Bauer9436ef62020-09-21 13:12:20 +01004604 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4605 return false;
4606
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004607 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
4608 return false;
4609 }
4610
Lorenz Bauer9436ef62020-09-21 13:12:20 +01004611 return true;
4612}
4613
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004614static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01004615{
4616 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07004617 check_arg_pair_ok(fn) &&
Lorenz Bauer9436ef62020-09-21 13:12:20 +01004618 check_btf_id_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004619 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02004620}
4621
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004622/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4623 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01004624 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004625static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4626 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004627{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01004628 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004629 int i;
4630
4631 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004632 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004633 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004634
Joe Stringerf3709f62018-10-02 13:35:29 -07004635 bpf_for_each_spilled_reg(i, state, reg) {
4636 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004637 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004638 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01004639 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004640 }
4641}
4642
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004643static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4644{
4645 struct bpf_verifier_state *vstate = env->cur_state;
4646 int i;
4647
4648 for (i = 0; i <= vstate->curframe; i++)
4649 __clear_all_pkt_pointers(env, vstate->frame[i]);
4650}
4651
Joe Stringerfd978bf72018-10-02 13:35:35 -07004652static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004653 struct bpf_func_state *state,
4654 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004655{
4656 struct bpf_reg_state *regs = state->regs, *reg;
4657 int i;
4658
4659 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004660 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004661 mark_reg_unknown(env, regs, i);
4662
4663 bpf_for_each_spilled_reg(i, state, reg) {
4664 if (!reg)
4665 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004666 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01004667 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07004668 }
4669}
4670
4671/* The pointer with the specified id has released its reference to kernel
4672 * resources. Identify all copies of the same pointer and clear the reference.
4673 */
4674static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004675 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004676{
4677 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004678 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004679 int i;
4680
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004681 err = release_reference_state(cur_func(env), ref_obj_id);
4682 if (err)
4683 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004684
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004685 for (i = 0; i <= vstate->curframe; i++)
4686 release_reg_references(env, vstate->frame[i], ref_obj_id);
4687
4688 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004689}
4690
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004691static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4692 struct bpf_reg_state *regs)
4693{
4694 int i;
4695
4696 /* after the call registers r0 - r5 were scratched */
4697 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4698 mark_reg_not_init(env, regs, caller_saved[i]);
4699 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4700 }
4701}
4702
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004703static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4704 int *insn_idx)
4705{
4706 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004707 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004708 struct bpf_func_state *caller, *callee;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004709 int i, err, subprog, target_insn;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004710 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004711
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08004712 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004713 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08004714 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004715 return -E2BIG;
4716 }
4717
4718 target_insn = *insn_idx + insn->imm;
4719 subprog = find_subprog(env, target_insn + 1);
4720 if (subprog < 0) {
4721 verbose(env, "verifier bug. No program starts at insn %d\n",
4722 target_insn + 1);
4723 return -EFAULT;
4724 }
4725
4726 caller = state->frame[state->curframe];
4727 if (state->frame[state->curframe + 1]) {
4728 verbose(env, "verifier bug. Frame %d already allocated\n",
4729 state->curframe + 1);
4730 return -EFAULT;
4731 }
4732
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004733 func_info_aux = env->prog->aux->func_info_aux;
4734 if (func_info_aux)
4735 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4736 err = btf_check_func_arg_match(env, subprog, caller->regs);
4737 if (err == -EFAULT)
4738 return err;
4739 if (is_global) {
4740 if (err) {
4741 verbose(env, "Caller passes invalid args into func#%d\n",
4742 subprog);
4743 return err;
4744 } else {
4745 if (env->log.level & BPF_LOG_LEVEL)
4746 verbose(env,
4747 "Func#%d is global and valid. Skipping.\n",
4748 subprog);
4749 clear_caller_saved_regs(env, caller->regs);
4750
4751 /* All global functions return SCALAR_VALUE */
4752 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4753
4754 /* continue with next insn after call */
4755 return 0;
4756 }
4757 }
4758
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004759 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4760 if (!callee)
4761 return -ENOMEM;
4762 state->frame[state->curframe + 1] = callee;
4763
4764 /* callee cannot access r0, r6 - r9 for reading and has to write
4765 * into its own stack before reading from it.
4766 * callee can read/write into caller's stack
4767 */
4768 init_func_state(env, callee,
4769 /* remember the callsite, it will be used by bpf_exit */
4770 *insn_idx /* callsite */,
4771 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04004772 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004773
Joe Stringerfd978bf72018-10-02 13:35:35 -07004774 /* Transfer references to the callee */
4775 err = transfer_reference_state(callee, caller);
4776 if (err)
4777 return err;
4778
Edward Cree679c7822018-08-22 20:02:19 +01004779 /* copy r1 - r5 args that callee can access. The copy includes parent
4780 * pointers, which connects us up to the liveness chain
4781 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004782 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4783 callee->regs[i] = caller->regs[i];
4784
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004785 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004786
4787 /* only increment it after check_reg_arg() finished */
4788 state->curframe++;
4789
4790 /* and go analyze first insn of the callee */
4791 *insn_idx = target_insn;
4792
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004793 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004794 verbose(env, "caller:\n");
4795 print_verifier_state(env, caller);
4796 verbose(env, "callee:\n");
4797 print_verifier_state(env, callee);
4798 }
4799 return 0;
4800}
4801
4802static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4803{
4804 struct bpf_verifier_state *state = env->cur_state;
4805 struct bpf_func_state *caller, *callee;
4806 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004807 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004808
4809 callee = state->frame[state->curframe];
4810 r0 = &callee->regs[BPF_REG_0];
4811 if (r0->type == PTR_TO_STACK) {
4812 /* technically it's ok to return caller's stack pointer
4813 * (or caller's caller's pointer) back to the caller,
4814 * since these pointers are valid. Only current stack
4815 * pointer will be invalid as soon as function exits,
4816 * but let's be conservative
4817 */
4818 verbose(env, "cannot return stack pointer to the caller\n");
4819 return -EINVAL;
4820 }
4821
4822 state->curframe--;
4823 caller = state->frame[state->curframe];
4824 /* return to the caller whatever r0 had in the callee */
4825 caller->regs[BPF_REG_0] = *r0;
4826
Joe Stringerfd978bf72018-10-02 13:35:35 -07004827 /* Transfer references to the caller */
4828 err = transfer_reference_state(caller, callee);
4829 if (err)
4830 return err;
4831
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004832 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004833 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004834 verbose(env, "returning from callee:\n");
4835 print_verifier_state(env, callee);
4836 verbose(env, "to caller at %d:\n", *insn_idx);
4837 print_verifier_state(env, caller);
4838 }
4839 /* clear everything in the callee */
4840 free_func_state(callee);
4841 state->frame[state->curframe + 1] = NULL;
4842 return 0;
4843}
4844
Yonghong Song849fa502018-04-28 22:28:09 -07004845static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4846 int func_id,
4847 struct bpf_call_arg_meta *meta)
4848{
4849 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4850
4851 if (ret_type != RET_INTEGER ||
4852 (func_id != BPF_FUNC_get_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02004853 func_id != BPF_FUNC_probe_read_str &&
4854 func_id != BPF_FUNC_probe_read_kernel_str &&
4855 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07004856 return;
4857
John Fastabend10060502020-03-30 14:36:19 -07004858 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07004859 ret_reg->s32_max_value = meta->msize_max_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004860 __reg_deduce_bounds(ret_reg);
4861 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07004862 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07004863}
4864
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004865static int
4866record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4867 int func_id, int insn_idx)
4868{
4869 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02004870 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004871
4872 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02004873 func_id != BPF_FUNC_map_lookup_elem &&
4874 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004875 func_id != BPF_FUNC_map_delete_elem &&
4876 func_id != BPF_FUNC_map_push_elem &&
4877 func_id != BPF_FUNC_map_pop_elem &&
4878 func_id != BPF_FUNC_map_peek_elem)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004879 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02004880
Daniel Borkmann591fe982019-04-09 23:20:05 +02004881 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004882 verbose(env, "kernel subsystem misconfigured verifier\n");
4883 return -EINVAL;
4884 }
4885
Daniel Borkmann591fe982019-04-09 23:20:05 +02004886 /* In case of read-only, some additional restrictions
4887 * need to be applied in order to prevent altering the
4888 * state of the map from program side.
4889 */
4890 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4891 (func_id == BPF_FUNC_map_delete_elem ||
4892 func_id == BPF_FUNC_map_update_elem ||
4893 func_id == BPF_FUNC_map_push_elem ||
4894 func_id == BPF_FUNC_map_pop_elem)) {
4895 verbose(env, "write into map forbidden\n");
4896 return -EACCES;
4897 }
4898
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004899 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004900 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004901 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004902 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004903 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004904 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004905 return 0;
4906}
4907
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004908static int
4909record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4910 int func_id, int insn_idx)
4911{
4912 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4913 struct bpf_reg_state *regs = cur_regs(env), *reg;
4914 struct bpf_map *map = meta->map_ptr;
4915 struct tnum range;
4916 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004917 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004918
4919 if (func_id != BPF_FUNC_tail_call)
4920 return 0;
4921 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4922 verbose(env, "kernel subsystem misconfigured verifier\n");
4923 return -EINVAL;
4924 }
4925
4926 range = tnum_range(0, map->max_entries - 1);
4927 reg = &regs[BPF_REG_3];
4928
4929 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4930 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4931 return 0;
4932 }
4933
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004934 err = mark_chain_precision(env, BPF_REG_3);
4935 if (err)
4936 return err;
4937
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004938 val = reg->var_off.value;
4939 if (bpf_map_key_unseen(aux))
4940 bpf_map_key_store(aux, val);
4941 else if (!bpf_map_key_poisoned(aux) &&
4942 bpf_map_key_immediate(aux) != val)
4943 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4944 return 0;
4945}
4946
Joe Stringerfd978bf72018-10-02 13:35:35 -07004947static int check_reference_leak(struct bpf_verifier_env *env)
4948{
4949 struct bpf_func_state *state = cur_func(env);
4950 int i;
4951
4952 for (i = 0; i < state->acquired_refs; i++) {
4953 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4954 state->refs[i].id, state->refs[i].insn_idx);
4955 }
4956 return state->acquired_refs ? -EINVAL : 0;
4957}
4958
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004959static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004960{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004961 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004962 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004963 struct bpf_call_arg_meta meta;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004964 bool changes_data;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004965 int i, err;
4966
4967 /* find function prototype */
4968 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004969 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4970 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004971 return -EINVAL;
4972 }
4973
Jakub Kicinski00176a32017-10-16 16:40:54 -07004974 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07004975 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004976 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004977 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4978 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004979 return -EINVAL;
4980 }
4981
4982 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01004983 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02004984 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004985 return -EINVAL;
4986 }
4987
Jiri Olsaeae2e832020-08-25 21:21:19 +02004988 if (fn->allowed && !fn->allowed(env->prog)) {
4989 verbose(env, "helper call is not allowed in probe\n");
4990 return -EINVAL;
4991 }
4992
Daniel Borkmann04514d12017-12-14 21:07:25 +01004993 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08004994 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01004995 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4996 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4997 func_id_name(func_id), func_id);
4998 return -EINVAL;
4999 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005000
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005001 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02005002 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005003
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005004 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005005 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005006 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005007 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005008 return err;
5009 }
5010
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08005011 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005012 /* check args */
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005013 for (i = 0; i < 5; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07005014 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005015 if (err)
5016 return err;
5017 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005018
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005019 err = record_func_map(env, &meta, func_id, insn_idx);
5020 if (err)
5021 return err;
5022
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005023 err = record_func_key(env, &meta, func_id, insn_idx);
5024 if (err)
5025 return err;
5026
Daniel Borkmann435faee12016-04-13 00:10:51 +02005027 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5028 * is inferred from register state.
5029 */
5030 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01005031 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5032 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005033 if (err)
5034 return err;
5035 }
5036
Joe Stringerfd978bf72018-10-02 13:35:35 -07005037 if (func_id == BPF_FUNC_tail_call) {
5038 err = check_reference_leak(env);
5039 if (err) {
5040 verbose(env, "tail_call would lead to reference leak\n");
5041 return err;
5042 }
5043 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005044 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005045 if (err) {
5046 verbose(env, "func %s#%d reference has not been acquired before\n",
5047 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005048 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005049 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07005050 }
5051
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005052 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07005053
5054 /* check that flags argument in get_local_storage(map, flags) is 0,
5055 * this is required because get_local_storage() can't return an error.
5056 */
5057 if (func_id == BPF_FUNC_get_local_storage &&
5058 !register_is_null(&regs[BPF_REG_2])) {
5059 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5060 return -EINVAL;
5061 }
5062
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005063 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01005064 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005065 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01005066 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5067 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005068
Jiong Wang5327ed32019-05-24 23:25:12 +01005069 /* helper call returns 64-bit value. */
5070 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5071
Edward Creedc503a82017-08-15 20:34:35 +01005072 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005073 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01005074 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005075 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005076 } else if (fn->ret_type == RET_VOID) {
5077 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07005078 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5079 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01005080 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005081 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005082 /* remember map_ptr, so that check_map_access()
5083 * can check 'value_size' boundary of memory access
5084 * to map element returned from bpf_map_lookup_elem()
5085 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005086 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005087 verbose(env,
5088 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005089 return -EINVAL;
5090 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005091 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005092 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5093 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08005094 if (map_value_has_spin_lock(meta.map_ptr))
5095 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005096 } else {
5097 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5098 regs[BPF_REG_0].id = ++env->id_gen;
5099 }
Joe Stringerc64b7982018-10-02 13:35:33 -07005100 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5101 mark_reg_known_zero(env, regs, BPF_REG_0);
5102 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005103 regs[BPF_REG_0].id = ++env->id_gen;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08005104 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5105 mark_reg_known_zero(env, regs, BPF_REG_0);
5106 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5107 regs[BPF_REG_0].id = ++env->id_gen;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005108 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5109 mark_reg_known_zero(env, regs, BPF_REG_0);
5110 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5111 regs[BPF_REG_0].id = ++env->id_gen;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005112 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5113 mark_reg_known_zero(env, regs, BPF_REG_0);
5114 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5115 regs[BPF_REG_0].id = ++env->id_gen;
5116 regs[BPF_REG_0].mem_size = meta.mem_size;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005117 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5118 int ret_btf_id;
5119
5120 mark_reg_known_zero(env, regs, BPF_REG_0);
5121 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5122 ret_btf_id = *fn->ret_btf_id;
5123 if (ret_btf_id == 0) {
5124 verbose(env, "invalid return type %d of func %s#%d\n",
5125 fn->ret_type, func_id_name(func_id), func_id);
5126 return -EINVAL;
5127 }
5128 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005129 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005130 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005131 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005132 return -EINVAL;
5133 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005134
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005135 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005136 /* For release_reference() */
5137 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005138 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005139 int id = acquire_reference_state(env, insn_idx);
5140
5141 if (id < 0)
5142 return id;
5143 /* For mark_ptr_or_null_reg() */
5144 regs[BPF_REG_0].id = id;
5145 /* For release_reference() */
5146 regs[BPF_REG_0].ref_obj_id = id;
5147 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005148
Yonghong Song849fa502018-04-28 22:28:09 -07005149 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5150
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005151 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00005152 if (err)
5153 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005154
Song Liufa28dcb2020-06-29 23:28:44 -07005155 if ((func_id == BPF_FUNC_get_stack ||
5156 func_id == BPF_FUNC_get_task_stack) &&
5157 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07005158 const char *err_str;
5159
5160#ifdef CONFIG_PERF_EVENTS
5161 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5162 err_str = "cannot get callchain buffer for func %s#%d\n";
5163#else
5164 err = -ENOTSUPP;
5165 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5166#endif
5167 if (err) {
5168 verbose(env, err_str, func_id_name(func_id), func_id);
5169 return err;
5170 }
5171
5172 env->prog->has_callchain_buf = true;
5173 }
5174
Song Liu5d99cb2c2020-07-23 11:06:45 -07005175 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5176 env->prog->call_get_stack = true;
5177
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005178 if (changes_data)
5179 clear_all_pkt_pointers(env);
5180 return 0;
5181}
5182
Edward Creeb03c9f92017-08-07 15:26:36 +01005183static bool signed_add_overflows(s64 a, s64 b)
5184{
5185 /* Do the add in u64, where overflow is well-defined */
5186 s64 res = (s64)((u64)a + (u64)b);
5187
5188 if (b < 0)
5189 return res > a;
5190 return res < a;
5191}
5192
John Fastabend3f50f132020-03-30 14:36:39 -07005193static bool signed_add32_overflows(s64 a, s64 b)
5194{
5195 /* Do the add in u32, where overflow is well-defined */
5196 s32 res = (s32)((u32)a + (u32)b);
5197
5198 if (b < 0)
5199 return res > a;
5200 return res < a;
5201}
5202
5203static bool signed_sub_overflows(s32 a, s32 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01005204{
5205 /* Do the sub in u64, where overflow is well-defined */
5206 s64 res = (s64)((u64)a - (u64)b);
5207
5208 if (b < 0)
5209 return res < a;
5210 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07005211}
5212
John Fastabend3f50f132020-03-30 14:36:39 -07005213static bool signed_sub32_overflows(s32 a, s32 b)
5214{
5215 /* Do the sub in u64, where overflow is well-defined */
5216 s32 res = (s32)((u32)a - (u32)b);
5217
5218 if (b < 0)
5219 return res < a;
5220 return res > a;
5221}
5222
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005223static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5224 const struct bpf_reg_state *reg,
5225 enum bpf_reg_type type)
5226{
5227 bool known = tnum_is_const(reg->var_off);
5228 s64 val = reg->var_off.value;
5229 s64 smin = reg->smin_value;
5230
5231 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5232 verbose(env, "math between %s pointer and %lld is not allowed\n",
5233 reg_type_str[type], val);
5234 return false;
5235 }
5236
5237 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5238 verbose(env, "%s pointer offset %d is not allowed\n",
5239 reg_type_str[type], reg->off);
5240 return false;
5241 }
5242
5243 if (smin == S64_MIN) {
5244 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5245 reg_type_str[type]);
5246 return false;
5247 }
5248
5249 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5250 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5251 smin, reg_type_str[type]);
5252 return false;
5253 }
5254
5255 return true;
5256}
5257
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005258static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5259{
5260 return &env->insn_aux_data[env->insn_idx];
5261}
5262
5263static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5264 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5265{
5266 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5267 (opcode == BPF_SUB && !off_is_neg);
5268 u32 off;
5269
5270 switch (ptr_reg->type) {
5271 case PTR_TO_STACK:
Andrey Ignatov088ec262019-04-03 23:22:39 -07005272 /* Indirect variable offset stack access is prohibited in
5273 * unprivileged mode so it's not handled here.
5274 */
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005275 off = ptr_reg->off + ptr_reg->var_off.value;
5276 if (mask_to_left)
5277 *ptr_limit = MAX_BPF_STACK + off;
5278 else
5279 *ptr_limit = -off;
5280 return 0;
5281 case PTR_TO_MAP_VALUE:
5282 if (mask_to_left) {
5283 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5284 } else {
5285 off = ptr_reg->smin_value + ptr_reg->off;
5286 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5287 }
5288 return 0;
5289 default:
5290 return -EINVAL;
5291 }
5292}
5293
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005294static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5295 const struct bpf_insn *insn)
5296{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005297 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005298}
5299
5300static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5301 u32 alu_state, u32 alu_limit)
5302{
5303 /* If we arrived here from different branches with different
5304 * state or limits to sanitize, then this won't work.
5305 */
5306 if (aux->alu_state &&
5307 (aux->alu_state != alu_state ||
5308 aux->alu_limit != alu_limit))
5309 return -EACCES;
5310
5311 /* Corresponding fixup done in fixup_bpf_calls(). */
5312 aux->alu_state = alu_state;
5313 aux->alu_limit = alu_limit;
5314 return 0;
5315}
5316
5317static int sanitize_val_alu(struct bpf_verifier_env *env,
5318 struct bpf_insn *insn)
5319{
5320 struct bpf_insn_aux_data *aux = cur_aux(env);
5321
5322 if (can_skip_alu_sanitation(env, insn))
5323 return 0;
5324
5325 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5326}
5327
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005328static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5329 struct bpf_insn *insn,
5330 const struct bpf_reg_state *ptr_reg,
5331 struct bpf_reg_state *dst_reg,
5332 bool off_is_neg)
5333{
5334 struct bpf_verifier_state *vstate = env->cur_state;
5335 struct bpf_insn_aux_data *aux = cur_aux(env);
5336 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5337 u8 opcode = BPF_OP(insn->code);
5338 u32 alu_state, alu_limit;
5339 struct bpf_reg_state tmp;
5340 bool ret;
5341
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005342 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005343 return 0;
5344
5345 /* We already marked aux for masking from non-speculative
5346 * paths, thus we got here in the first place. We only care
5347 * to explore bad access from here.
5348 */
5349 if (vstate->speculative)
5350 goto do_sim;
5351
5352 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5353 alu_state |= ptr_is_dst_reg ?
5354 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5355
5356 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5357 return 0;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005358 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005359 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005360do_sim:
5361 /* Simulate and find potential out-of-bounds access under
5362 * speculative execution from truncation as a result of
5363 * masking when off was not within expected range. If off
5364 * sits in dst, then we temporarily need to move ptr there
5365 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5366 * for cases where we use K-based arithmetic in one direction
5367 * and truncated reg-based in the other in order to explore
5368 * bad access.
5369 */
5370 if (!ptr_is_dst_reg) {
5371 tmp = *dst_reg;
5372 *dst_reg = *ptr_reg;
5373 }
5374 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08005375 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005376 *dst_reg = tmp;
5377 return !ret ? -EFAULT : 0;
5378}
5379
Edward Creef1174f72017-08-07 15:26:19 +01005380/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01005381 * Caller should also handle BPF_MOV case separately.
5382 * If we return -EACCES, caller may want to try again treating pointer as a
5383 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5384 */
5385static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5386 struct bpf_insn *insn,
5387 const struct bpf_reg_state *ptr_reg,
5388 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04005389{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005390 struct bpf_verifier_state *vstate = env->cur_state;
5391 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5392 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01005393 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01005394 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5395 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5396 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5397 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01005398 u32 dst = insn->dst_reg, src = insn->src_reg;
Josef Bacik48461132016-09-28 10:54:32 -04005399 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005400 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04005401
Edward Creef1174f72017-08-07 15:26:19 +01005402 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04005403
Daniel Borkmann6f161012018-01-18 01:15:21 +01005404 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5405 smin_val > smax_val || umin_val > umax_val) {
5406 /* Taint dst register if offset had invalid bounds derived from
5407 * e.g. dead branches.
5408 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005409 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01005410 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04005411 }
5412
Edward Creef1174f72017-08-07 15:26:19 +01005413 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5414 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07005415 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5416 __mark_reg_unknown(env, dst_reg);
5417 return 0;
5418 }
5419
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005420 verbose(env,
5421 "R%d 32-bit pointer arithmetic prohibited\n",
5422 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005423 return -EACCES;
5424 }
David S. Millerd1174412017-05-10 11:22:52 -07005425
Joe Stringeraad2eea2018-10-02 13:35:30 -07005426 switch (ptr_reg->type) {
5427 case PTR_TO_MAP_VALUE_OR_NULL:
5428 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5429 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01005430 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07005431 case CONST_PTR_TO_MAP:
Yonghong Song7c696732020-09-08 10:57:02 -07005432 /* smin_val represents the known value */
5433 if (known && smin_val == 0 && opcode == BPF_ADD)
5434 break;
5435 /* fall-through */
Joe Stringeraad2eea2018-10-02 13:35:30 -07005436 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07005437 case PTR_TO_SOCKET:
5438 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005439 case PTR_TO_SOCK_COMMON:
5440 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005441 case PTR_TO_TCP_SOCK:
5442 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07005443 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07005444 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5445 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01005446 return -EACCES;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01005447 case PTR_TO_MAP_VALUE:
5448 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5449 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5450 off_reg == dst_reg ? dst : src);
5451 return -EACCES;
5452 }
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -05005453 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07005454 default:
5455 break;
Edward Creef1174f72017-08-07 15:26:19 +01005456 }
5457
5458 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5459 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04005460 */
Edward Creef1174f72017-08-07 15:26:19 +01005461 dst_reg->type = ptr_reg->type;
5462 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05005463
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005464 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5465 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5466 return -EINVAL;
5467
John Fastabend3f50f132020-03-30 14:36:39 -07005468 /* pointer types do not carry 32-bit bounds at the moment. */
5469 __mark_reg32_unbounded(dst_reg);
5470
Josef Bacik48461132016-09-28 10:54:32 -04005471 switch (opcode) {
5472 case BPF_ADD:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005473 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5474 if (ret < 0) {
5475 verbose(env, "R%d tried to add from different maps or paths\n", dst);
5476 return ret;
5477 }
Edward Creef1174f72017-08-07 15:26:19 +01005478 /* We can take a fixed offset as long as it doesn't overflow
5479 * the s32 'off' field
5480 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005481 if (known && (ptr_reg->off + smin_val ==
5482 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01005483 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01005484 dst_reg->smin_value = smin_ptr;
5485 dst_reg->smax_value = smax_ptr;
5486 dst_reg->umin_value = umin_ptr;
5487 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01005488 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01005489 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01005490 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01005491 break;
5492 }
Edward Creef1174f72017-08-07 15:26:19 +01005493 /* A new variable offset is created. Note that off_reg->off
5494 * == 0, since it's a scalar.
5495 * dst_reg gets the pointer type and since some positive
5496 * integer value was added to the pointer, give it a new 'id'
5497 * if it's a PTR_TO_PACKET.
5498 * this creates a new 'base' pointer, off_reg (variable) gets
5499 * added into the variable offset, and we copy the fixed offset
5500 * from ptr_reg.
5501 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005502 if (signed_add_overflows(smin_ptr, smin_val) ||
5503 signed_add_overflows(smax_ptr, smax_val)) {
5504 dst_reg->smin_value = S64_MIN;
5505 dst_reg->smax_value = S64_MAX;
5506 } else {
5507 dst_reg->smin_value = smin_ptr + smin_val;
5508 dst_reg->smax_value = smax_ptr + smax_val;
5509 }
5510 if (umin_ptr + umin_val < umin_ptr ||
5511 umax_ptr + umax_val < umax_ptr) {
5512 dst_reg->umin_value = 0;
5513 dst_reg->umax_value = U64_MAX;
5514 } else {
5515 dst_reg->umin_value = umin_ptr + umin_val;
5516 dst_reg->umax_value = umax_ptr + umax_val;
5517 }
Edward Creef1174f72017-08-07 15:26:19 +01005518 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5519 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01005520 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005521 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01005522 dst_reg->id = ++env->id_gen;
5523 /* something was added to pkt_ptr, set range to zero */
Daniel Borkmann09625902018-11-01 00:05:52 +01005524 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01005525 }
Josef Bacik48461132016-09-28 10:54:32 -04005526 break;
5527 case BPF_SUB:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005528 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5529 if (ret < 0) {
5530 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5531 return ret;
5532 }
Edward Creef1174f72017-08-07 15:26:19 +01005533 if (dst_reg == off_reg) {
5534 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005535 verbose(env, "R%d tried to subtract pointer from scalar\n",
5536 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005537 return -EACCES;
5538 }
5539 /* We don't allow subtraction from FP, because (according to
5540 * test_verifier.c test "invalid fp arithmetic", JITs might not
5541 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01005542 */
Edward Creef1174f72017-08-07 15:26:19 +01005543 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005544 verbose(env, "R%d subtraction from stack pointer prohibited\n",
5545 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005546 return -EACCES;
5547 }
Edward Creeb03c9f92017-08-07 15:26:36 +01005548 if (known && (ptr_reg->off - smin_val ==
5549 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01005550 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01005551 dst_reg->smin_value = smin_ptr;
5552 dst_reg->smax_value = smax_ptr;
5553 dst_reg->umin_value = umin_ptr;
5554 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01005555 dst_reg->var_off = ptr_reg->var_off;
5556 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01005557 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01005558 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01005559 break;
5560 }
Edward Creef1174f72017-08-07 15:26:19 +01005561 /* A new variable offset is created. If the subtrahend is known
5562 * nonnegative, then any reg->range we had before is still good.
5563 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005564 if (signed_sub_overflows(smin_ptr, smax_val) ||
5565 signed_sub_overflows(smax_ptr, smin_val)) {
5566 /* Overflow possible, we know nothing */
5567 dst_reg->smin_value = S64_MIN;
5568 dst_reg->smax_value = S64_MAX;
5569 } else {
5570 dst_reg->smin_value = smin_ptr - smax_val;
5571 dst_reg->smax_value = smax_ptr - smin_val;
5572 }
5573 if (umin_ptr < umax_val) {
5574 /* Overflow possible, we know nothing */
5575 dst_reg->umin_value = 0;
5576 dst_reg->umax_value = U64_MAX;
5577 } else {
5578 /* Cannot overflow (as long as bounds are consistent) */
5579 dst_reg->umin_value = umin_ptr - umax_val;
5580 dst_reg->umax_value = umax_ptr - umin_val;
5581 }
Edward Creef1174f72017-08-07 15:26:19 +01005582 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5583 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01005584 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005585 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01005586 dst_reg->id = ++env->id_gen;
5587 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01005588 if (smin_val < 0)
Daniel Borkmann09625902018-11-01 00:05:52 +01005589 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01005590 }
5591 break;
5592 case BPF_AND:
5593 case BPF_OR:
5594 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005595 /* bitwise ops on pointers are troublesome, prohibit. */
5596 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5597 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01005598 return -EACCES;
5599 default:
5600 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005601 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5602 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01005603 return -EACCES;
5604 }
5605
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005606 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5607 return -EINVAL;
5608
Edward Creeb03c9f92017-08-07 15:26:36 +01005609 __update_reg_bounds(dst_reg);
5610 __reg_deduce_bounds(dst_reg);
5611 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01005612
5613 /* For unprivileged we require that resulting offset must be in bounds
5614 * in order to be able to sanitize access later on.
5615 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005616 if (!env->bypass_spec_v1) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01005617 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5618 check_map_access(env, dst, dst_reg->off, 1, false)) {
5619 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5620 "prohibited for !root\n", dst);
5621 return -EACCES;
5622 } else if (dst_reg->type == PTR_TO_STACK &&
5623 check_stack_access(env, dst_reg, dst_reg->off +
5624 dst_reg->var_off.value, 1)) {
5625 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5626 "prohibited for !root\n", dst);
5627 return -EACCES;
5628 }
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01005629 }
5630
Edward Creef1174f72017-08-07 15:26:19 +01005631 return 0;
5632}
5633
John Fastabend3f50f132020-03-30 14:36:39 -07005634static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5635 struct bpf_reg_state *src_reg)
5636{
5637 s32 smin_val = src_reg->s32_min_value;
5638 s32 smax_val = src_reg->s32_max_value;
5639 u32 umin_val = src_reg->u32_min_value;
5640 u32 umax_val = src_reg->u32_max_value;
5641
5642 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5643 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5644 dst_reg->s32_min_value = S32_MIN;
5645 dst_reg->s32_max_value = S32_MAX;
5646 } else {
5647 dst_reg->s32_min_value += smin_val;
5648 dst_reg->s32_max_value += smax_val;
5649 }
5650 if (dst_reg->u32_min_value + umin_val < umin_val ||
5651 dst_reg->u32_max_value + umax_val < umax_val) {
5652 dst_reg->u32_min_value = 0;
5653 dst_reg->u32_max_value = U32_MAX;
5654 } else {
5655 dst_reg->u32_min_value += umin_val;
5656 dst_reg->u32_max_value += umax_val;
5657 }
5658}
5659
John Fastabend07cd2632020-03-24 10:38:15 -07005660static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5661 struct bpf_reg_state *src_reg)
5662{
5663 s64 smin_val = src_reg->smin_value;
5664 s64 smax_val = src_reg->smax_value;
5665 u64 umin_val = src_reg->umin_value;
5666 u64 umax_val = src_reg->umax_value;
5667
5668 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5669 signed_add_overflows(dst_reg->smax_value, smax_val)) {
5670 dst_reg->smin_value = S64_MIN;
5671 dst_reg->smax_value = S64_MAX;
5672 } else {
5673 dst_reg->smin_value += smin_val;
5674 dst_reg->smax_value += smax_val;
5675 }
5676 if (dst_reg->umin_value + umin_val < umin_val ||
5677 dst_reg->umax_value + umax_val < umax_val) {
5678 dst_reg->umin_value = 0;
5679 dst_reg->umax_value = U64_MAX;
5680 } else {
5681 dst_reg->umin_value += umin_val;
5682 dst_reg->umax_value += umax_val;
5683 }
John Fastabend3f50f132020-03-30 14:36:39 -07005684}
5685
5686static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5687 struct bpf_reg_state *src_reg)
5688{
5689 s32 smin_val = src_reg->s32_min_value;
5690 s32 smax_val = src_reg->s32_max_value;
5691 u32 umin_val = src_reg->u32_min_value;
5692 u32 umax_val = src_reg->u32_max_value;
5693
5694 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5695 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5696 /* Overflow possible, we know nothing */
5697 dst_reg->s32_min_value = S32_MIN;
5698 dst_reg->s32_max_value = S32_MAX;
5699 } else {
5700 dst_reg->s32_min_value -= smax_val;
5701 dst_reg->s32_max_value -= smin_val;
5702 }
5703 if (dst_reg->u32_min_value < umax_val) {
5704 /* Overflow possible, we know nothing */
5705 dst_reg->u32_min_value = 0;
5706 dst_reg->u32_max_value = U32_MAX;
5707 } else {
5708 /* Cannot overflow (as long as bounds are consistent) */
5709 dst_reg->u32_min_value -= umax_val;
5710 dst_reg->u32_max_value -= umin_val;
5711 }
John Fastabend07cd2632020-03-24 10:38:15 -07005712}
5713
5714static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5715 struct bpf_reg_state *src_reg)
5716{
5717 s64 smin_val = src_reg->smin_value;
5718 s64 smax_val = src_reg->smax_value;
5719 u64 umin_val = src_reg->umin_value;
5720 u64 umax_val = src_reg->umax_value;
5721
5722 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5723 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5724 /* Overflow possible, we know nothing */
5725 dst_reg->smin_value = S64_MIN;
5726 dst_reg->smax_value = S64_MAX;
5727 } else {
5728 dst_reg->smin_value -= smax_val;
5729 dst_reg->smax_value -= smin_val;
5730 }
5731 if (dst_reg->umin_value < umax_val) {
5732 /* Overflow possible, we know nothing */
5733 dst_reg->umin_value = 0;
5734 dst_reg->umax_value = U64_MAX;
5735 } else {
5736 /* Cannot overflow (as long as bounds are consistent) */
5737 dst_reg->umin_value -= umax_val;
5738 dst_reg->umax_value -= umin_val;
5739 }
John Fastabend3f50f132020-03-30 14:36:39 -07005740}
5741
5742static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5743 struct bpf_reg_state *src_reg)
5744{
5745 s32 smin_val = src_reg->s32_min_value;
5746 u32 umin_val = src_reg->u32_min_value;
5747 u32 umax_val = src_reg->u32_max_value;
5748
5749 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5750 /* Ain't nobody got time to multiply that sign */
5751 __mark_reg32_unbounded(dst_reg);
5752 return;
5753 }
5754 /* Both values are positive, so we can work with unsigned and
5755 * copy the result to signed (unless it exceeds S32_MAX).
5756 */
5757 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5758 /* Potential overflow, we know nothing */
5759 __mark_reg32_unbounded(dst_reg);
5760 return;
5761 }
5762 dst_reg->u32_min_value *= umin_val;
5763 dst_reg->u32_max_value *= umax_val;
5764 if (dst_reg->u32_max_value > S32_MAX) {
5765 /* Overflow possible, we know nothing */
5766 dst_reg->s32_min_value = S32_MIN;
5767 dst_reg->s32_max_value = S32_MAX;
5768 } else {
5769 dst_reg->s32_min_value = dst_reg->u32_min_value;
5770 dst_reg->s32_max_value = dst_reg->u32_max_value;
5771 }
John Fastabend07cd2632020-03-24 10:38:15 -07005772}
5773
5774static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5775 struct bpf_reg_state *src_reg)
5776{
5777 s64 smin_val = src_reg->smin_value;
5778 u64 umin_val = src_reg->umin_value;
5779 u64 umax_val = src_reg->umax_value;
5780
John Fastabend07cd2632020-03-24 10:38:15 -07005781 if (smin_val < 0 || dst_reg->smin_value < 0) {
5782 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07005783 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07005784 return;
5785 }
5786 /* Both values are positive, so we can work with unsigned and
5787 * copy the result to signed (unless it exceeds S64_MAX).
5788 */
5789 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5790 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07005791 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07005792 return;
5793 }
5794 dst_reg->umin_value *= umin_val;
5795 dst_reg->umax_value *= umax_val;
5796 if (dst_reg->umax_value > S64_MAX) {
5797 /* Overflow possible, we know nothing */
5798 dst_reg->smin_value = S64_MIN;
5799 dst_reg->smax_value = S64_MAX;
5800 } else {
5801 dst_reg->smin_value = dst_reg->umin_value;
5802 dst_reg->smax_value = dst_reg->umax_value;
5803 }
5804}
5805
John Fastabend3f50f132020-03-30 14:36:39 -07005806static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5807 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07005808{
John Fastabend3f50f132020-03-30 14:36:39 -07005809 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5810 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5811 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5812 s32 smin_val = src_reg->s32_min_value;
5813 u32 umax_val = src_reg->u32_max_value;
5814
5815 /* Assuming scalar64_min_max_and will be called so its safe
5816 * to skip updating register for known 32-bit case.
5817 */
5818 if (src_known && dst_known)
5819 return;
John Fastabend07cd2632020-03-24 10:38:15 -07005820
5821 /* We get our minimum from the var_off, since that's inherently
5822 * bitwise. Our maximum is the minimum of the operands' maxima.
5823 */
John Fastabend3f50f132020-03-30 14:36:39 -07005824 dst_reg->u32_min_value = var32_off.value;
5825 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5826 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5827 /* Lose signed bounds when ANDing negative numbers,
5828 * ain't nobody got time for that.
5829 */
5830 dst_reg->s32_min_value = S32_MIN;
5831 dst_reg->s32_max_value = S32_MAX;
5832 } else {
5833 /* ANDing two positives gives a positive, so safe to
5834 * cast result into s64.
5835 */
5836 dst_reg->s32_min_value = dst_reg->u32_min_value;
5837 dst_reg->s32_max_value = dst_reg->u32_max_value;
5838 }
5839
5840}
5841
5842static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5843 struct bpf_reg_state *src_reg)
5844{
5845 bool src_known = tnum_is_const(src_reg->var_off);
5846 bool dst_known = tnum_is_const(dst_reg->var_off);
5847 s64 smin_val = src_reg->smin_value;
5848 u64 umax_val = src_reg->umax_value;
5849
5850 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07005851 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07005852 return;
5853 }
5854
5855 /* We get our minimum from the var_off, since that's inherently
5856 * bitwise. Our maximum is the minimum of the operands' maxima.
5857 */
John Fastabend07cd2632020-03-24 10:38:15 -07005858 dst_reg->umin_value = dst_reg->var_off.value;
5859 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5860 if (dst_reg->smin_value < 0 || smin_val < 0) {
5861 /* Lose signed bounds when ANDing negative numbers,
5862 * ain't nobody got time for that.
5863 */
5864 dst_reg->smin_value = S64_MIN;
5865 dst_reg->smax_value = S64_MAX;
5866 } else {
5867 /* ANDing two positives gives a positive, so safe to
5868 * cast result into s64.
5869 */
5870 dst_reg->smin_value = dst_reg->umin_value;
5871 dst_reg->smax_value = dst_reg->umax_value;
5872 }
5873 /* We may learn something more from the var_off */
5874 __update_reg_bounds(dst_reg);
5875}
5876
John Fastabend3f50f132020-03-30 14:36:39 -07005877static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5878 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07005879{
John Fastabend3f50f132020-03-30 14:36:39 -07005880 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5881 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5882 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5883 s32 smin_val = src_reg->smin_value;
5884 u32 umin_val = src_reg->umin_value;
5885
5886 /* Assuming scalar64_min_max_or will be called so it is safe
5887 * to skip updating register for known case.
5888 */
5889 if (src_known && dst_known)
5890 return;
John Fastabend07cd2632020-03-24 10:38:15 -07005891
5892 /* We get our maximum from the var_off, and our minimum is the
5893 * maximum of the operands' minima
5894 */
John Fastabend3f50f132020-03-30 14:36:39 -07005895 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5896 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5897 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5898 /* Lose signed bounds when ORing negative numbers,
5899 * ain't nobody got time for that.
5900 */
5901 dst_reg->s32_min_value = S32_MIN;
5902 dst_reg->s32_max_value = S32_MAX;
5903 } else {
5904 /* ORing two positives gives a positive, so safe to
5905 * cast result into s64.
5906 */
5907 dst_reg->s32_min_value = dst_reg->umin_value;
5908 dst_reg->s32_max_value = dst_reg->umax_value;
5909 }
5910}
5911
5912static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5913 struct bpf_reg_state *src_reg)
5914{
5915 bool src_known = tnum_is_const(src_reg->var_off);
5916 bool dst_known = tnum_is_const(dst_reg->var_off);
5917 s64 smin_val = src_reg->smin_value;
5918 u64 umin_val = src_reg->umin_value;
5919
5920 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07005921 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07005922 return;
5923 }
5924
5925 /* We get our maximum from the var_off, and our minimum is the
5926 * maximum of the operands' minima
5927 */
John Fastabend07cd2632020-03-24 10:38:15 -07005928 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5929 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5930 if (dst_reg->smin_value < 0 || smin_val < 0) {
5931 /* Lose signed bounds when ORing negative numbers,
5932 * ain't nobody got time for that.
5933 */
5934 dst_reg->smin_value = S64_MIN;
5935 dst_reg->smax_value = S64_MAX;
5936 } else {
5937 /* ORing two positives gives a positive, so safe to
5938 * cast result into s64.
5939 */
5940 dst_reg->smin_value = dst_reg->umin_value;
5941 dst_reg->smax_value = dst_reg->umax_value;
5942 }
5943 /* We may learn something more from the var_off */
5944 __update_reg_bounds(dst_reg);
5945}
5946
Yonghong Song2921c902020-08-24 23:46:08 -07005947static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
5948 struct bpf_reg_state *src_reg)
5949{
5950 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5951 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5952 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5953 s32 smin_val = src_reg->s32_min_value;
5954
5955 /* Assuming scalar64_min_max_xor will be called so it is safe
5956 * to skip updating register for known case.
5957 */
5958 if (src_known && dst_known)
5959 return;
5960
5961 /* We get both minimum and maximum from the var32_off. */
5962 dst_reg->u32_min_value = var32_off.value;
5963 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5964
5965 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
5966 /* XORing two positive sign numbers gives a positive,
5967 * so safe to cast u32 result into s32.
5968 */
5969 dst_reg->s32_min_value = dst_reg->u32_min_value;
5970 dst_reg->s32_max_value = dst_reg->u32_max_value;
5971 } else {
5972 dst_reg->s32_min_value = S32_MIN;
5973 dst_reg->s32_max_value = S32_MAX;
5974 }
5975}
5976
5977static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
5978 struct bpf_reg_state *src_reg)
5979{
5980 bool src_known = tnum_is_const(src_reg->var_off);
5981 bool dst_known = tnum_is_const(dst_reg->var_off);
5982 s64 smin_val = src_reg->smin_value;
5983
5984 if (src_known && dst_known) {
5985 /* dst_reg->var_off.value has been updated earlier */
5986 __mark_reg_known(dst_reg, dst_reg->var_off.value);
5987 return;
5988 }
5989
5990 /* We get both minimum and maximum from the var_off. */
5991 dst_reg->umin_value = dst_reg->var_off.value;
5992 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5993
5994 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
5995 /* XORing two positive sign numbers gives a positive,
5996 * so safe to cast u64 result into s64.
5997 */
5998 dst_reg->smin_value = dst_reg->umin_value;
5999 dst_reg->smax_value = dst_reg->umax_value;
6000 } else {
6001 dst_reg->smin_value = S64_MIN;
6002 dst_reg->smax_value = S64_MAX;
6003 }
6004
6005 __update_reg_bounds(dst_reg);
6006}
6007
John Fastabend3f50f132020-03-30 14:36:39 -07006008static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6009 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07006010{
John Fastabend07cd2632020-03-24 10:38:15 -07006011 /* We lose all sign bit information (except what we can pick
6012 * up from var_off)
6013 */
John Fastabend3f50f132020-03-30 14:36:39 -07006014 dst_reg->s32_min_value = S32_MIN;
6015 dst_reg->s32_max_value = S32_MAX;
6016 /* If we might shift our top bit out, then we know nothing */
6017 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6018 dst_reg->u32_min_value = 0;
6019 dst_reg->u32_max_value = U32_MAX;
6020 } else {
6021 dst_reg->u32_min_value <<= umin_val;
6022 dst_reg->u32_max_value <<= umax_val;
6023 }
6024}
6025
6026static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6027 struct bpf_reg_state *src_reg)
6028{
6029 u32 umax_val = src_reg->u32_max_value;
6030 u32 umin_val = src_reg->u32_min_value;
6031 /* u32 alu operation will zext upper bits */
6032 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6033
6034 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6035 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6036 /* Not required but being careful mark reg64 bounds as unknown so
6037 * that we are forced to pick them up from tnum and zext later and
6038 * if some path skips this step we are still safe.
6039 */
6040 __mark_reg64_unbounded(dst_reg);
6041 __update_reg32_bounds(dst_reg);
6042}
6043
6044static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6045 u64 umin_val, u64 umax_val)
6046{
6047 /* Special case <<32 because it is a common compiler pattern to sign
6048 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6049 * positive we know this shift will also be positive so we can track
6050 * bounds correctly. Otherwise we lose all sign bit information except
6051 * what we can pick up from var_off. Perhaps we can generalize this
6052 * later to shifts of any length.
6053 */
6054 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6055 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6056 else
6057 dst_reg->smax_value = S64_MAX;
6058
6059 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6060 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6061 else
6062 dst_reg->smin_value = S64_MIN;
6063
John Fastabend07cd2632020-03-24 10:38:15 -07006064 /* If we might shift our top bit out, then we know nothing */
6065 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6066 dst_reg->umin_value = 0;
6067 dst_reg->umax_value = U64_MAX;
6068 } else {
6069 dst_reg->umin_value <<= umin_val;
6070 dst_reg->umax_value <<= umax_val;
6071 }
John Fastabend3f50f132020-03-30 14:36:39 -07006072}
6073
6074static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6075 struct bpf_reg_state *src_reg)
6076{
6077 u64 umax_val = src_reg->umax_value;
6078 u64 umin_val = src_reg->umin_value;
6079
6080 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6081 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6082 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6083
John Fastabend07cd2632020-03-24 10:38:15 -07006084 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6085 /* We may learn something more from the var_off */
6086 __update_reg_bounds(dst_reg);
6087}
6088
John Fastabend3f50f132020-03-30 14:36:39 -07006089static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6090 struct bpf_reg_state *src_reg)
6091{
6092 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6093 u32 umax_val = src_reg->u32_max_value;
6094 u32 umin_val = src_reg->u32_min_value;
6095
6096 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6097 * be negative, then either:
6098 * 1) src_reg might be zero, so the sign bit of the result is
6099 * unknown, so we lose our signed bounds
6100 * 2) it's known negative, thus the unsigned bounds capture the
6101 * signed bounds
6102 * 3) the signed bounds cross zero, so they tell us nothing
6103 * about the result
6104 * If the value in dst_reg is known nonnegative, then again the
6105 * unsigned bounts capture the signed bounds.
6106 * Thus, in all cases it suffices to blow away our signed bounds
6107 * and rely on inferring new ones from the unsigned bounds and
6108 * var_off of the result.
6109 */
6110 dst_reg->s32_min_value = S32_MIN;
6111 dst_reg->s32_max_value = S32_MAX;
6112
6113 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6114 dst_reg->u32_min_value >>= umax_val;
6115 dst_reg->u32_max_value >>= umin_val;
6116
6117 __mark_reg64_unbounded(dst_reg);
6118 __update_reg32_bounds(dst_reg);
6119}
6120
John Fastabend07cd2632020-03-24 10:38:15 -07006121static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6122 struct bpf_reg_state *src_reg)
6123{
6124 u64 umax_val = src_reg->umax_value;
6125 u64 umin_val = src_reg->umin_value;
6126
6127 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6128 * be negative, then either:
6129 * 1) src_reg might be zero, so the sign bit of the result is
6130 * unknown, so we lose our signed bounds
6131 * 2) it's known negative, thus the unsigned bounds capture the
6132 * signed bounds
6133 * 3) the signed bounds cross zero, so they tell us nothing
6134 * about the result
6135 * If the value in dst_reg is known nonnegative, then again the
6136 * unsigned bounts capture the signed bounds.
6137 * Thus, in all cases it suffices to blow away our signed bounds
6138 * and rely on inferring new ones from the unsigned bounds and
6139 * var_off of the result.
6140 */
6141 dst_reg->smin_value = S64_MIN;
6142 dst_reg->smax_value = S64_MAX;
6143 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6144 dst_reg->umin_value >>= umax_val;
6145 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006146
6147 /* Its not easy to operate on alu32 bounds here because it depends
6148 * on bits being shifted in. Take easy way out and mark unbounded
6149 * so we can recalculate later from tnum.
6150 */
6151 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006152 __update_reg_bounds(dst_reg);
6153}
6154
John Fastabend3f50f132020-03-30 14:36:39 -07006155static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6156 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006157{
John Fastabend3f50f132020-03-30 14:36:39 -07006158 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07006159
6160 /* Upon reaching here, src_known is true and
6161 * umax_val is equal to umin_val.
6162 */
John Fastabend3f50f132020-03-30 14:36:39 -07006163 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6164 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07006165
John Fastabend3f50f132020-03-30 14:36:39 -07006166 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6167
6168 /* blow away the dst_reg umin_value/umax_value and rely on
6169 * dst_reg var_off to refine the result.
6170 */
6171 dst_reg->u32_min_value = 0;
6172 dst_reg->u32_max_value = U32_MAX;
6173
6174 __mark_reg64_unbounded(dst_reg);
6175 __update_reg32_bounds(dst_reg);
6176}
6177
6178static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6179 struct bpf_reg_state *src_reg)
6180{
6181 u64 umin_val = src_reg->umin_value;
6182
6183 /* Upon reaching here, src_known is true and umax_val is equal
6184 * to umin_val.
6185 */
6186 dst_reg->smin_value >>= umin_val;
6187 dst_reg->smax_value >>= umin_val;
6188
6189 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07006190
6191 /* blow away the dst_reg umin_value/umax_value and rely on
6192 * dst_reg var_off to refine the result.
6193 */
6194 dst_reg->umin_value = 0;
6195 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07006196
6197 /* Its not easy to operate on alu32 bounds here because it depends
6198 * on bits being shifted in from upper 32-bits. Take easy way out
6199 * and mark unbounded so we can recalculate later from tnum.
6200 */
6201 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006202 __update_reg_bounds(dst_reg);
6203}
6204
Jann Horn468f6ea2017-12-18 20:11:56 -08006205/* WARNING: This function does calculations on 64-bit values, but the actual
6206 * execution may occur on 32-bit values. Therefore, things like bitshifts
6207 * need extra checks in the 32-bit case.
6208 */
Edward Creef1174f72017-08-07 15:26:19 +01006209static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6210 struct bpf_insn *insn,
6211 struct bpf_reg_state *dst_reg,
6212 struct bpf_reg_state src_reg)
6213{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006214 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01006215 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08006216 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01006217 s64 smin_val, smax_val;
6218 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006219 s32 s32_min_val, s32_max_val;
6220 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08006221 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006222 u32 dst = insn->dst_reg;
6223 int ret;
John Fastabend3f50f132020-03-30 14:36:39 -07006224 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Jann Hornb7992072018-10-05 18:17:59 +02006225
Edward Creeb03c9f92017-08-07 15:26:36 +01006226 smin_val = src_reg.smin_value;
6227 smax_val = src_reg.smax_value;
6228 umin_val = src_reg.umin_value;
6229 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01006230
John Fastabend3f50f132020-03-30 14:36:39 -07006231 s32_min_val = src_reg.s32_min_value;
6232 s32_max_val = src_reg.s32_max_value;
6233 u32_min_val = src_reg.u32_min_value;
6234 u32_max_val = src_reg.u32_max_value;
6235
6236 if (alu32) {
6237 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006238 if ((src_known &&
6239 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6240 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6241 /* Taint dst register if offset had invalid bounds
6242 * derived from e.g. dead branches.
6243 */
6244 __mark_reg_unknown(env, dst_reg);
6245 return 0;
6246 }
6247 } else {
6248 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006249 if ((src_known &&
6250 (smin_val != smax_val || umin_val != umax_val)) ||
6251 smin_val > smax_val || umin_val > umax_val) {
6252 /* Taint dst register if offset had invalid bounds
6253 * derived from e.g. dead branches.
6254 */
6255 __mark_reg_unknown(env, dst_reg);
6256 return 0;
6257 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01006258 }
6259
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006260 if (!src_known &&
6261 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006262 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006263 return 0;
6264 }
6265
John Fastabend3f50f132020-03-30 14:36:39 -07006266 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6267 * There are two classes of instructions: The first class we track both
6268 * alu32 and alu64 sign/unsigned bounds independently this provides the
6269 * greatest amount of precision when alu operations are mixed with jmp32
6270 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6271 * and BPF_OR. This is possible because these ops have fairly easy to
6272 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6273 * See alu32 verifier tests for examples. The second class of
6274 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6275 * with regards to tracking sign/unsigned bounds because the bits may
6276 * cross subreg boundaries in the alu64 case. When this happens we mark
6277 * the reg unbounded in the subreg bound space and use the resulting
6278 * tnum to calculate an approximation of the sign/unsigned bounds.
6279 */
Edward Creef1174f72017-08-07 15:26:19 +01006280 switch (opcode) {
6281 case BPF_ADD:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006282 ret = sanitize_val_alu(env, insn);
6283 if (ret < 0) {
6284 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6285 return ret;
6286 }
John Fastabend3f50f132020-03-30 14:36:39 -07006287 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006288 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006289 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01006290 break;
6291 case BPF_SUB:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006292 ret = sanitize_val_alu(env, insn);
6293 if (ret < 0) {
6294 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6295 return ret;
6296 }
John Fastabend3f50f132020-03-30 14:36:39 -07006297 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006298 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006299 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04006300 break;
6301 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07006302 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6303 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006304 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006305 break;
6306 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07006307 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6308 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006309 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006310 break;
6311 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07006312 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6313 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006314 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006315 break;
Yonghong Song2921c902020-08-24 23:46:08 -07006316 case BPF_XOR:
6317 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6318 scalar32_min_max_xor(dst_reg, &src_reg);
6319 scalar_min_max_xor(dst_reg, &src_reg);
6320 break;
Josef Bacik48461132016-09-28 10:54:32 -04006321 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006322 if (umax_val >= insn_bitness) {
6323 /* Shifts greater than 31 or 63 are undefined.
6324 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006325 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006326 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006327 break;
6328 }
John Fastabend3f50f132020-03-30 14:36:39 -07006329 if (alu32)
6330 scalar32_min_max_lsh(dst_reg, &src_reg);
6331 else
6332 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006333 break;
6334 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006335 if (umax_val >= insn_bitness) {
6336 /* Shifts greater than 31 or 63 are undefined.
6337 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006338 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006339 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006340 break;
6341 }
John Fastabend3f50f132020-03-30 14:36:39 -07006342 if (alu32)
6343 scalar32_min_max_rsh(dst_reg, &src_reg);
6344 else
6345 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006346 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006347 case BPF_ARSH:
6348 if (umax_val >= insn_bitness) {
6349 /* Shifts greater than 31 or 63 are undefined.
6350 * This includes shifts by a negative number.
6351 */
6352 mark_reg_unknown(env, regs, insn->dst_reg);
6353 break;
6354 }
John Fastabend3f50f132020-03-30 14:36:39 -07006355 if (alu32)
6356 scalar32_min_max_arsh(dst_reg, &src_reg);
6357 else
6358 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006359 break;
Josef Bacik48461132016-09-28 10:54:32 -04006360 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006361 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006362 break;
6363 }
6364
John Fastabend3f50f132020-03-30 14:36:39 -07006365 /* ALU32 ops are zero extended into 64bit register */
6366 if (alu32)
6367 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08006368
John Fastabend294f2fc2020-03-24 10:38:37 -07006369 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01006370 __reg_deduce_bounds(dst_reg);
6371 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006372 return 0;
6373}
6374
6375/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6376 * and var_off.
6377 */
6378static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6379 struct bpf_insn *insn)
6380{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006381 struct bpf_verifier_state *vstate = env->cur_state;
6382 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6383 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01006384 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6385 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006386 int err;
Edward Creef1174f72017-08-07 15:26:19 +01006387
6388 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01006389 src_reg = NULL;
6390 if (dst_reg->type != SCALAR_VALUE)
6391 ptr_reg = dst_reg;
6392 if (BPF_SRC(insn->code) == BPF_X) {
6393 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01006394 if (src_reg->type != SCALAR_VALUE) {
6395 if (dst_reg->type != SCALAR_VALUE) {
6396 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006397 * an arbitrary scalar. Disallow all math except
6398 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01006399 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07006400 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006401 mark_reg_unknown(env, regs, insn->dst_reg);
6402 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01006403 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006404 verbose(env, "R%d pointer %s pointer prohibited\n",
6405 insn->dst_reg,
6406 bpf_alu_string[opcode >> 4]);
6407 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01006408 } else {
6409 /* scalar += pointer
6410 * This is legal, but we have to reverse our
6411 * src/dest handling in computing the range
6412 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006413 err = mark_chain_precision(env, insn->dst_reg);
6414 if (err)
6415 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006416 return adjust_ptr_min_max_vals(env, insn,
6417 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006418 }
6419 } else if (ptr_reg) {
6420 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006421 err = mark_chain_precision(env, insn->src_reg);
6422 if (err)
6423 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006424 return adjust_ptr_min_max_vals(env, insn,
6425 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006426 }
6427 } else {
6428 /* Pretend the src is a reg with a known value, since we only
6429 * need to be able to read from this state.
6430 */
6431 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01006432 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01006433 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006434 if (ptr_reg) /* pointer += K */
6435 return adjust_ptr_min_max_vals(env, insn,
6436 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006437 }
6438
6439 /* Got here implies adding two SCALAR_VALUEs */
6440 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006441 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006442 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01006443 return -EINVAL;
6444 }
6445 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006446 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006447 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01006448 return -EINVAL;
6449 }
6450 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006451}
6452
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006453/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006454static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006455{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006456 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006457 u8 opcode = BPF_OP(insn->code);
6458 int err;
6459
6460 if (opcode == BPF_END || opcode == BPF_NEG) {
6461 if (opcode == BPF_NEG) {
6462 if (BPF_SRC(insn->code) != 0 ||
6463 insn->src_reg != BPF_REG_0 ||
6464 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006465 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006466 return -EINVAL;
6467 }
6468 } else {
6469 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01006470 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6471 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006472 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006473 return -EINVAL;
6474 }
6475 }
6476
6477 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01006478 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006479 if (err)
6480 return err;
6481
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006482 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006483 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006484 insn->dst_reg);
6485 return -EACCES;
6486 }
6487
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006488 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01006489 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006490 if (err)
6491 return err;
6492
6493 } else if (opcode == BPF_MOV) {
6494
6495 if (BPF_SRC(insn->code) == BPF_X) {
6496 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006497 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006498 return -EINVAL;
6499 }
6500
6501 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01006502 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006503 if (err)
6504 return err;
6505 } else {
6506 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006507 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006508 return -EINVAL;
6509 }
6510 }
6511
Arthur Fabrefbeb1602018-07-31 18:17:22 +01006512 /* check dest operand, mark as required later */
6513 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006514 if (err)
6515 return err;
6516
6517 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05006518 struct bpf_reg_state *src_reg = regs + insn->src_reg;
6519 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6520
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006521 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6522 /* case: R1 = R2
6523 * copy register state to dest reg
6524 */
Jiong Wange434b8c2018-12-07 12:16:18 -05006525 *dst_reg = *src_reg;
6526 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01006527 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006528 } else {
Edward Creef1174f72017-08-07 15:26:19 +01006529 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006530 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006531 verbose(env,
6532 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006533 insn->src_reg);
6534 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05006535 } else if (src_reg->type == SCALAR_VALUE) {
6536 *dst_reg = *src_reg;
6537 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01006538 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05006539 } else {
6540 mark_reg_unknown(env, regs,
6541 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006542 }
John Fastabend3f50f132020-03-30 14:36:39 -07006543 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006544 }
6545 } else {
6546 /* case: R = imm
6547 * remember the value we stored into this reg
6548 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01006549 /* clear any state __mark_reg_known doesn't set */
6550 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006551 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08006552 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6553 __mark_reg_known(regs + insn->dst_reg,
6554 insn->imm);
6555 } else {
6556 __mark_reg_known(regs + insn->dst_reg,
6557 (u32)insn->imm);
6558 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006559 }
6560
6561 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006562 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006563 return -EINVAL;
6564
6565 } else { /* all other ALU ops: and, sub, xor, add, ... */
6566
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006567 if (BPF_SRC(insn->code) == BPF_X) {
6568 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006569 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006570 return -EINVAL;
6571 }
6572 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006573 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006574 if (err)
6575 return err;
6576 } else {
6577 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006578 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006579 return -EINVAL;
6580 }
6581 }
6582
6583 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006584 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006585 if (err)
6586 return err;
6587
6588 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6589 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006590 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006591 return -EINVAL;
6592 }
6593
Rabin Vincent229394e82016-01-12 20:17:08 +01006594 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6595 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6596 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6597
6598 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006599 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01006600 return -EINVAL;
6601 }
6602 }
6603
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006604 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01006605 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006606 if (err)
6607 return err;
6608
Edward Creef1174f72017-08-07 15:26:19 +01006609 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006610 }
6611
6612 return 0;
6613}
6614
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006615static void __find_good_pkt_pointers(struct bpf_func_state *state,
6616 struct bpf_reg_state *dst_reg,
6617 enum bpf_reg_type type, u16 new_range)
6618{
6619 struct bpf_reg_state *reg;
6620 int i;
6621
6622 for (i = 0; i < MAX_BPF_REG; i++) {
6623 reg = &state->regs[i];
6624 if (reg->type == type && reg->id == dst_reg->id)
6625 /* keep the maximum range already checked */
6626 reg->range = max(reg->range, new_range);
6627 }
6628
6629 bpf_for_each_spilled_reg(i, state, reg) {
6630 if (!reg)
6631 continue;
6632 if (reg->type == type && reg->id == dst_reg->id)
6633 reg->range = max(reg->range, new_range);
6634 }
6635}
6636
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006637static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006638 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01006639 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006640 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006641{
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006642 u16 new_range;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006643 int i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006644
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006645 if (dst_reg->off < 0 ||
6646 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01006647 /* This doesn't give us any range */
6648 return;
6649
Edward Creeb03c9f92017-08-07 15:26:36 +01006650 if (dst_reg->umax_value > MAX_PACKET_OFF ||
6651 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01006652 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6653 * than pkt_end, but that's because it's also less than pkt.
6654 */
6655 return;
6656
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006657 new_range = dst_reg->off;
6658 if (range_right_open)
6659 new_range--;
6660
6661 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006662 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006663 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006664 *
6665 * r2 = r3;
6666 * r2 += 8;
6667 * if (r2 > pkt_end) goto <handle exception>
6668 * <access okay>
6669 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006670 * r2 = r3;
6671 * r2 += 8;
6672 * if (r2 < pkt_end) goto <access okay>
6673 * <handle exception>
6674 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006675 * Where:
6676 * r2 == dst_reg, pkt_end == src_reg
6677 * r2=pkt(id=n,off=8,r=0)
6678 * r3=pkt(id=n,off=0,r=0)
6679 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006680 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006681 *
6682 * r2 = r3;
6683 * r2 += 8;
6684 * if (pkt_end >= r2) goto <access okay>
6685 * <handle exception>
6686 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006687 * r2 = r3;
6688 * r2 += 8;
6689 * if (pkt_end <= r2) goto <handle exception>
6690 * <access okay>
6691 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006692 * Where:
6693 * pkt_end == dst_reg, r2 == src_reg
6694 * r2=pkt(id=n,off=8,r=0)
6695 * r3=pkt(id=n,off=0,r=0)
6696 *
6697 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006698 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6699 * and [r3, r3 + 8-1) respectively is safe to access depending on
6700 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006701 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006702
Edward Creef1174f72017-08-07 15:26:19 +01006703 /* If our ids match, then we must have the same max_value. And we
6704 * don't care about the other reg's fixed offset, since if it's too big
6705 * the range won't allow anything.
6706 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6707 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006708 for (i = 0; i <= vstate->curframe; i++)
6709 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6710 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006711}
6712
John Fastabend3f50f132020-03-30 14:36:39 -07006713static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006714{
John Fastabend3f50f132020-03-30 14:36:39 -07006715 struct tnum subreg = tnum_subreg(reg->var_off);
6716 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006717
John Fastabend3f50f132020-03-30 14:36:39 -07006718 switch (opcode) {
6719 case BPF_JEQ:
6720 if (tnum_is_const(subreg))
6721 return !!tnum_equals_const(subreg, val);
6722 break;
6723 case BPF_JNE:
6724 if (tnum_is_const(subreg))
6725 return !tnum_equals_const(subreg, val);
6726 break;
6727 case BPF_JSET:
6728 if ((~subreg.mask & subreg.value) & val)
6729 return 1;
6730 if (!((subreg.mask | subreg.value) & val))
6731 return 0;
6732 break;
6733 case BPF_JGT:
6734 if (reg->u32_min_value > val)
6735 return 1;
6736 else if (reg->u32_max_value <= val)
6737 return 0;
6738 break;
6739 case BPF_JSGT:
6740 if (reg->s32_min_value > sval)
6741 return 1;
6742 else if (reg->s32_max_value < sval)
6743 return 0;
6744 break;
6745 case BPF_JLT:
6746 if (reg->u32_max_value < val)
6747 return 1;
6748 else if (reg->u32_min_value >= val)
6749 return 0;
6750 break;
6751 case BPF_JSLT:
6752 if (reg->s32_max_value < sval)
6753 return 1;
6754 else if (reg->s32_min_value >= sval)
6755 return 0;
6756 break;
6757 case BPF_JGE:
6758 if (reg->u32_min_value >= val)
6759 return 1;
6760 else if (reg->u32_max_value < val)
6761 return 0;
6762 break;
6763 case BPF_JSGE:
6764 if (reg->s32_min_value >= sval)
6765 return 1;
6766 else if (reg->s32_max_value < sval)
6767 return 0;
6768 break;
6769 case BPF_JLE:
6770 if (reg->u32_max_value <= val)
6771 return 1;
6772 else if (reg->u32_min_value > val)
6773 return 0;
6774 break;
6775 case BPF_JSLE:
6776 if (reg->s32_max_value <= sval)
6777 return 1;
6778 else if (reg->s32_min_value > sval)
6779 return 0;
6780 break;
Jiong Wang092ed092019-01-26 12:26:01 -05006781 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05006782
John Fastabend3f50f132020-03-30 14:36:39 -07006783 return -1;
6784}
6785
6786
6787static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6788{
6789 s64 sval = (s64)val;
6790
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006791 switch (opcode) {
6792 case BPF_JEQ:
6793 if (tnum_is_const(reg->var_off))
6794 return !!tnum_equals_const(reg->var_off, val);
6795 break;
6796 case BPF_JNE:
6797 if (tnum_is_const(reg->var_off))
6798 return !tnum_equals_const(reg->var_off, val);
6799 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08006800 case BPF_JSET:
6801 if ((~reg->var_off.mask & reg->var_off.value) & val)
6802 return 1;
6803 if (!((reg->var_off.mask | reg->var_off.value) & val))
6804 return 0;
6805 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006806 case BPF_JGT:
6807 if (reg->umin_value > val)
6808 return 1;
6809 else if (reg->umax_value <= val)
6810 return 0;
6811 break;
6812 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006813 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006814 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006815 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006816 return 0;
6817 break;
6818 case BPF_JLT:
6819 if (reg->umax_value < val)
6820 return 1;
6821 else if (reg->umin_value >= val)
6822 return 0;
6823 break;
6824 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006825 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006826 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006827 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006828 return 0;
6829 break;
6830 case BPF_JGE:
6831 if (reg->umin_value >= val)
6832 return 1;
6833 else if (reg->umax_value < val)
6834 return 0;
6835 break;
6836 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006837 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006838 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006839 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006840 return 0;
6841 break;
6842 case BPF_JLE:
6843 if (reg->umax_value <= val)
6844 return 1;
6845 else if (reg->umin_value > val)
6846 return 0;
6847 break;
6848 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006849 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006850 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006851 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006852 return 0;
6853 break;
6854 }
6855
6856 return -1;
6857}
6858
John Fastabend3f50f132020-03-30 14:36:39 -07006859/* compute branch direction of the expression "if (reg opcode val) goto target;"
6860 * and return:
6861 * 1 - branch will be taken and "goto target" will be executed
6862 * 0 - branch will not be taken and fall-through to next insn
6863 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6864 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05006865 */
John Fastabend3f50f132020-03-30 14:36:39 -07006866static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6867 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05006868{
John Fastabendcac616d2020-05-21 13:07:26 -07006869 if (__is_pointer_value(false, reg)) {
6870 if (!reg_type_not_null(reg->type))
6871 return -1;
6872
6873 /* If pointer is valid tests against zero will fail so we can
6874 * use this to direct branch taken.
6875 */
6876 if (val != 0)
6877 return -1;
6878
6879 switch (opcode) {
6880 case BPF_JEQ:
6881 return 0;
6882 case BPF_JNE:
6883 return 1;
6884 default:
6885 return -1;
6886 }
6887 }
Jiong Wang092ed092019-01-26 12:26:01 -05006888
John Fastabend3f50f132020-03-30 14:36:39 -07006889 if (is_jmp32)
6890 return is_branch32_taken(reg, val, opcode);
6891 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02006892}
6893
Josef Bacik48461132016-09-28 10:54:32 -04006894/* Adjusts the register min/max values in the case that the dst_reg is the
6895 * variable register that we are working on, and src_reg is a constant or we're
6896 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01006897 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04006898 */
6899static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07006900 struct bpf_reg_state *false_reg,
6901 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05006902 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04006903{
John Fastabend3f50f132020-03-30 14:36:39 -07006904 struct tnum false_32off = tnum_subreg(false_reg->var_off);
6905 struct tnum false_64off = false_reg->var_off;
6906 struct tnum true_32off = tnum_subreg(true_reg->var_off);
6907 struct tnum true_64off = true_reg->var_off;
6908 s64 sval = (s64)val;
6909 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006910
Edward Creef1174f72017-08-07 15:26:19 +01006911 /* If the dst_reg is a pointer, we can't learn anything about its
6912 * variable offset from the compare (unless src_reg were a pointer into
6913 * the same object, but we don't bother with that.
6914 * Since false_reg and true_reg have the same type by construction, we
6915 * only need to check one of them for pointerness.
6916 */
6917 if (__is_pointer_value(false, false_reg))
6918 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02006919
Josef Bacik48461132016-09-28 10:54:32 -04006920 switch (opcode) {
6921 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04006922 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006923 {
6924 struct bpf_reg_state *reg =
6925 opcode == BPF_JEQ ? true_reg : false_reg;
6926
6927 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6928 * if it is true we know the value for sure. Likewise for
6929 * BPF_JNE.
Josef Bacik48461132016-09-28 10:54:32 -04006930 */
John Fastabend3f50f132020-03-30 14:36:39 -07006931 if (is_jmp32)
6932 __mark_reg32_known(reg, val32);
6933 else
Jiong Wang092ed092019-01-26 12:26:01 -05006934 __mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04006935 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006936 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08006937 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07006938 if (is_jmp32) {
6939 false_32off = tnum_and(false_32off, tnum_const(~val32));
6940 if (is_power_of_2(val32))
6941 true_32off = tnum_or(true_32off,
6942 tnum_const(val32));
6943 } else {
6944 false_64off = tnum_and(false_64off, tnum_const(~val));
6945 if (is_power_of_2(val))
6946 true_64off = tnum_or(true_64off,
6947 tnum_const(val));
6948 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08006949 break;
Josef Bacik48461132016-09-28 10:54:32 -04006950 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006951 case BPF_JGT:
6952 {
John Fastabend3f50f132020-03-30 14:36:39 -07006953 if (is_jmp32) {
6954 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
6955 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
6956
6957 false_reg->u32_max_value = min(false_reg->u32_max_value,
6958 false_umax);
6959 true_reg->u32_min_value = max(true_reg->u32_min_value,
6960 true_umin);
6961 } else {
6962 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
6963 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
6964
6965 false_reg->umax_value = min(false_reg->umax_value, false_umax);
6966 true_reg->umin_value = max(true_reg->umin_value, true_umin);
6967 }
Edward Creeb03c9f92017-08-07 15:26:36 +01006968 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006969 }
Josef Bacik48461132016-09-28 10:54:32 -04006970 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006971 case BPF_JSGT:
6972 {
John Fastabend3f50f132020-03-30 14:36:39 -07006973 if (is_jmp32) {
6974 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
6975 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006976
John Fastabend3f50f132020-03-30 14:36:39 -07006977 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
6978 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
6979 } else {
6980 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
6981 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
6982
6983 false_reg->smax_value = min(false_reg->smax_value, false_smax);
6984 true_reg->smin_value = max(true_reg->smin_value, true_smin);
6985 }
Josef Bacik48461132016-09-28 10:54:32 -04006986 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006987 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006988 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006989 case BPF_JLT:
6990 {
John Fastabend3f50f132020-03-30 14:36:39 -07006991 if (is_jmp32) {
6992 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
6993 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
6994
6995 false_reg->u32_min_value = max(false_reg->u32_min_value,
6996 false_umin);
6997 true_reg->u32_max_value = min(true_reg->u32_max_value,
6998 true_umax);
6999 } else {
7000 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7001 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7002
7003 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7004 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7005 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007006 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007007 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007008 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007009 case BPF_JSLT:
7010 {
John Fastabend3f50f132020-03-30 14:36:39 -07007011 if (is_jmp32) {
7012 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7013 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007014
John Fastabend3f50f132020-03-30 14:36:39 -07007015 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7016 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7017 } else {
7018 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7019 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7020
7021 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7022 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7023 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007024 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007025 }
Josef Bacik48461132016-09-28 10:54:32 -04007026 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02007027 return;
Josef Bacik48461132016-09-28 10:54:32 -04007028 }
7029
John Fastabend3f50f132020-03-30 14:36:39 -07007030 if (is_jmp32) {
7031 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7032 tnum_subreg(false_32off));
7033 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7034 tnum_subreg(true_32off));
7035 __reg_combine_32_into_64(false_reg);
7036 __reg_combine_32_into_64(true_reg);
7037 } else {
7038 false_reg->var_off = false_64off;
7039 true_reg->var_off = true_64off;
7040 __reg_combine_64_into_32(false_reg);
7041 __reg_combine_64_into_32(true_reg);
7042 }
Josef Bacik48461132016-09-28 10:54:32 -04007043}
7044
Edward Creef1174f72017-08-07 15:26:19 +01007045/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7046 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04007047 */
7048static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007049 struct bpf_reg_state *false_reg,
7050 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05007051 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04007052{
Jann Horn0fc31b12020-03-30 18:03:24 +02007053 /* How can we transform "a <op> b" into "b <op> a"? */
7054 static const u8 opcode_flip[16] = {
7055 /* these stay the same */
7056 [BPF_JEQ >> 4] = BPF_JEQ,
7057 [BPF_JNE >> 4] = BPF_JNE,
7058 [BPF_JSET >> 4] = BPF_JSET,
7059 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7060 [BPF_JGE >> 4] = BPF_JLE,
7061 [BPF_JGT >> 4] = BPF_JLT,
7062 [BPF_JLE >> 4] = BPF_JGE,
7063 [BPF_JLT >> 4] = BPF_JGT,
7064 [BPF_JSGE >> 4] = BPF_JSLE,
7065 [BPF_JSGT >> 4] = BPF_JSLT,
7066 [BPF_JSLE >> 4] = BPF_JSGE,
7067 [BPF_JSLT >> 4] = BPF_JSGT
7068 };
7069 opcode = opcode_flip[opcode >> 4];
7070 /* This uses zero as "not present in table"; luckily the zero opcode,
7071 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01007072 */
Jann Horn0fc31b12020-03-30 18:03:24 +02007073 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07007074 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01007075}
7076
7077/* Regs are known to be equal, so intersect their min/max/var_off */
7078static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7079 struct bpf_reg_state *dst_reg)
7080{
Edward Creeb03c9f92017-08-07 15:26:36 +01007081 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7082 dst_reg->umin_value);
7083 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7084 dst_reg->umax_value);
7085 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7086 dst_reg->smin_value);
7087 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7088 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01007089 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7090 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01007091 /* We might have learned new bounds from the var_off. */
7092 __update_reg_bounds(src_reg);
7093 __update_reg_bounds(dst_reg);
7094 /* We might have learned something about the sign bit. */
7095 __reg_deduce_bounds(src_reg);
7096 __reg_deduce_bounds(dst_reg);
7097 /* We might have learned some bits from the bounds. */
7098 __reg_bound_offset(src_reg);
7099 __reg_bound_offset(dst_reg);
7100 /* Intersecting with the old var_off might have improved our bounds
7101 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7102 * then new var_off is (0; 0x7f...fc) which improves our umax.
7103 */
7104 __update_reg_bounds(src_reg);
7105 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007106}
7107
7108static void reg_combine_min_max(struct bpf_reg_state *true_src,
7109 struct bpf_reg_state *true_dst,
7110 struct bpf_reg_state *false_src,
7111 struct bpf_reg_state *false_dst,
7112 u8 opcode)
7113{
7114 switch (opcode) {
7115 case BPF_JEQ:
7116 __reg_combine_min_max(true_src, true_dst);
7117 break;
7118 case BPF_JNE:
7119 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01007120 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007121 }
Josef Bacik48461132016-09-28 10:54:32 -04007122}
7123
Joe Stringerfd978bf72018-10-02 13:35:35 -07007124static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7125 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07007126 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007127{
Joe Stringer840b9612018-10-02 13:35:32 -07007128 if (reg_type_may_be_null(reg->type) && reg->id == id) {
Edward Creef1174f72017-08-07 15:26:19 +01007129 /* Old offset (both fixed and variable parts) should
7130 * have been known-zero, because we don't allow pointer
7131 * arithmetic on pointers that might be NULL.
7132 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007133 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7134 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01007135 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01007136 __mark_reg_known_zero(reg);
7137 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007138 }
7139 if (is_null) {
7140 reg->type = SCALAR_VALUE;
Joe Stringer840b9612018-10-02 13:35:32 -07007141 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007142 const struct bpf_map *map = reg->map_ptr;
7143
7144 if (map->inner_map_meta) {
Joe Stringer840b9612018-10-02 13:35:32 -07007145 reg->type = CONST_PTR_TO_MAP;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007146 reg->map_ptr = map->inner_map_meta;
7147 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07007148 reg->type = PTR_TO_XDP_SOCK;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007149 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7150 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7151 reg->type = PTR_TO_SOCKET;
Joe Stringer840b9612018-10-02 13:35:32 -07007152 } else {
7153 reg->type = PTR_TO_MAP_VALUE;
7154 }
Joe Stringerc64b7982018-10-02 13:35:33 -07007155 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7156 reg->type = PTR_TO_SOCKET;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08007157 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7158 reg->type = PTR_TO_SOCK_COMMON;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08007159 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7160 reg->type = PTR_TO_TCP_SOCK;
Yonghong Songb121b342020-05-09 10:59:12 -07007161 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7162 reg->type = PTR_TO_BTF_ID;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07007163 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7164 reg->type = PTR_TO_MEM;
Yonghong Songafbf21d2020-07-23 11:41:11 -07007165 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7166 reg->type = PTR_TO_RDONLY_BUF;
7167 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7168 reg->type = PTR_TO_RDWR_BUF;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07007169 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007170 if (is_null) {
7171 /* We don't need id and ref_obj_id from this point
7172 * onwards anymore, thus we should better reset it,
7173 * so that state pruning has chances to take effect.
7174 */
7175 reg->id = 0;
7176 reg->ref_obj_id = 0;
7177 } else if (!reg_may_point_to_spin_lock(reg)) {
7178 /* For not-NULL ptr, reg->ref_obj_id will be reset
7179 * in release_reg_references().
7180 *
7181 * reg->id is still used by spin_lock ptr. Other
7182 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07007183 */
7184 reg->id = 0;
7185 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02007186 }
7187}
7188
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007189static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7190 bool is_null)
7191{
7192 struct bpf_reg_state *reg;
7193 int i;
7194
7195 for (i = 0; i < MAX_BPF_REG; i++)
7196 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7197
7198 bpf_for_each_spilled_reg(i, state, reg) {
7199 if (!reg)
7200 continue;
7201 mark_ptr_or_null_reg(state, reg, id, is_null);
7202 }
7203}
7204
Thomas Graf57a09bf2016-10-18 19:51:19 +02007205/* The logic is similar to find_good_pkt_pointers(), both could eventually
7206 * be folded together at some point.
7207 */
Joe Stringer840b9612018-10-02 13:35:32 -07007208static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7209 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007210{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007211 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007212 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007213 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01007214 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007215 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02007216
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007217 if (ref_obj_id && ref_obj_id == id && is_null)
7218 /* regs[regno] is in the " == NULL" branch.
7219 * No one could have freed the reference state before
7220 * doing the NULL check.
7221 */
7222 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07007223
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007224 for (i = 0; i <= vstate->curframe; i++)
7225 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02007226}
7227
Daniel Borkmann5beca082017-11-01 23:58:10 +01007228static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7229 struct bpf_reg_state *dst_reg,
7230 struct bpf_reg_state *src_reg,
7231 struct bpf_verifier_state *this_branch,
7232 struct bpf_verifier_state *other_branch)
7233{
7234 if (BPF_SRC(insn->code) != BPF_X)
7235 return false;
7236
Jiong Wang092ed092019-01-26 12:26:01 -05007237 /* Pointers are always 64-bit. */
7238 if (BPF_CLASS(insn->code) == BPF_JMP32)
7239 return false;
7240
Daniel Borkmann5beca082017-11-01 23:58:10 +01007241 switch (BPF_OP(insn->code)) {
7242 case BPF_JGT:
7243 if ((dst_reg->type == PTR_TO_PACKET &&
7244 src_reg->type == PTR_TO_PACKET_END) ||
7245 (dst_reg->type == PTR_TO_PACKET_META &&
7246 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7247 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7248 find_good_pkt_pointers(this_branch, dst_reg,
7249 dst_reg->type, false);
7250 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7251 src_reg->type == PTR_TO_PACKET) ||
7252 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7253 src_reg->type == PTR_TO_PACKET_META)) {
7254 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7255 find_good_pkt_pointers(other_branch, src_reg,
7256 src_reg->type, true);
7257 } else {
7258 return false;
7259 }
7260 break;
7261 case BPF_JLT:
7262 if ((dst_reg->type == PTR_TO_PACKET &&
7263 src_reg->type == PTR_TO_PACKET_END) ||
7264 (dst_reg->type == PTR_TO_PACKET_META &&
7265 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7266 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7267 find_good_pkt_pointers(other_branch, dst_reg,
7268 dst_reg->type, true);
7269 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7270 src_reg->type == PTR_TO_PACKET) ||
7271 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7272 src_reg->type == PTR_TO_PACKET_META)) {
7273 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7274 find_good_pkt_pointers(this_branch, src_reg,
7275 src_reg->type, false);
7276 } else {
7277 return false;
7278 }
7279 break;
7280 case BPF_JGE:
7281 if ((dst_reg->type == PTR_TO_PACKET &&
7282 src_reg->type == PTR_TO_PACKET_END) ||
7283 (dst_reg->type == PTR_TO_PACKET_META &&
7284 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7285 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7286 find_good_pkt_pointers(this_branch, dst_reg,
7287 dst_reg->type, true);
7288 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7289 src_reg->type == PTR_TO_PACKET) ||
7290 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7291 src_reg->type == PTR_TO_PACKET_META)) {
7292 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7293 find_good_pkt_pointers(other_branch, src_reg,
7294 src_reg->type, false);
7295 } else {
7296 return false;
7297 }
7298 break;
7299 case BPF_JLE:
7300 if ((dst_reg->type == PTR_TO_PACKET &&
7301 src_reg->type == PTR_TO_PACKET_END) ||
7302 (dst_reg->type == PTR_TO_PACKET_META &&
7303 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7304 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7305 find_good_pkt_pointers(other_branch, dst_reg,
7306 dst_reg->type, false);
7307 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7308 src_reg->type == PTR_TO_PACKET) ||
7309 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7310 src_reg->type == PTR_TO_PACKET_META)) {
7311 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7312 find_good_pkt_pointers(this_branch, src_reg,
7313 src_reg->type, true);
7314 } else {
7315 return false;
7316 }
7317 break;
7318 default:
7319 return false;
7320 }
7321
7322 return true;
7323}
7324
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007325static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007326 struct bpf_insn *insn, int *insn_idx)
7327{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007328 struct bpf_verifier_state *this_branch = env->cur_state;
7329 struct bpf_verifier_state *other_branch;
7330 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007331 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007332 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05007333 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007334 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007335 int err;
7336
Jiong Wang092ed092019-01-26 12:26:01 -05007337 /* Only conditional jumps are expected to reach here. */
7338 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7339 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007340 return -EINVAL;
7341 }
7342
7343 if (BPF_SRC(insn->code) == BPF_X) {
7344 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05007345 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007346 return -EINVAL;
7347 }
7348
7349 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007350 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007351 if (err)
7352 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007353
7354 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007355 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007356 insn->src_reg);
7357 return -EACCES;
7358 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007359 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007360 } else {
7361 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05007362 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007363 return -EINVAL;
7364 }
7365 }
7366
7367 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007368 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007369 if (err)
7370 return err;
7371
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007372 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05007373 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007374
John Fastabend3f50f132020-03-30 14:36:39 -07007375 if (BPF_SRC(insn->code) == BPF_K) {
7376 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7377 } else if (src_reg->type == SCALAR_VALUE &&
7378 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7379 pred = is_branch_taken(dst_reg,
7380 tnum_subreg(src_reg->var_off).value,
7381 opcode,
7382 is_jmp32);
7383 } else if (src_reg->type == SCALAR_VALUE &&
7384 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7385 pred = is_branch_taken(dst_reg,
7386 src_reg->var_off.value,
7387 opcode,
7388 is_jmp32);
7389 }
7390
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007391 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07007392 /* If we get here with a dst_reg pointer type it is because
7393 * above is_branch_taken() special cased the 0 comparison.
7394 */
7395 if (!__is_pointer_value(false, dst_reg))
7396 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007397 if (BPF_SRC(insn->code) == BPF_X && !err)
7398 err = mark_chain_precision(env, insn->src_reg);
7399 if (err)
7400 return err;
7401 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007402 if (pred == 1) {
7403 /* only follow the goto, ignore fall-through */
7404 *insn_idx += insn->off;
7405 return 0;
7406 } else if (pred == 0) {
7407 /* only follow fall-through branch, since
7408 * that's where the program will go
7409 */
7410 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007411 }
7412
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007413 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
7414 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007415 if (!other_branch)
7416 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007417 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007418
Josef Bacik48461132016-09-28 10:54:32 -04007419 /* detect if we are comparing against a constant value so we can adjust
7420 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01007421 * this is only legit if both are scalars (or pointers to the same
7422 * object, I suppose, but we don't support that right now), because
7423 * otherwise the different base pointers mean the offsets aren't
7424 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04007425 */
7426 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05007427 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05007428
Edward Creef1174f72017-08-07 15:26:19 +01007429 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05007430 src_reg->type == SCALAR_VALUE) {
7431 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07007432 (is_jmp32 &&
7433 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007434 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007435 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007436 src_reg->var_off.value,
7437 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05007438 opcode, is_jmp32);
7439 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07007440 (is_jmp32 &&
7441 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007442 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007443 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007444 dst_reg->var_off.value,
7445 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05007446 opcode, is_jmp32);
7447 else if (!is_jmp32 &&
7448 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01007449 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007450 reg_combine_min_max(&other_branch_regs[insn->src_reg],
7451 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007452 src_reg, dst_reg, opcode);
Edward Creef1174f72017-08-07 15:26:19 +01007453 }
7454 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007455 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07007456 dst_reg, insn->imm, (u32)insn->imm,
7457 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04007458 }
7459
Jiong Wang092ed092019-01-26 12:26:01 -05007460 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7461 * NOTE: these optimizations below are related with pointer comparison
7462 * which will never be JMP32.
7463 */
7464 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007465 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07007466 reg_type_may_be_null(dst_reg->type)) {
7467 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02007468 * safe or unknown depending R == 0 or R != 0 conditional.
7469 */
Joe Stringer840b9612018-10-02 13:35:32 -07007470 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7471 opcode == BPF_JNE);
7472 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7473 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007474 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7475 this_branch, other_branch) &&
7476 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007477 verbose(env, "R%d pointer comparison prohibited\n",
7478 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007479 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007480 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007481 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007482 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007483 return 0;
7484}
7485
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007486/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007487static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007488{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007489 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007490 struct bpf_reg_state *regs = cur_regs(env);
Hao Luo4976b712020-09-29 16:50:44 -07007491 struct bpf_reg_state *dst_reg;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007492 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007493 int err;
7494
7495 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007496 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007497 return -EINVAL;
7498 }
7499 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007500 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007501 return -EINVAL;
7502 }
7503
Edward Creedc503a82017-08-15 20:34:35 +01007504 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007505 if (err)
7506 return err;
7507
Hao Luo4976b712020-09-29 16:50:44 -07007508 dst_reg = &regs[insn->dst_reg];
Jakub Kicinski6b173872016-09-21 11:43:59 +01007509 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01007510 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7511
Hao Luo4976b712020-09-29 16:50:44 -07007512 dst_reg->type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01007513 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007514 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01007515 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007516
Hao Luo4976b712020-09-29 16:50:44 -07007517 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
7518 mark_reg_known_zero(env, regs, insn->dst_reg);
7519
7520 dst_reg->type = aux->btf_var.reg_type;
7521 switch (dst_reg->type) {
7522 case PTR_TO_MEM:
7523 dst_reg->mem_size = aux->btf_var.mem_size;
7524 break;
7525 case PTR_TO_BTF_ID:
7526 dst_reg->btf_id = aux->btf_var.btf_id;
7527 break;
7528 default:
7529 verbose(env, "bpf verifier is misconfigured\n");
7530 return -EFAULT;
7531 }
7532 return 0;
7533 }
7534
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007535 map = env->used_maps[aux->map_index];
7536 mark_reg_known_zero(env, regs, insn->dst_reg);
Hao Luo4976b712020-09-29 16:50:44 -07007537 dst_reg->map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007538
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007539 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
Hao Luo4976b712020-09-29 16:50:44 -07007540 dst_reg->type = PTR_TO_MAP_VALUE;
7541 dst_reg->off = aux->map_off;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007542 if (map_value_has_spin_lock(map))
Hao Luo4976b712020-09-29 16:50:44 -07007543 dst_reg->id = ++env->id_gen;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007544 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
Hao Luo4976b712020-09-29 16:50:44 -07007545 dst_reg->type = CONST_PTR_TO_MAP;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007546 } else {
7547 verbose(env, "bpf verifier is misconfigured\n");
7548 return -EINVAL;
7549 }
7550
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007551 return 0;
7552}
7553
Daniel Borkmann96be4322015-03-01 12:31:46 +01007554static bool may_access_skb(enum bpf_prog_type type)
7555{
7556 switch (type) {
7557 case BPF_PROG_TYPE_SOCKET_FILTER:
7558 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01007559 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01007560 return true;
7561 default:
7562 return false;
7563 }
7564}
7565
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007566/* verify safety of LD_ABS|LD_IND instructions:
7567 * - they can only appear in the programs where ctx == skb
7568 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7569 * preserve R6-R9, and store return value into R0
7570 *
7571 * Implicit input:
7572 * ctx == skb == R6 == CTX
7573 *
7574 * Explicit input:
7575 * SRC == any register
7576 * IMM == 32-bit immediate
7577 *
7578 * Output:
7579 * R0 - 8/16/32-bit skb data converted to cpu endianness
7580 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007581static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007582{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007583 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007584 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007585 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007586 int i, err;
7587
Udip Pant7e407812020-08-25 16:20:00 -07007588 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007589 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007590 return -EINVAL;
7591 }
7592
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02007593 if (!env->ops->gen_ld_abs) {
7594 verbose(env, "bpf verifier is misconfigured\n");
7595 return -EINVAL;
7596 }
7597
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007598 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07007599 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007600 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007601 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007602 return -EINVAL;
7603 }
7604
7605 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007606 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007607 if (err)
7608 return err;
7609
Joe Stringerfd978bf72018-10-02 13:35:35 -07007610 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7611 * gen_ld_abs() may terminate the program at runtime, leading to
7612 * reference leak.
7613 */
7614 err = check_reference_leak(env);
7615 if (err) {
7616 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7617 return err;
7618 }
7619
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08007620 if (env->cur_state->active_spin_lock) {
7621 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7622 return -EINVAL;
7623 }
7624
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007625 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007626 verbose(env,
7627 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007628 return -EINVAL;
7629 }
7630
7631 if (mode == BPF_IND) {
7632 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01007633 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007634 if (err)
7635 return err;
7636 }
7637
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007638 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7639 if (err < 0)
7640 return err;
7641
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007642 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01007643 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007644 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01007645 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7646 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007647
7648 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01007649 * the value fetched from the packet.
7650 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007651 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007652 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01007653 /* ld_abs load up to 32-bit skb data. */
7654 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007655 return 0;
7656}
7657
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007658static int check_return_code(struct bpf_verifier_env *env)
7659{
brakmo5cf1e912019-05-28 16:59:36 -07007660 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007661 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007662 struct bpf_reg_state *reg;
7663 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07007664 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007665 int err;
7666
KP Singh9e4e01d2020-03-29 01:43:52 +01007667 /* LSM and struct_ops func-ptr's return type could be "void" */
Udip Pant7e407812020-08-25 16:20:00 -07007668 if ((prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7669 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007670 !prog->aux->attach_func_proto->type)
7671 return 0;
7672
7673 /* eBPF calling convetion is such that R0 is used
7674 * to return the value from eBPF program.
7675 * Make sure that it's readable at this time
7676 * of bpf_exit, which means that program wrote
7677 * something into it earlier
7678 */
7679 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7680 if (err)
7681 return err;
7682
7683 if (is_pointer_value(env, BPF_REG_0)) {
7684 verbose(env, "R0 leaks addr as return value\n");
7685 return -EACCES;
7686 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007687
Udip Pant7e407812020-08-25 16:20:00 -07007688 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02007689 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7690 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02007691 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7692 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7693 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7694 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7695 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02007696 range = tnum_range(1, 1);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05007697 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007698 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07007699 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7700 range = tnum_range(0, 3);
7701 enforce_attach_type_range = tnum_range(2, 3);
7702 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05007703 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007704 case BPF_PROG_TYPE_CGROUP_SOCK:
7705 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05007706 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08007707 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07007708 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007709 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07007710 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7711 if (!env->prog->aux->attach_btf_id)
7712 return 0;
7713 range = tnum_const(0);
7714 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07007715 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07007716 switch (env->prog->expected_attach_type) {
7717 case BPF_TRACE_FENTRY:
7718 case BPF_TRACE_FEXIT:
7719 range = tnum_const(0);
7720 break;
7721 case BPF_TRACE_RAW_TP:
7722 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07007723 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02007724 case BPF_TRACE_ITER:
7725 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07007726 default:
7727 return -ENOTSUPP;
7728 }
Yonghong Song15d83c42020-05-09 10:59:00 -07007729 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02007730 case BPF_PROG_TYPE_SK_LOOKUP:
7731 range = tnum_range(SK_DROP, SK_PASS);
7732 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07007733 case BPF_PROG_TYPE_EXT:
7734 /* freplace program can return anything as its return value
7735 * depends on the to-be-replaced kernel func or bpf program.
7736 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007737 default:
7738 return 0;
7739 }
7740
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007741 reg = cur_regs(env) + BPF_REG_0;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007742 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007743 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007744 reg_type_str[reg->type]);
7745 return -EINVAL;
7746 }
7747
7748 if (!tnum_in(range, reg->var_off)) {
brakmo5cf1e912019-05-28 16:59:36 -07007749 char tn_buf[48];
7750
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007751 verbose(env, "At program exit the register R0 ");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007752 if (!tnum_is_unknown(reg->var_off)) {
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007753 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007754 verbose(env, "has value %s", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007755 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007756 verbose(env, "has unknown scalar value");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007757 }
brakmo5cf1e912019-05-28 16:59:36 -07007758 tnum_strn(tn_buf, sizeof(tn_buf), range);
Daniel Borkmann983695f2019-06-07 01:48:57 +02007759 verbose(env, " should have been in %s\n", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007760 return -EINVAL;
7761 }
brakmo5cf1e912019-05-28 16:59:36 -07007762
7763 if (!tnum_is_unknown(enforce_attach_type_range) &&
7764 tnum_in(enforce_attach_type_range, reg->var_off))
7765 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007766 return 0;
7767}
7768
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007769/* non-recursive DFS pseudo code
7770 * 1 procedure DFS-iterative(G,v):
7771 * 2 label v as discovered
7772 * 3 let S be a stack
7773 * 4 S.push(v)
7774 * 5 while S is not empty
7775 * 6 t <- S.pop()
7776 * 7 if t is what we're looking for:
7777 * 8 return t
7778 * 9 for all edges e in G.adjacentEdges(t) do
7779 * 10 if edge e is already labelled
7780 * 11 continue with the next edge
7781 * 12 w <- G.adjacentVertex(t,e)
7782 * 13 if vertex w is not discovered and not explored
7783 * 14 label e as tree-edge
7784 * 15 label w as discovered
7785 * 16 S.push(w)
7786 * 17 continue at 5
7787 * 18 else if vertex w is discovered
7788 * 19 label e as back-edge
7789 * 20 else
7790 * 21 // vertex w is explored
7791 * 22 label e as forward- or cross-edge
7792 * 23 label t as explored
7793 * 24 S.pop()
7794 *
7795 * convention:
7796 * 0x10 - discovered
7797 * 0x11 - discovered and fall-through edge labelled
7798 * 0x12 - discovered and fall-through and branch edges labelled
7799 * 0x20 - explored
7800 */
7801
7802enum {
7803 DISCOVERED = 0x10,
7804 EXPLORED = 0x20,
7805 FALLTHROUGH = 1,
7806 BRANCH = 2,
7807};
7808
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007809static u32 state_htab_size(struct bpf_verifier_env *env)
7810{
7811 return env->prog->len;
7812}
7813
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007814static struct bpf_verifier_state_list **explored_state(
7815 struct bpf_verifier_env *env,
7816 int idx)
7817{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007818 struct bpf_verifier_state *cur = env->cur_state;
7819 struct bpf_func_state *state = cur->frame[cur->curframe];
7820
7821 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007822}
7823
7824static void init_explored_state(struct bpf_verifier_env *env, int idx)
7825{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007826 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007827}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007828
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007829/* t, w, e - match pseudo-code above:
7830 * t - index of current instruction
7831 * w - next instruction
7832 * e - edge
7833 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07007834static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7835 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007836{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007837 int *insn_stack = env->cfg.insn_stack;
7838 int *insn_state = env->cfg.insn_state;
7839
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007840 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7841 return 0;
7842
7843 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7844 return 0;
7845
7846 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08007847 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007848 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007849 return -EINVAL;
7850 }
7851
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007852 if (e == BRANCH)
7853 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007854 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007855
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007856 if (insn_state[w] == 0) {
7857 /* tree-edge */
7858 insn_state[t] = DISCOVERED | e;
7859 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007860 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007861 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007862 insn_stack[env->cfg.cur_stack++] = w;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007863 return 1;
7864 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07007865 if (loop_ok && env->bpf_capable)
Alexei Starovoitov25897262019-06-15 12:12:20 -07007866 return 0;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08007867 verbose_linfo(env, t, "%d: ", t);
7868 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007869 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007870 return -EINVAL;
7871 } else if (insn_state[w] == EXPLORED) {
7872 /* forward- or cross-edge */
7873 insn_state[t] = DISCOVERED | e;
7874 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007875 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007876 return -EFAULT;
7877 }
7878 return 0;
7879}
7880
7881/* non-recursive depth-first-search to detect loops in BPF program
7882 * loop == back-edge in directed graph
7883 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007884static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007885{
7886 struct bpf_insn *insns = env->prog->insnsi;
7887 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007888 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007889 int ret = 0;
7890 int i, t;
7891
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007892 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007893 if (!insn_state)
7894 return -ENOMEM;
7895
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007896 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007897 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07007898 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007899 return -ENOMEM;
7900 }
7901
7902 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
7903 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007904 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007905
7906peek_stack:
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007907 if (env->cfg.cur_stack == 0)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007908 goto check_state;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007909 t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007910
Jiong Wang092ed092019-01-26 12:26:01 -05007911 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
7912 BPF_CLASS(insns[t].code) == BPF_JMP32) {
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007913 u8 opcode = BPF_OP(insns[t].code);
7914
7915 if (opcode == BPF_EXIT) {
7916 goto mark_explored;
7917 } else if (opcode == BPF_CALL) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07007918 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007919 if (ret == 1)
7920 goto peek_stack;
7921 else if (ret < 0)
7922 goto err_free;
Daniel Borkmann07016152016-04-05 22:33:17 +02007923 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007924 init_explored_state(env, t + 1);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08007925 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007926 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07007927 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
7928 env, false);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08007929 if (ret == 1)
7930 goto peek_stack;
7931 else if (ret < 0)
7932 goto err_free;
7933 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007934 } else if (opcode == BPF_JA) {
7935 if (BPF_SRC(insns[t].code) != BPF_K) {
7936 ret = -EINVAL;
7937 goto err_free;
7938 }
7939 /* unconditional jump with single edge */
7940 ret = push_insn(t, t + insns[t].off + 1,
Alexei Starovoitov25897262019-06-15 12:12:20 -07007941 FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007942 if (ret == 1)
7943 goto peek_stack;
7944 else if (ret < 0)
7945 goto err_free;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007946 /* unconditional jmp is not a good pruning point,
7947 * but it's marked, since backtracking needs
7948 * to record jmp history in is_state_visited().
7949 */
7950 init_explored_state(env, t + insns[t].off + 1);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007951 /* tell verifier to check for equivalent states
7952 * after every call and jump
7953 */
Alexei Starovoitovc3de6312015-04-14 15:57:13 -07007954 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007955 init_explored_state(env, t + 1);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007956 } else {
7957 /* conditional jump with two edges */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007958 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07007959 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007960 if (ret == 1)
7961 goto peek_stack;
7962 else if (ret < 0)
7963 goto err_free;
7964
Alexei Starovoitov25897262019-06-15 12:12:20 -07007965 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007966 if (ret == 1)
7967 goto peek_stack;
7968 else if (ret < 0)
7969 goto err_free;
7970 }
7971 } else {
7972 /* all other non-branch instructions with single
7973 * fall-through edge
7974 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07007975 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007976 if (ret == 1)
7977 goto peek_stack;
7978 else if (ret < 0)
7979 goto err_free;
7980 }
7981
7982mark_explored:
7983 insn_state[t] = EXPLORED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007984 if (env->cfg.cur_stack-- <= 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007985 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007986 ret = -EFAULT;
7987 goto err_free;
7988 }
7989 goto peek_stack;
7990
7991check_state:
7992 for (i = 0; i < insn_cnt; i++) {
7993 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007994 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007995 ret = -EINVAL;
7996 goto err_free;
7997 }
7998 }
7999 ret = 0; /* cfg looks good */
8000
8001err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07008002 kvfree(insn_state);
8003 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008004 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008005 return ret;
8006}
8007
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008008static int check_abnormal_return(struct bpf_verifier_env *env)
8009{
8010 int i;
8011
8012 for (i = 1; i < env->subprog_cnt; i++) {
8013 if (env->subprog_info[i].has_ld_abs) {
8014 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8015 return -EINVAL;
8016 }
8017 if (env->subprog_info[i].has_tail_call) {
8018 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8019 return -EINVAL;
8020 }
8021 }
8022 return 0;
8023}
8024
Yonghong Song838e9692018-11-19 15:29:11 -08008025/* The minimum supported BTF func info size */
8026#define MIN_BPF_FUNCINFO_SIZE 8
8027#define MAX_FUNCINFO_REC_SIZE 252
8028
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008029static int check_btf_func(struct bpf_verifier_env *env,
8030 const union bpf_attr *attr,
8031 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08008032{
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008033 const struct btf_type *type, *func_proto, *ret_type;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08008034 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08008035 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008036 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008037 struct bpf_func_info_aux *info_aux = NULL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008038 struct bpf_prog *prog;
8039 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08008040 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08008041 u32 prev_offset = 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008042 bool scalar_return;
Dan Carpentere7ed83d2020-06-04 11:54:36 +03008043 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -08008044
8045 nfuncs = attr->func_info_cnt;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008046 if (!nfuncs) {
8047 if (check_abnormal_return(env))
8048 return -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08008049 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008050 }
Yonghong Song838e9692018-11-19 15:29:11 -08008051
8052 if (nfuncs != env->subprog_cnt) {
8053 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8054 return -EINVAL;
8055 }
8056
8057 urec_size = attr->func_info_rec_size;
8058 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8059 urec_size > MAX_FUNCINFO_REC_SIZE ||
8060 urec_size % sizeof(u32)) {
8061 verbose(env, "invalid func info rec size %u\n", urec_size);
8062 return -EINVAL;
8063 }
8064
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008065 prog = env->prog;
8066 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08008067
8068 urecord = u64_to_user_ptr(attr->func_info);
8069 min_size = min_t(u32, krec_size, urec_size);
8070
Yonghong Songba64e7d2018-11-24 23:20:44 -08008071 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008072 if (!krecord)
8073 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008074 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8075 if (!info_aux)
8076 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008077
Yonghong Song838e9692018-11-19 15:29:11 -08008078 for (i = 0; i < nfuncs; i++) {
8079 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8080 if (ret) {
8081 if (ret == -E2BIG) {
8082 verbose(env, "nonzero tailing record in func info");
8083 /* set the size kernel expects so loader can zero
8084 * out the rest of the record.
8085 */
8086 if (put_user(min_size, &uattr->func_info_rec_size))
8087 ret = -EFAULT;
8088 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008089 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008090 }
8091
Yonghong Songba64e7d2018-11-24 23:20:44 -08008092 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08008093 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008094 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008095 }
8096
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008097 /* check insn_off */
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008098 ret = -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08008099 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008100 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08008101 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008102 "nonzero insn_off %u for the first func info record",
8103 krecord[i].insn_off);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008104 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008105 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008106 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08008107 verbose(env,
8108 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008109 krecord[i].insn_off, prev_offset);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008110 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008111 }
8112
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008113 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08008114 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008115 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008116 }
8117
8118 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08008119 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008120 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08008121 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08008122 krecord[i].type_id);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008123 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008124 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008125 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008126
8127 func_proto = btf_type_by_id(btf, type->type);
8128 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8129 /* btf_func_check() already verified it during BTF load */
8130 goto err_free;
8131 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8132 scalar_return =
8133 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8134 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8135 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8136 goto err_free;
8137 }
8138 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8139 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8140 goto err_free;
8141 }
8142
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008143 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08008144 urecord += urec_size;
8145 }
8146
Yonghong Songba64e7d2018-11-24 23:20:44 -08008147 prog->aux->func_info = krecord;
8148 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008149 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08008150 return 0;
8151
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008152err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08008153 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008154 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08008155 return ret;
8156}
8157
Yonghong Songba64e7d2018-11-24 23:20:44 -08008158static void adjust_btf_func(struct bpf_verifier_env *env)
8159{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008160 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008161 int i;
8162
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008163 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08008164 return;
8165
8166 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008167 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008168}
8169
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008170#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8171 sizeof(((struct bpf_line_info *)(0))->line_col))
8172#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8173
8174static int check_btf_line(struct bpf_verifier_env *env,
8175 const union bpf_attr *attr,
8176 union bpf_attr __user *uattr)
8177{
8178 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8179 struct bpf_subprog_info *sub;
8180 struct bpf_line_info *linfo;
8181 struct bpf_prog *prog;
8182 const struct btf *btf;
8183 void __user *ulinfo;
8184 int err;
8185
8186 nr_linfo = attr->line_info_cnt;
8187 if (!nr_linfo)
8188 return 0;
8189
8190 rec_size = attr->line_info_rec_size;
8191 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8192 rec_size > MAX_LINEINFO_REC_SIZE ||
8193 rec_size & (sizeof(u32) - 1))
8194 return -EINVAL;
8195
8196 /* Need to zero it in case the userspace may
8197 * pass in a smaller bpf_line_info object.
8198 */
8199 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8200 GFP_KERNEL | __GFP_NOWARN);
8201 if (!linfo)
8202 return -ENOMEM;
8203
8204 prog = env->prog;
8205 btf = prog->aux->btf;
8206
8207 s = 0;
8208 sub = env->subprog_info;
8209 ulinfo = u64_to_user_ptr(attr->line_info);
8210 expected_size = sizeof(struct bpf_line_info);
8211 ncopy = min_t(u32, expected_size, rec_size);
8212 for (i = 0; i < nr_linfo; i++) {
8213 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8214 if (err) {
8215 if (err == -E2BIG) {
8216 verbose(env, "nonzero tailing record in line_info");
8217 if (put_user(expected_size,
8218 &uattr->line_info_rec_size))
8219 err = -EFAULT;
8220 }
8221 goto err_free;
8222 }
8223
8224 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8225 err = -EFAULT;
8226 goto err_free;
8227 }
8228
8229 /*
8230 * Check insn_off to ensure
8231 * 1) strictly increasing AND
8232 * 2) bounded by prog->len
8233 *
8234 * The linfo[0].insn_off == 0 check logically falls into
8235 * the later "missing bpf_line_info for func..." case
8236 * because the first linfo[0].insn_off must be the
8237 * first sub also and the first sub must have
8238 * subprog_info[0].start == 0.
8239 */
8240 if ((i && linfo[i].insn_off <= prev_offset) ||
8241 linfo[i].insn_off >= prog->len) {
8242 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8243 i, linfo[i].insn_off, prev_offset,
8244 prog->len);
8245 err = -EINVAL;
8246 goto err_free;
8247 }
8248
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08008249 if (!prog->insnsi[linfo[i].insn_off].code) {
8250 verbose(env,
8251 "Invalid insn code at line_info[%u].insn_off\n",
8252 i);
8253 err = -EINVAL;
8254 goto err_free;
8255 }
8256
Martin KaFai Lau23127b32018-12-13 10:41:46 -08008257 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8258 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008259 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8260 err = -EINVAL;
8261 goto err_free;
8262 }
8263
8264 if (s != env->subprog_cnt) {
8265 if (linfo[i].insn_off == sub[s].start) {
8266 sub[s].linfo_idx = i;
8267 s++;
8268 } else if (sub[s].start < linfo[i].insn_off) {
8269 verbose(env, "missing bpf_line_info for func#%u\n", s);
8270 err = -EINVAL;
8271 goto err_free;
8272 }
8273 }
8274
8275 prev_offset = linfo[i].insn_off;
8276 ulinfo += rec_size;
8277 }
8278
8279 if (s != env->subprog_cnt) {
8280 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8281 env->subprog_cnt - s, s);
8282 err = -EINVAL;
8283 goto err_free;
8284 }
8285
8286 prog->aux->linfo = linfo;
8287 prog->aux->nr_linfo = nr_linfo;
8288
8289 return 0;
8290
8291err_free:
8292 kvfree(linfo);
8293 return err;
8294}
8295
8296static int check_btf_info(struct bpf_verifier_env *env,
8297 const union bpf_attr *attr,
8298 union bpf_attr __user *uattr)
8299{
8300 struct btf *btf;
8301 int err;
8302
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008303 if (!attr->func_info_cnt && !attr->line_info_cnt) {
8304 if (check_abnormal_return(env))
8305 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008306 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008307 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008308
8309 btf = btf_get_by_fd(attr->prog_btf_fd);
8310 if (IS_ERR(btf))
8311 return PTR_ERR(btf);
8312 env->prog->aux->btf = btf;
8313
8314 err = check_btf_func(env, attr, uattr);
8315 if (err)
8316 return err;
8317
8318 err = check_btf_line(env, attr, uattr);
8319 if (err)
8320 return err;
8321
8322 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008323}
8324
Edward Creef1174f72017-08-07 15:26:19 +01008325/* check %cur's range satisfies %old's */
8326static bool range_within(struct bpf_reg_state *old,
8327 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008328{
Edward Creeb03c9f92017-08-07 15:26:36 +01008329 return old->umin_value <= cur->umin_value &&
8330 old->umax_value >= cur->umax_value &&
8331 old->smin_value <= cur->smin_value &&
8332 old->smax_value >= cur->smax_value;
Edward Creef1174f72017-08-07 15:26:19 +01008333}
8334
8335/* Maximum number of register states that can exist at once */
8336#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8337struct idpair {
8338 u32 old;
8339 u32 cur;
8340};
8341
8342/* If in the old state two registers had the same id, then they need to have
8343 * the same id in the new state as well. But that id could be different from
8344 * the old state, so we need to track the mapping from old to new ids.
8345 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8346 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8347 * regs with a different old id could still have new id 9, we don't care about
8348 * that.
8349 * So we look through our idmap to see if this old id has been seen before. If
8350 * so, we require the new id to match; otherwise, we add the id pair to the map.
8351 */
8352static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
8353{
8354 unsigned int i;
8355
8356 for (i = 0; i < ID_MAP_SIZE; i++) {
8357 if (!idmap[i].old) {
8358 /* Reached an empty slot; haven't seen this id before */
8359 idmap[i].old = old_id;
8360 idmap[i].cur = cur_id;
8361 return true;
8362 }
8363 if (idmap[i].old == old_id)
8364 return idmap[i].cur == cur_id;
8365 }
8366 /* We ran out of idmap slots, which should be impossible */
8367 WARN_ON_ONCE(1);
8368 return false;
8369}
8370
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008371static void clean_func_state(struct bpf_verifier_env *env,
8372 struct bpf_func_state *st)
8373{
8374 enum bpf_reg_liveness live;
8375 int i, j;
8376
8377 for (i = 0; i < BPF_REG_FP; i++) {
8378 live = st->regs[i].live;
8379 /* liveness must not touch this register anymore */
8380 st->regs[i].live |= REG_LIVE_DONE;
8381 if (!(live & REG_LIVE_READ))
8382 /* since the register is unused, clear its state
8383 * to make further comparison simpler
8384 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01008385 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008386 }
8387
8388 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
8389 live = st->stack[i].spilled_ptr.live;
8390 /* liveness must not touch this stack slot anymore */
8391 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
8392 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01008393 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008394 for (j = 0; j < BPF_REG_SIZE; j++)
8395 st->stack[i].slot_type[j] = STACK_INVALID;
8396 }
8397 }
8398}
8399
8400static void clean_verifier_state(struct bpf_verifier_env *env,
8401 struct bpf_verifier_state *st)
8402{
8403 int i;
8404
8405 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
8406 /* all regs in this state in all frames were already marked */
8407 return;
8408
8409 for (i = 0; i <= st->curframe; i++)
8410 clean_func_state(env, st->frame[i]);
8411}
8412
8413/* the parentage chains form a tree.
8414 * the verifier states are added to state lists at given insn and
8415 * pushed into state stack for future exploration.
8416 * when the verifier reaches bpf_exit insn some of the verifer states
8417 * stored in the state lists have their final liveness state already,
8418 * but a lot of states will get revised from liveness point of view when
8419 * the verifier explores other branches.
8420 * Example:
8421 * 1: r0 = 1
8422 * 2: if r1 == 100 goto pc+1
8423 * 3: r0 = 2
8424 * 4: exit
8425 * when the verifier reaches exit insn the register r0 in the state list of
8426 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8427 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8428 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8429 *
8430 * Since the verifier pushes the branch states as it sees them while exploring
8431 * the program the condition of walking the branch instruction for the second
8432 * time means that all states below this branch were already explored and
8433 * their final liveness markes are already propagated.
8434 * Hence when the verifier completes the search of state list in is_state_visited()
8435 * we can call this clean_live_states() function to mark all liveness states
8436 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8437 * will not be used.
8438 * This function also clears the registers and stack for states that !READ
8439 * to simplify state merging.
8440 *
8441 * Important note here that walking the same branch instruction in the callee
8442 * doesn't meant that the states are DONE. The verifier has to compare
8443 * the callsites
8444 */
8445static void clean_live_states(struct bpf_verifier_env *env, int insn,
8446 struct bpf_verifier_state *cur)
8447{
8448 struct bpf_verifier_state_list *sl;
8449 int i;
8450
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008451 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008452 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07008453 if (sl->state.branches)
8454 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008455 if (sl->state.insn_idx != insn ||
8456 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008457 goto next;
8458 for (i = 0; i <= cur->curframe; i++)
8459 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
8460 goto next;
8461 clean_verifier_state(env, &sl->state);
8462next:
8463 sl = sl->next;
8464 }
8465}
8466
Edward Creef1174f72017-08-07 15:26:19 +01008467/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01008468static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8469 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01008470{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008471 bool equal;
8472
Edward Creedc503a82017-08-15 20:34:35 +01008473 if (!(rold->live & REG_LIVE_READ))
8474 /* explored state didn't use this */
8475 return true;
8476
Edward Cree679c7822018-08-22 20:02:19 +01008477 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008478
8479 if (rold->type == PTR_TO_STACK)
8480 /* two stack pointers are equal only if they're pointing to
8481 * the same stack frame, since fp-8 in foo != fp-8 in bar
8482 */
8483 return equal && rold->frameno == rcur->frameno;
8484
8485 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01008486 return true;
8487
8488 if (rold->type == NOT_INIT)
8489 /* explored state can't have used this */
8490 return true;
8491 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008492 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008493 switch (rold->type) {
8494 case SCALAR_VALUE:
8495 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008496 if (!rold->precise && !rcur->precise)
8497 return true;
Edward Creef1174f72017-08-07 15:26:19 +01008498 /* new val must satisfy old val knowledge */
8499 return range_within(rold, rcur) &&
8500 tnum_in(rold->var_off, rcur->var_off);
8501 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08008502 /* We're trying to use a pointer in place of a scalar.
8503 * Even if the scalar was unbounded, this could lead to
8504 * pointer leaks because scalars are allowed to leak
8505 * while pointers are not. We could make this safe in
8506 * special cases if root is calling us, but it's
8507 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01008508 */
Jann Horn179d1c52017-12-18 20:11:59 -08008509 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008510 }
8511 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01008512 /* If the new min/max/var_off satisfy the old ones and
8513 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008514 * 'id' is not compared, since it's only used for maps with
8515 * bpf_spin_lock inside map element and in such cases if
8516 * the rest of the prog is valid for one map element then
8517 * it's valid for all map elements regardless of the key
8518 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01008519 */
8520 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8521 range_within(rold, rcur) &&
8522 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01008523 case PTR_TO_MAP_VALUE_OR_NULL:
8524 /* a PTR_TO_MAP_VALUE could be safe to use as a
8525 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8526 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8527 * checked, doing so could have affected others with the same
8528 * id, and we can't check for that because we lost the id when
8529 * we converted to a PTR_TO_MAP_VALUE.
8530 */
8531 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8532 return false;
8533 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8534 return false;
8535 /* Check our ids match any regs they're supposed to */
8536 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02008537 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01008538 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02008539 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01008540 return false;
8541 /* We must have at least as much range as the old ptr
8542 * did, so that any accesses which were safe before are
8543 * still safe. This is true even if old range < old off,
8544 * since someone could have accessed through (ptr - k), or
8545 * even done ptr -= k in a register, to get a safe access.
8546 */
8547 if (rold->range > rcur->range)
8548 return false;
8549 /* If the offsets don't match, we can't trust our alignment;
8550 * nor can we be sure that we won't fall out of range.
8551 */
8552 if (rold->off != rcur->off)
8553 return false;
8554 /* id relations must be preserved */
8555 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8556 return false;
8557 /* new val must satisfy old val knowledge */
8558 return range_within(rold, rcur) &&
8559 tnum_in(rold->var_off, rcur->var_off);
8560 case PTR_TO_CTX:
8561 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01008562 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07008563 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07008564 case PTR_TO_SOCKET:
8565 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08008566 case PTR_TO_SOCK_COMMON:
8567 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08008568 case PTR_TO_TCP_SOCK:
8569 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07008570 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01008571 /* Only valid matches are exact, which memcmp() above
8572 * would have accepted
8573 */
8574 default:
8575 /* Don't know what's going on, just say it's not safe */
8576 return false;
8577 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008578
Edward Creef1174f72017-08-07 15:26:19 +01008579 /* Shouldn't get here; if we do, say it's not safe */
8580 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008581 return false;
8582}
8583
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008584static bool stacksafe(struct bpf_func_state *old,
8585 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008586 struct idpair *idmap)
8587{
8588 int i, spi;
8589
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008590 /* walk slots of the explored stack and ignore any additional
8591 * slots in the current stack, since explored(safe) state
8592 * didn't use them
8593 */
8594 for (i = 0; i < old->allocated_stack; i++) {
8595 spi = i / BPF_REG_SIZE;
8596
Alexei Starovoitovb2339202018-12-13 11:42:31 -08008597 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8598 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008599 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +00008600 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -08008601 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008602
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008603 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8604 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -08008605
8606 /* explored stack has more populated slots than current stack
8607 * and these slots were used
8608 */
8609 if (i >= cur->allocated_stack)
8610 return false;
8611
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008612 /* if old state was safe with misc data in the stack
8613 * it will be safe with zero-initialized stack.
8614 * The opposite is not true
8615 */
8616 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8617 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8618 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008619 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8620 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8621 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -07008622 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008623 * this verifier states are not equivalent,
8624 * return false to continue verification of this path
8625 */
8626 return false;
8627 if (i % BPF_REG_SIZE)
8628 continue;
8629 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8630 continue;
8631 if (!regsafe(&old->stack[spi].spilled_ptr,
8632 &cur->stack[spi].spilled_ptr,
8633 idmap))
8634 /* when explored and current stack slot are both storing
8635 * spilled registers, check that stored pointers types
8636 * are the same as well.
8637 * Ex: explored safe path could have stored
8638 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8639 * but current path has stored:
8640 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8641 * such verifier states are not equivalent.
8642 * return false to continue verification of this path
8643 */
8644 return false;
8645 }
8646 return true;
8647}
8648
Joe Stringerfd978bf72018-10-02 13:35:35 -07008649static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8650{
8651 if (old->acquired_refs != cur->acquired_refs)
8652 return false;
8653 return !memcmp(old->refs, cur->refs,
8654 sizeof(*old->refs) * old->acquired_refs);
8655}
8656
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008657/* compare two verifier states
8658 *
8659 * all states stored in state_list are known to be valid, since
8660 * verifier reached 'bpf_exit' instruction through them
8661 *
8662 * this function is called when verifier exploring different branches of
8663 * execution popped from the state stack. If it sees an old state that has
8664 * more strict register state and more strict stack state then this execution
8665 * branch doesn't need to be explored further, since verifier already
8666 * concluded that more strict state leads to valid finish.
8667 *
8668 * Therefore two states are equivalent if register state is more conservative
8669 * and explored stack state is more conservative than the current one.
8670 * Example:
8671 * explored current
8672 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8673 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8674 *
8675 * In other words if current stack state (one being explored) has more
8676 * valid slots than old one that already passed validation, it means
8677 * the verifier can stop exploring and conclude that current state is valid too
8678 *
8679 * Similarly with registers. If explored state has register type as invalid
8680 * whereas register type in current state is meaningful, it means that
8681 * the current state will reach 'bpf_exit' instruction safely
8682 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008683static bool func_states_equal(struct bpf_func_state *old,
8684 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008685{
Edward Creef1174f72017-08-07 15:26:19 +01008686 struct idpair *idmap;
8687 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008688 int i;
8689
Edward Creef1174f72017-08-07 15:26:19 +01008690 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8691 /* If we failed to allocate the idmap, just say it's not safe */
8692 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008693 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008694
8695 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +01008696 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +01008697 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008698 }
8699
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008700 if (!stacksafe(old, cur, idmap))
8701 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -07008702
8703 if (!refsafe(old, cur))
8704 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +01008705 ret = true;
8706out_free:
8707 kfree(idmap);
8708 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008709}
8710
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008711static bool states_equal(struct bpf_verifier_env *env,
8712 struct bpf_verifier_state *old,
8713 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +01008714{
Edward Creedc503a82017-08-15 20:34:35 +01008715 int i;
8716
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008717 if (old->curframe != cur->curframe)
8718 return false;
8719
Daniel Borkmann979d63d2019-01-03 00:58:34 +01008720 /* Verification state from speculative execution simulation
8721 * must never prune a non-speculative execution one.
8722 */
8723 if (old->speculative && !cur->speculative)
8724 return false;
8725
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008726 if (old->active_spin_lock != cur->active_spin_lock)
8727 return false;
8728
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008729 /* for states to be equal callsites have to be the same
8730 * and all frame states need to be equivalent
8731 */
8732 for (i = 0; i <= old->curframe; i++) {
8733 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8734 return false;
8735 if (!func_states_equal(old->frame[i], cur->frame[i]))
8736 return false;
8737 }
8738 return true;
8739}
8740
Jiong Wang5327ed32019-05-24 23:25:12 +01008741/* Return 0 if no propagation happened. Return negative error code if error
8742 * happened. Otherwise, return the propagated bit.
8743 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008744static int propagate_liveness_reg(struct bpf_verifier_env *env,
8745 struct bpf_reg_state *reg,
8746 struct bpf_reg_state *parent_reg)
8747{
Jiong Wang5327ed32019-05-24 23:25:12 +01008748 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8749 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008750 int err;
8751
Jiong Wang5327ed32019-05-24 23:25:12 +01008752 /* When comes here, read flags of PARENT_REG or REG could be any of
8753 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8754 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8755 */
8756 if (parent_flag == REG_LIVE_READ64 ||
8757 /* Or if there is no read flag from REG. */
8758 !flag ||
8759 /* Or if the read flag from REG is the same as PARENT_REG. */
8760 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008761 return 0;
8762
Jiong Wang5327ed32019-05-24 23:25:12 +01008763 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008764 if (err)
8765 return err;
8766
Jiong Wang5327ed32019-05-24 23:25:12 +01008767 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008768}
8769
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008770/* A write screens off any subsequent reads; but write marks come from the
8771 * straight-line code between a state and its parent. When we arrive at an
8772 * equivalent state (jump target or such) we didn't arrive by the straight-line
8773 * code, so read marks in the state must propagate to the parent regardless
8774 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +01008775 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008776 */
8777static int propagate_liveness(struct bpf_verifier_env *env,
8778 const struct bpf_verifier_state *vstate,
8779 struct bpf_verifier_state *vparent)
8780{
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008781 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008782 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008783 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008784
8785 if (vparent->curframe != vstate->curframe) {
8786 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8787 vparent->curframe, vstate->curframe);
8788 return -EFAULT;
8789 }
Edward Creedc503a82017-08-15 20:34:35 +01008790 /* Propagate read liveness of registers... */
8791 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -07008792 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008793 parent = vparent->frame[frame];
8794 state = vstate->frame[frame];
8795 parent_reg = parent->regs;
8796 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -07008797 /* We don't need to worry about FP liveness, it's read-only */
8798 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008799 err = propagate_liveness_reg(env, &state_reg[i],
8800 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +01008801 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008802 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +01008803 if (err == REG_LIVE_READ64)
8804 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +01008805 }
Edward Creedc503a82017-08-15 20:34:35 +01008806
Jiong Wang1b04aee2019-04-12 22:59:34 +01008807 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008808 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8809 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008810 parent_reg = &parent->stack[i].spilled_ptr;
8811 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008812 err = propagate_liveness_reg(env, state_reg,
8813 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +01008814 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008815 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008816 }
Edward Creedc503a82017-08-15 20:34:35 +01008817 }
Jiong Wang5327ed32019-05-24 23:25:12 +01008818 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01008819}
8820
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07008821/* find precise scalars in the previous equivalent state and
8822 * propagate them into the current state
8823 */
8824static int propagate_precision(struct bpf_verifier_env *env,
8825 const struct bpf_verifier_state *old)
8826{
8827 struct bpf_reg_state *state_reg;
8828 struct bpf_func_state *state;
8829 int i, err = 0;
8830
8831 state = old->frame[old->curframe];
8832 state_reg = state->regs;
8833 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8834 if (state_reg->type != SCALAR_VALUE ||
8835 !state_reg->precise)
8836 continue;
8837 if (env->log.level & BPF_LOG_LEVEL2)
8838 verbose(env, "propagating r%d\n", i);
8839 err = mark_chain_precision(env, i);
8840 if (err < 0)
8841 return err;
8842 }
8843
8844 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8845 if (state->stack[i].slot_type[0] != STACK_SPILL)
8846 continue;
8847 state_reg = &state->stack[i].spilled_ptr;
8848 if (state_reg->type != SCALAR_VALUE ||
8849 !state_reg->precise)
8850 continue;
8851 if (env->log.level & BPF_LOG_LEVEL2)
8852 verbose(env, "propagating fp%d\n",
8853 (-i - 1) * BPF_REG_SIZE);
8854 err = mark_chain_precision_stack(env, i);
8855 if (err < 0)
8856 return err;
8857 }
8858 return 0;
8859}
8860
Alexei Starovoitov25897262019-06-15 12:12:20 -07008861static bool states_maybe_looping(struct bpf_verifier_state *old,
8862 struct bpf_verifier_state *cur)
8863{
8864 struct bpf_func_state *fold, *fcur;
8865 int i, fr = cur->curframe;
8866
8867 if (old->curframe != fr)
8868 return false;
8869
8870 fold = old->frame[fr];
8871 fcur = cur->frame[fr];
8872 for (i = 0; i < MAX_BPF_REG; i++)
8873 if (memcmp(&fold->regs[i], &fcur->regs[i],
8874 offsetof(struct bpf_reg_state, parent)))
8875 return false;
8876 return true;
8877}
8878
8879
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008880static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008881{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008882 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008883 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +01008884 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08008885 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -07008886 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008887
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008888 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008889 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008890 /* this 'insn_idx' instruction wasn't marked, so we will not
8891 * be doing state search here
8892 */
8893 return 0;
8894
Alexei Starovoitov25897262019-06-15 12:12:20 -07008895 /* bpf progs typically have pruning point every 4 instructions
8896 * http://vger.kernel.org/bpfconf2019.html#session-1
8897 * Do not add new state for future pruning if the verifier hasn't seen
8898 * at least 2 jumps and at least 8 instructions.
8899 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8900 * In tests that amounts to up to 50% reduction into total verifier
8901 * memory consumption and 20% verifier time speedup.
8902 */
8903 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
8904 env->insn_processed - env->prev_insn_processed >= 8)
8905 add_new_state = true;
8906
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008907 pprev = explored_state(env, insn_idx);
8908 sl = *pprev;
8909
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008910 clean_live_states(env, insn_idx, cur);
8911
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008912 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008913 states_cnt++;
8914 if (sl->state.insn_idx != insn_idx)
8915 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -07008916 if (sl->state.branches) {
8917 if (states_maybe_looping(&sl->state, cur) &&
8918 states_equal(env, &sl->state, cur)) {
8919 verbose_linfo(env, insn_idx, "; ");
8920 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
8921 return -EINVAL;
8922 }
8923 /* if the verifier is processing a loop, avoid adding new state
8924 * too often, since different loop iterations have distinct
8925 * states and may not help future pruning.
8926 * This threshold shouldn't be too low to make sure that
8927 * a loop with large bound will be rejected quickly.
8928 * The most abusive loop will be:
8929 * r1 += 1
8930 * if r1 < 1000000 goto pc-2
8931 * 1M insn_procssed limit / 100 == 10k peak states.
8932 * This threshold shouldn't be too high either, since states
8933 * at the end of the loop are likely to be useful in pruning.
8934 */
8935 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
8936 env->insn_processed - env->prev_insn_processed < 100)
8937 add_new_state = false;
8938 goto miss;
8939 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008940 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008941 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008942 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +01008943 * prune the search.
8944 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +01008945 * If we have any write marks in env->cur_state, they
8946 * will prevent corresponding reads in the continuation
8947 * from reaching our parent (an explored_state). Our
8948 * own state will get the read marks recorded, but
8949 * they'll be immediately forgotten as we're pruning
8950 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008951 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008952 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07008953
8954 /* if previous state reached the exit with precision and
8955 * current state is equivalent to it (except precsion marks)
8956 * the precision needs to be propagated back in
8957 * the current state.
8958 */
8959 err = err ? : push_jmp_history(env, cur);
8960 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008961 if (err)
8962 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008963 return 1;
Edward Creedc503a82017-08-15 20:34:35 +01008964 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07008965miss:
8966 /* when new state is not going to be added do not increase miss count.
8967 * Otherwise several loop iterations will remove the state
8968 * recorded earlier. The goal of these heuristics is to have
8969 * states from some iterations of the loop (some in the beginning
8970 * and some at the end) to help pruning.
8971 */
8972 if (add_new_state)
8973 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008974 /* heuristic to determine whether this state is beneficial
8975 * to keep checking from state equivalence point of view.
8976 * Higher numbers increase max_states_per_insn and verification time,
8977 * but do not meaningfully decrease insn_processed.
8978 */
8979 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
8980 /* the state is unlikely to be useful. Remove it to
8981 * speed up verification
8982 */
8983 *pprev = sl->next;
8984 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07008985 u32 br = sl->state.branches;
8986
8987 WARN_ONCE(br,
8988 "BUG live_done but branches_to_explore %d\n",
8989 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008990 free_verifier_state(&sl->state, false);
8991 kfree(sl);
8992 env->peak_states--;
8993 } else {
8994 /* cannot free this state, since parentage chain may
8995 * walk it later. Add it for free_list instead to
8996 * be freed at the end of verification
8997 */
8998 sl->next = env->free_list;
8999 env->free_list = sl;
9000 }
9001 sl = *pprev;
9002 continue;
9003 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009004next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009005 pprev = &sl->next;
9006 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009007 }
9008
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009009 if (env->max_states_per_insn < states_cnt)
9010 env->max_states_per_insn = states_cnt;
9011
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07009012 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009013 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08009014
Alexei Starovoitov25897262019-06-15 12:12:20 -07009015 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009016 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -07009017
9018 /* There were no equivalent states, remember the current one.
9019 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009020 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -07009021 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009022 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -07009023 * again on the way to bpf_exit.
9024 * When looping the sl->state.branches will be > 0 and this state
9025 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009026 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009027 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009028 if (!new_sl)
9029 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009030 env->total_states++;
9031 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009032 env->prev_jmps_processed = env->jmps_processed;
9033 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009034
9035 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +01009036 new = &new_sl->state;
9037 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07009038 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +01009039 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07009040 kfree(new_sl);
9041 return err;
9042 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009043 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009044 WARN_ONCE(new->branches != 1,
9045 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009046
Alexei Starovoitov25897262019-06-15 12:12:20 -07009047 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009048 cur->first_insn_idx = insn_idx;
9049 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009050 new_sl->next = *explored_state(env, insn_idx);
9051 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -08009052 /* connect new state to parentage chain. Current frame needs all
9053 * registers connected. Only r6 - r9 of the callers are alive (pushed
9054 * to the stack implicitly by JITs) so in callers' frames connect just
9055 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9056 * the state of the call instruction (with WRITTEN set), and r0 comes
9057 * from callee with its full parentage chain, anyway.
9058 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +01009059 /* clear write marks in current state: the writes we did are not writes
9060 * our child did, so they don't screen off its reads from us.
9061 * (There are no read marks in current state, because reads always mark
9062 * their parent and current state never has children yet. Only
9063 * explored_states can get read marks.)
9064 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -07009065 for (j = 0; j <= cur->curframe; j++) {
9066 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9067 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9068 for (i = 0; i < BPF_REG_FP; i++)
9069 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9070 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009071
9072 /* all stack frames are accessible from callee, clear them all */
9073 for (j = 0; j <= cur->curframe; j++) {
9074 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +01009075 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009076
Edward Cree679c7822018-08-22 20:02:19 +01009077 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009078 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01009079 frame->stack[i].spilled_ptr.parent =
9080 &newframe->stack[i].spilled_ptr;
9081 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009082 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009083 return 0;
9084}
9085
Joe Stringerc64b7982018-10-02 13:35:33 -07009086/* Return true if it's OK to have the same insn return a different type. */
9087static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9088{
9089 switch (type) {
9090 case PTR_TO_CTX:
9091 case PTR_TO_SOCKET:
9092 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08009093 case PTR_TO_SOCK_COMMON:
9094 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08009095 case PTR_TO_TCP_SOCK:
9096 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07009097 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -07009098 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07009099 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -07009100 return false;
9101 default:
9102 return true;
9103 }
9104}
9105
9106/* If an instruction was previously used with particular pointer types, then we
9107 * need to be careful to avoid cases such as the below, where it may be ok
9108 * for one branch accessing the pointer, but not ok for the other branch:
9109 *
9110 * R1 = sock_ptr
9111 * goto X;
9112 * ...
9113 * R1 = some_other_valid_ptr;
9114 * goto X;
9115 * ...
9116 * R2 = *(u32 *)(R1 + 0);
9117 */
9118static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9119{
9120 return src != prev && (!reg_type_mismatch_ok(src) ||
9121 !reg_type_mismatch_ok(prev));
9122}
9123
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009124static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009125{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07009126 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009127 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009128 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009129 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009130 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009131 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009132 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009133
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009134 for (;;) {
9135 struct bpf_insn *insn;
9136 u8 class;
9137 int err;
9138
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009139 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009140 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009141 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009142 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009143 return -EFAULT;
9144 }
9145
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009146 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009147 class = BPF_CLASS(insn->code);
9148
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009149 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009150 verbose(env,
9151 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009152 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009153 return -E2BIG;
9154 }
9155
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009156 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009157 if (err < 0)
9158 return err;
9159 if (err == 1) {
9160 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009161 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009162 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009163 verbose(env, "\nfrom %d to %d%s: safe\n",
9164 env->prev_insn_idx, env->insn_idx,
9165 env->cur_state->speculative ?
9166 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009167 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009168 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009169 }
9170 goto process_bpf_exit;
9171 }
9172
Alexei Starovoitovc3494802018-12-03 22:46:04 -08009173 if (signal_pending(current))
9174 return -EAGAIN;
9175
Daniel Borkmann3c2ce602017-05-18 03:00:06 +02009176 if (need_resched())
9177 cond_resched();
9178
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009179 if (env->log.level & BPF_LOG_LEVEL2 ||
9180 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9181 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009182 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -07009183 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009184 verbose(env, "\nfrom %d to %d%s:",
9185 env->prev_insn_idx, env->insn_idx,
9186 env->cur_state->speculative ?
9187 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009188 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009189 do_print_state = false;
9190 }
9191
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009192 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01009193 const struct bpf_insn_cbs cbs = {
9194 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +01009195 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +01009196 };
9197
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009198 verbose_linfo(env, env->insn_idx, "; ");
9199 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +01009200 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009201 }
9202
Jakub Kicinskicae19272017-12-27 18:39:05 -08009203 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009204 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9205 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -08009206 if (err)
9207 return err;
9208 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +01009209
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009210 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009211 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009212 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -07009213
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009214 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07009215 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009216 if (err)
9217 return err;
9218
9219 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009220 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009221
9222 /* check for reserved fields is already done */
9223
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009224 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01009225 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009226 if (err)
9227 return err;
9228
Edward Creedc503a82017-08-15 20:34:35 +01009229 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009230 if (err)
9231 return err;
9232
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -07009233 src_reg_type = regs[insn->src_reg].type;
9234
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009235 /* check that memory (src_reg + off) is readable,
9236 * the state of dst_reg will be updated by this func
9237 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009238 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9239 insn->off, BPF_SIZE(insn->code),
9240 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009241 if (err)
9242 return err;
9243
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009244 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009245
9246 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009247 /* saw a valid insn
9248 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009249 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009250 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009251 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009252
Joe Stringerc64b7982018-10-02 13:35:33 -07009253 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009254 /* ABuser program is trying to use the same insn
9255 * dst_reg = *(u32*) (src_reg + off)
9256 * with different pointer types:
9257 * src_reg == ctx in one branch and
9258 * src_reg == stack|map in some other branch.
9259 * Reject it.
9260 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009261 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009262 return -EINVAL;
9263 }
9264
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009265 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009266 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009267
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009268 if (BPF_MODE(insn->code) == BPF_XADD) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009269 err = check_xadd(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009270 if (err)
9271 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009272 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009273 continue;
9274 }
9275
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009276 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01009277 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009278 if (err)
9279 return err;
9280 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01009281 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009282 if (err)
9283 return err;
9284
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009285 dst_reg_type = regs[insn->dst_reg].type;
9286
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009287 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009288 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9289 insn->off, BPF_SIZE(insn->code),
9290 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009291 if (err)
9292 return err;
9293
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009294 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009295
9296 if (*prev_dst_type == NOT_INIT) {
9297 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -07009298 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009299 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009300 return -EINVAL;
9301 }
9302
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009303 } else if (class == BPF_ST) {
9304 if (BPF_MODE(insn->code) != BPF_MEM ||
9305 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009306 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009307 return -EINVAL;
9308 }
9309 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01009310 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009311 if (err)
9312 return err;
9313
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01009314 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -07009315 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02009316 insn->dst_reg,
9317 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01009318 return -EACCES;
9319 }
9320
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009321 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009322 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9323 insn->off, BPF_SIZE(insn->code),
9324 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009325 if (err)
9326 return err;
9327
Jiong Wang092ed092019-01-26 12:26:01 -05009328 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009329 u8 opcode = BPF_OP(insn->code);
9330
Alexei Starovoitov25897262019-06-15 12:12:20 -07009331 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009332 if (opcode == BPF_CALL) {
9333 if (BPF_SRC(insn->code) != BPF_K ||
9334 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009335 (insn->src_reg != BPF_REG_0 &&
9336 insn->src_reg != BPF_PSEUDO_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -05009337 insn->dst_reg != BPF_REG_0 ||
9338 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009339 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009340 return -EINVAL;
9341 }
9342
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009343 if (env->cur_state->active_spin_lock &&
9344 (insn->src_reg == BPF_PSEUDO_CALL ||
9345 insn->imm != BPF_FUNC_spin_unlock)) {
9346 verbose(env, "function calls are not allowed while holding a lock\n");
9347 return -EINVAL;
9348 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009349 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009350 err = check_func_call(env, insn, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009351 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009352 err = check_helper_call(env, insn->imm, env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009353 if (err)
9354 return err;
9355
9356 } else if (opcode == BPF_JA) {
9357 if (BPF_SRC(insn->code) != BPF_K ||
9358 insn->imm != 0 ||
9359 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05009360 insn->dst_reg != BPF_REG_0 ||
9361 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009362 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009363 return -EINVAL;
9364 }
9365
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009366 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009367 continue;
9368
9369 } else if (opcode == BPF_EXIT) {
9370 if (BPF_SRC(insn->code) != BPF_K ||
9371 insn->imm != 0 ||
9372 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05009373 insn->dst_reg != BPF_REG_0 ||
9374 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009375 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009376 return -EINVAL;
9377 }
9378
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009379 if (env->cur_state->active_spin_lock) {
9380 verbose(env, "bpf_spin_unlock is missing\n");
9381 return -EINVAL;
9382 }
9383
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009384 if (state->curframe) {
9385 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009386 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009387 if (err)
9388 return err;
9389 do_print_state = true;
9390 continue;
9391 }
9392
Joe Stringerfd978bf72018-10-02 13:35:35 -07009393 err = check_reference_leak(env);
9394 if (err)
9395 return err;
9396
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009397 err = check_return_code(env);
9398 if (err)
9399 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009400process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -07009401 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009402 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07009403 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009404 if (err < 0) {
9405 if (err != -ENOENT)
9406 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009407 break;
9408 } else {
9409 do_print_state = true;
9410 continue;
9411 }
9412 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009413 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009414 if (err)
9415 return err;
9416 }
9417 } else if (class == BPF_LD) {
9418 u8 mode = BPF_MODE(insn->code);
9419
9420 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009421 err = check_ld_abs(env, insn);
9422 if (err)
9423 return err;
9424
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009425 } else if (mode == BPF_IMM) {
9426 err = check_ld_imm(env, insn);
9427 if (err)
9428 return err;
9429
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009430 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009431 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009432 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009433 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009434 return -EINVAL;
9435 }
9436 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009437 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009438 return -EINVAL;
9439 }
9440
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009441 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009442 }
9443
9444 return 0;
9445}
9446
Hao Luo4976b712020-09-29 16:50:44 -07009447/* replace pseudo btf_id with kernel symbol address */
9448static int check_pseudo_btf_id(struct bpf_verifier_env *env,
9449 struct bpf_insn *insn,
9450 struct bpf_insn_aux_data *aux)
9451{
9452 u32 type, id = insn->imm;
9453 const struct btf_type *t;
9454 const char *sym_name;
9455 u64 addr;
9456
9457 if (!btf_vmlinux) {
9458 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
9459 return -EINVAL;
9460 }
9461
9462 if (insn[1].imm != 0) {
9463 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
9464 return -EINVAL;
9465 }
9466
9467 t = btf_type_by_id(btf_vmlinux, id);
9468 if (!t) {
9469 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
9470 return -ENOENT;
9471 }
9472
9473 if (!btf_type_is_var(t)) {
9474 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
9475 id);
9476 return -EINVAL;
9477 }
9478
9479 sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
9480 addr = kallsyms_lookup_name(sym_name);
9481 if (!addr) {
9482 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
9483 sym_name);
9484 return -ENOENT;
9485 }
9486
9487 insn[0].imm = (u32)addr;
9488 insn[1].imm = addr >> 32;
9489
9490 type = t->type;
9491 t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
9492 if (!btf_type_is_struct(t)) {
9493 const struct btf_type *ret;
9494 const char *tname;
9495 u32 tsize;
9496
9497 /* resolve the type size of ksym. */
9498 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
9499 if (IS_ERR(ret)) {
9500 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
9501 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
9502 tname, PTR_ERR(ret));
9503 return -EINVAL;
9504 }
9505 aux->btf_var.reg_type = PTR_TO_MEM;
9506 aux->btf_var.mem_size = tsize;
9507 } else {
9508 aux->btf_var.reg_type = PTR_TO_BTF_ID;
9509 aux->btf_var.btf_id = type;
9510 }
9511 return 0;
9512}
9513
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009514static int check_map_prealloc(struct bpf_map *map)
9515{
9516 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07009517 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9518 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009519 !(map->map_flags & BPF_F_NO_PREALLOC);
9520}
9521
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009522static bool is_tracing_prog_type(enum bpf_prog_type type)
9523{
9524 switch (type) {
9525 case BPF_PROG_TYPE_KPROBE:
9526 case BPF_PROG_TYPE_TRACEPOINT:
9527 case BPF_PROG_TYPE_PERF_EVENT:
9528 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9529 return true;
9530 default:
9531 return false;
9532 }
9533}
9534
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009535static bool is_preallocated_map(struct bpf_map *map)
9536{
9537 if (!check_map_prealloc(map))
9538 return false;
9539 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
9540 return false;
9541 return true;
9542}
9543
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009544static int check_map_prog_compatibility(struct bpf_verifier_env *env,
9545 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009546 struct bpf_prog *prog)
9547
9548{
Udip Pant7e407812020-08-25 16:20:00 -07009549 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009550 /*
9551 * Validate that trace type programs use preallocated hash maps.
9552 *
9553 * For programs attached to PERF events this is mandatory as the
9554 * perf NMI can hit any arbitrary code sequence.
9555 *
9556 * All other trace types using preallocated hash maps are unsafe as
9557 * well because tracepoint or kprobes can be inside locked regions
9558 * of the memory allocator or at a place where a recursion into the
9559 * memory allocator would see inconsistent state.
9560 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01009561 * On RT enabled kernels run-time allocation of all trace type
9562 * programs is strictly prohibited due to lock type constraints. On
9563 * !RT kernels it is allowed for backwards compatibility reasons for
9564 * now, but warnings are emitted so developers are made aware of
9565 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009566 */
Udip Pant7e407812020-08-25 16:20:00 -07009567 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
9568 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009569 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009570 return -EINVAL;
9571 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01009572 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
9573 verbose(env, "trace type programs can only use preallocated hash map\n");
9574 return -EINVAL;
9575 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009576 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9577 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 -07009578 }
Jakub Kicinskia3884572018-01-11 20:29:09 -08009579
Udip Pant7e407812020-08-25 16:20:00 -07009580 if ((is_tracing_prog_type(prog_type) ||
9581 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009582 map_value_has_spin_lock(map)) {
9583 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9584 return -EINVAL;
9585 }
9586
Jakub Kicinskia3884572018-01-11 20:29:09 -08009587 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -07009588 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -08009589 verbose(env, "offload device mismatch between prog and map\n");
9590 return -EINVAL;
9591 }
9592
Martin KaFai Lau85d33df2020-01-08 16:35:05 -08009593 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9594 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9595 return -EINVAL;
9596 }
9597
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -07009598 if (prog->aux->sleepable)
9599 switch (map->map_type) {
9600 case BPF_MAP_TYPE_HASH:
9601 case BPF_MAP_TYPE_LRU_HASH:
9602 case BPF_MAP_TYPE_ARRAY:
9603 if (!is_preallocated_map(map)) {
9604 verbose(env,
9605 "Sleepable programs can only use preallocated hash maps\n");
9606 return -EINVAL;
9607 }
9608 break;
9609 default:
9610 verbose(env,
9611 "Sleepable programs can only use array and hash maps\n");
9612 return -EINVAL;
9613 }
9614
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009615 return 0;
9616}
9617
Roman Gushchinb741f162018-09-28 14:45:43 +00009618static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9619{
9620 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9621 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9622}
9623
Hao Luo4976b712020-09-29 16:50:44 -07009624/* find and rewrite pseudo imm in ld_imm64 instructions:
9625 *
9626 * 1. if it accesses map FD, replace it with actual map pointer.
9627 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
9628 *
9629 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009630 */
Hao Luo4976b712020-09-29 16:50:44 -07009631static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009632{
9633 struct bpf_insn *insn = env->prog->insnsi;
9634 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009635 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009636
Daniel Borkmannf1f77142017-01-13 23:38:15 +01009637 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +01009638 if (err)
9639 return err;
9640
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009641 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009642 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009643 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009644 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009645 return -EINVAL;
9646 }
9647
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009648 if (BPF_CLASS(insn->code) == BPF_STX &&
9649 ((BPF_MODE(insn->code) != BPF_MEM &&
9650 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009651 verbose(env, "BPF_STX uses reserved fields\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009652 return -EINVAL;
9653 }
9654
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009655 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009656 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009657 struct bpf_map *map;
9658 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009659 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009660
9661 if (i == insn_cnt - 1 || insn[1].code != 0 ||
9662 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9663 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009664 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009665 return -EINVAL;
9666 }
9667
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009668 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009669 /* valid generic load 64-bit imm */
9670 goto next_insn;
9671
Hao Luo4976b712020-09-29 16:50:44 -07009672 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
9673 aux = &env->insn_aux_data[i];
9674 err = check_pseudo_btf_id(env, insn, aux);
9675 if (err)
9676 return err;
9677 goto next_insn;
9678 }
9679
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009680 /* In final convert_pseudo_ld_imm64() step, this is
9681 * converted into regular 64-bit imm load insn.
9682 */
9683 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9684 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9685 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9686 insn[1].imm != 0)) {
9687 verbose(env,
9688 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009689 return -EINVAL;
9690 }
9691
Daniel Borkmann20182392019-03-04 21:08:53 +01009692 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +01009693 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009694 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009695 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +01009696 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009697 return PTR_ERR(map);
9698 }
9699
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009700 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009701 if (err) {
9702 fdput(f);
9703 return err;
9704 }
9705
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009706 aux = &env->insn_aux_data[i];
9707 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9708 addr = (unsigned long)map;
9709 } else {
9710 u32 off = insn[1].imm;
9711
9712 if (off >= BPF_MAX_VAR_OFF) {
9713 verbose(env, "direct value offset of %u is not allowed\n", off);
9714 fdput(f);
9715 return -EINVAL;
9716 }
9717
9718 if (!map->ops->map_direct_value_addr) {
9719 verbose(env, "no direct value access support for this map type\n");
9720 fdput(f);
9721 return -EINVAL;
9722 }
9723
9724 err = map->ops->map_direct_value_addr(map, &addr, off);
9725 if (err) {
9726 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9727 map->value_size, off);
9728 fdput(f);
9729 return err;
9730 }
9731
9732 aux->map_off = off;
9733 addr += off;
9734 }
9735
9736 insn[0].imm = (u32)addr;
9737 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009738
9739 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009740 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009741 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009742 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009743 fdput(f);
9744 goto next_insn;
9745 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009746 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009747
9748 if (env->used_map_cnt >= MAX_USED_MAPS) {
9749 fdput(f);
9750 return -E2BIG;
9751 }
9752
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009753 /* hold the map. If the program is rejected by verifier,
9754 * the map will be released by release_maps() or it
9755 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -07009756 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009757 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -08009758 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009759
9760 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -07009761 env->used_maps[env->used_map_cnt++] = map;
9762
Roman Gushchinb741f162018-09-28 14:45:43 +00009763 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +01009764 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +00009765 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -07009766 fdput(f);
9767 return -EBUSY;
9768 }
9769
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009770 fdput(f);
9771next_insn:
9772 insn++;
9773 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +01009774 continue;
9775 }
9776
9777 /* Basic sanity check before we invest more work here. */
9778 if (!bpf_opcode_in_insntable(insn->code)) {
9779 verbose(env, "unknown opcode %02x\n", insn->code);
9780 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009781 }
9782 }
9783
9784 /* now all pseudo BPF_LD_IMM64 instructions load valid
9785 * 'struct bpf_map *' into a register instead of user map_fd.
9786 * These pointers will be used later by verifier to validate map access.
9787 */
9788 return 0;
9789}
9790
9791/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009792static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009793{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +01009794 __bpf_free_used_maps(env->prog->aux, env->used_maps,
9795 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009796}
9797
9798/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009799static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009800{
9801 struct bpf_insn *insn = env->prog->insnsi;
9802 int insn_cnt = env->prog->len;
9803 int i;
9804
9805 for (i = 0; i < insn_cnt; i++, insn++)
9806 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9807 insn->src_reg = 0;
9808}
9809
Alexei Starovoitov80419022017-03-15 18:26:41 -07009810/* single env->prog->insni[off] instruction was replaced with the range
9811 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9812 * [0, off) and [off, end) to new locations, so the patched range stays zero
9813 */
Jiong Wangb325fbc2019-05-24 23:25:13 +01009814static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9815 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -07009816{
9817 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009818 struct bpf_insn *insn = new_prog->insnsi;
9819 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009820 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -07009821
Jiong Wangb325fbc2019-05-24 23:25:13 +01009822 /* aux info at OFF always needs adjustment, no matter fast path
9823 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9824 * original insn at old prog.
9825 */
9826 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9827
Alexei Starovoitov80419022017-03-15 18:26:41 -07009828 if (cnt == 1)
9829 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009830 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -07009831 new_data = vzalloc(array_size(prog_len,
9832 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -07009833 if (!new_data)
9834 return -ENOMEM;
9835 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9836 memcpy(new_data + off + cnt - 1, old_data + off,
9837 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +01009838 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009839 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009840 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9841 }
Alexei Starovoitov80419022017-03-15 18:26:41 -07009842 env->insn_aux_data = new_data;
9843 vfree(old_data);
9844 return 0;
9845}
9846
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009847static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9848{
9849 int i;
9850
9851 if (len == 1)
9852 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -04009853 /* NOTE: fake 'exit' subprog should be updated as well. */
9854 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +00009855 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009856 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -04009857 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009858 }
9859}
9860
Maciej Fijalkowskia748c692020-09-16 23:10:05 +02009861static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
9862{
9863 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
9864 int i, sz = prog->aux->size_poke_tab;
9865 struct bpf_jit_poke_descriptor *desc;
9866
9867 for (i = 0; i < sz; i++) {
9868 desc = &tab[i];
9869 desc->insn_idx += len - 1;
9870 }
9871}
9872
Alexei Starovoitov80419022017-03-15 18:26:41 -07009873static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
9874 const struct bpf_insn *patch, u32 len)
9875{
9876 struct bpf_prog *new_prog;
9877
9878 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -07009879 if (IS_ERR(new_prog)) {
9880 if (PTR_ERR(new_prog) == -ERANGE)
9881 verbose(env,
9882 "insn %d cannot be patched due to 16-bit range\n",
9883 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -07009884 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -07009885 }
Jiong Wangb325fbc2019-05-24 23:25:13 +01009886 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -07009887 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009888 adjust_subprog_starts(env, off, len);
Maciej Fijalkowskia748c692020-09-16 23:10:05 +02009889 adjust_poke_descs(new_prog, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -07009890 return new_prog;
9891}
9892
Jakub Kicinski52875a02019-01-22 22:45:20 -08009893static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
9894 u32 off, u32 cnt)
9895{
9896 int i, j;
9897
9898 /* find first prog starting at or after off (first to remove) */
9899 for (i = 0; i < env->subprog_cnt; i++)
9900 if (env->subprog_info[i].start >= off)
9901 break;
9902 /* find first prog starting at or after off + cnt (first to stay) */
9903 for (j = i; j < env->subprog_cnt; j++)
9904 if (env->subprog_info[j].start >= off + cnt)
9905 break;
9906 /* if j doesn't start exactly at off + cnt, we are just removing
9907 * the front of previous prog
9908 */
9909 if (env->subprog_info[j].start != off + cnt)
9910 j--;
9911
9912 if (j > i) {
9913 struct bpf_prog_aux *aux = env->prog->aux;
9914 int move;
9915
9916 /* move fake 'exit' subprog as well */
9917 move = env->subprog_cnt + 1 - j;
9918
9919 memmove(env->subprog_info + i,
9920 env->subprog_info + j,
9921 sizeof(*env->subprog_info) * move);
9922 env->subprog_cnt -= j - i;
9923
9924 /* remove func_info */
9925 if (aux->func_info) {
9926 move = aux->func_info_cnt - j;
9927
9928 memmove(aux->func_info + i,
9929 aux->func_info + j,
9930 sizeof(*aux->func_info) * move);
9931 aux->func_info_cnt -= j - i;
9932 /* func_info->insn_off is set after all code rewrites,
9933 * in adjust_btf_func() - no need to adjust
9934 */
9935 }
9936 } else {
9937 /* convert i from "first prog to remove" to "first to adjust" */
9938 if (env->subprog_info[i].start == off)
9939 i++;
9940 }
9941
9942 /* update fake 'exit' subprog as well */
9943 for (; i <= env->subprog_cnt; i++)
9944 env->subprog_info[i].start -= cnt;
9945
9946 return 0;
9947}
9948
9949static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
9950 u32 cnt)
9951{
9952 struct bpf_prog *prog = env->prog;
9953 u32 i, l_off, l_cnt, nr_linfo;
9954 struct bpf_line_info *linfo;
9955
9956 nr_linfo = prog->aux->nr_linfo;
9957 if (!nr_linfo)
9958 return 0;
9959
9960 linfo = prog->aux->linfo;
9961
9962 /* find first line info to remove, count lines to be removed */
9963 for (i = 0; i < nr_linfo; i++)
9964 if (linfo[i].insn_off >= off)
9965 break;
9966
9967 l_off = i;
9968 l_cnt = 0;
9969 for (; i < nr_linfo; i++)
9970 if (linfo[i].insn_off < off + cnt)
9971 l_cnt++;
9972 else
9973 break;
9974
9975 /* First live insn doesn't match first live linfo, it needs to "inherit"
9976 * last removed linfo. prog is already modified, so prog->len == off
9977 * means no live instructions after (tail of the program was removed).
9978 */
9979 if (prog->len != off && l_cnt &&
9980 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
9981 l_cnt--;
9982 linfo[--i].insn_off = off + cnt;
9983 }
9984
9985 /* remove the line info which refer to the removed instructions */
9986 if (l_cnt) {
9987 memmove(linfo + l_off, linfo + i,
9988 sizeof(*linfo) * (nr_linfo - i));
9989
9990 prog->aux->nr_linfo -= l_cnt;
9991 nr_linfo = prog->aux->nr_linfo;
9992 }
9993
9994 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9995 for (i = l_off; i < nr_linfo; i++)
9996 linfo[i].insn_off -= cnt;
9997
9998 /* fix up all subprogs (incl. 'exit') which start >= off */
9999 for (i = 0; i <= env->subprog_cnt; i++)
10000 if (env->subprog_info[i].linfo_idx > l_off) {
10001 /* program may have started in the removed region but
10002 * may not be fully removed
10003 */
10004 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10005 env->subprog_info[i].linfo_idx -= l_cnt;
10006 else
10007 env->subprog_info[i].linfo_idx = l_off;
10008 }
10009
10010 return 0;
10011}
10012
10013static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10014{
10015 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10016 unsigned int orig_prog_len = env->prog->len;
10017 int err;
10018
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080010019 if (bpf_prog_is_dev_bound(env->prog->aux))
10020 bpf_prog_offload_remove_insns(env, off, cnt);
10021
Jakub Kicinski52875a02019-01-22 22:45:20 -080010022 err = bpf_remove_insns(env->prog, off, cnt);
10023 if (err)
10024 return err;
10025
10026 err = adjust_subprog_starts_after_remove(env, off, cnt);
10027 if (err)
10028 return err;
10029
10030 err = bpf_adj_linfo_after_remove(env, off, cnt);
10031 if (err)
10032 return err;
10033
10034 memmove(aux_data + off, aux_data + off + cnt,
10035 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10036
10037 return 0;
10038}
10039
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010040/* The verifier does more data flow analysis than llvm and will not
10041 * explore branches that are dead at run time. Malicious programs can
10042 * have dead code too. Therefore replace all dead at-run-time code
10043 * with 'ja -1'.
10044 *
10045 * Just nops are not optimal, e.g. if they would sit at the end of the
10046 * program and through another bug we would manage to jump there, then
10047 * we'd execute beyond program memory otherwise. Returning exception
10048 * code also wouldn't work since we can have subprogs where the dead
10049 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010050 */
10051static void sanitize_dead_code(struct bpf_verifier_env *env)
10052{
10053 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010054 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010055 struct bpf_insn *insn = env->prog->insnsi;
10056 const int insn_cnt = env->prog->len;
10057 int i;
10058
10059 for (i = 0; i < insn_cnt; i++) {
10060 if (aux_data[i].seen)
10061 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010062 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010063 }
10064}
10065
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010066static bool insn_is_cond_jump(u8 code)
10067{
10068 u8 op;
10069
Jiong Wang092ed092019-01-26 12:26:01 -050010070 if (BPF_CLASS(code) == BPF_JMP32)
10071 return true;
10072
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010073 if (BPF_CLASS(code) != BPF_JMP)
10074 return false;
10075
10076 op = BPF_OP(code);
10077 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10078}
10079
10080static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10081{
10082 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10083 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10084 struct bpf_insn *insn = env->prog->insnsi;
10085 const int insn_cnt = env->prog->len;
10086 int i;
10087
10088 for (i = 0; i < insn_cnt; i++, insn++) {
10089 if (!insn_is_cond_jump(insn->code))
10090 continue;
10091
10092 if (!aux_data[i + 1].seen)
10093 ja.off = insn->off;
10094 else if (!aux_data[i + 1 + insn->off].seen)
10095 ja.off = 0;
10096 else
10097 continue;
10098
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080010099 if (bpf_prog_is_dev_bound(env->prog->aux))
10100 bpf_prog_offload_replace_insn(env, i, &ja);
10101
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010102 memcpy(insn, &ja, sizeof(ja));
10103 }
10104}
10105
Jakub Kicinski52875a02019-01-22 22:45:20 -080010106static int opt_remove_dead_code(struct bpf_verifier_env *env)
10107{
10108 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10109 int insn_cnt = env->prog->len;
10110 int i, err;
10111
10112 for (i = 0; i < insn_cnt; i++) {
10113 int j;
10114
10115 j = 0;
10116 while (i + j < insn_cnt && !aux_data[i + j].seen)
10117 j++;
10118 if (!j)
10119 continue;
10120
10121 err = verifier_remove_insns(env, i, j);
10122 if (err)
10123 return err;
10124 insn_cnt = env->prog->len;
10125 }
10126
10127 return 0;
10128}
10129
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080010130static int opt_remove_nops(struct bpf_verifier_env *env)
10131{
10132 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10133 struct bpf_insn *insn = env->prog->insnsi;
10134 int insn_cnt = env->prog->len;
10135 int i, err;
10136
10137 for (i = 0; i < insn_cnt; i++) {
10138 if (memcmp(&insn[i], &ja, sizeof(ja)))
10139 continue;
10140
10141 err = verifier_remove_insns(env, i, 1);
10142 if (err)
10143 return err;
10144 insn_cnt--;
10145 i--;
10146 }
10147
10148 return 0;
10149}
10150
Jiong Wangd6c23082019-05-24 23:25:18 +010010151static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10152 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010153{
Jiong Wangd6c23082019-05-24 23:25:18 +010010154 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010155 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010010156 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010157 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010158 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +010010159 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010160
Jiong Wangd6c23082019-05-24 23:25:18 +010010161 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010162 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +010010163 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10164 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10165 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010166 for (i = 0; i < len; i++) {
10167 int adj_idx = i + delta;
10168 struct bpf_insn insn;
10169
Jiong Wangd6c23082019-05-24 23:25:18 +010010170 insn = insns[adj_idx];
10171 if (!aux[adj_idx].zext_dst) {
10172 u8 code, class;
10173 u32 imm_rnd;
10174
10175 if (!rnd_hi32)
10176 continue;
10177
10178 code = insn.code;
10179 class = BPF_CLASS(code);
10180 if (insn_no_def(&insn))
10181 continue;
10182
10183 /* NOTE: arg "reg" (the fourth one) is only used for
10184 * BPF_STX which has been ruled out in above
10185 * check, it is safe to pass NULL here.
10186 */
10187 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10188 if (class == BPF_LD &&
10189 BPF_MODE(code) == BPF_IMM)
10190 i++;
10191 continue;
10192 }
10193
10194 /* ctx load could be transformed into wider load. */
10195 if (class == BPF_LDX &&
10196 aux[adj_idx].ptr_type == PTR_TO_CTX)
10197 continue;
10198
10199 imm_rnd = get_random_int();
10200 rnd_hi32_patch[0] = insn;
10201 rnd_hi32_patch[1].imm = imm_rnd;
10202 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10203 patch = rnd_hi32_patch;
10204 patch_len = 4;
10205 goto apply_patch_buffer;
10206 }
10207
10208 if (!bpf_jit_needs_zext())
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010209 continue;
10210
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010211 zext_patch[0] = insn;
10212 zext_patch[1].dst_reg = insn.dst_reg;
10213 zext_patch[1].src_reg = insn.dst_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010010214 patch = zext_patch;
10215 patch_len = 2;
10216apply_patch_buffer:
10217 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010218 if (!new_prog)
10219 return -ENOMEM;
10220 env->prog = new_prog;
10221 insns = new_prog->insnsi;
10222 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010010223 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010224 }
10225
10226 return 0;
10227}
10228
Joe Stringerc64b7982018-10-02 13:35:33 -070010229/* convert load instructions that access fields of a context type into a
10230 * sequence of instructions that access fields of the underlying structure:
10231 * struct __sk_buff -> struct sk_buff
10232 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010233 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010234static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010235{
Jakub Kicinski00176a32017-10-16 16:40:54 -070010236 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010237 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010238 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010239 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010240 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010241 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010242 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010243 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010244
Daniel Borkmannb09928b2018-10-24 22:05:49 +020010245 if (ops->gen_prologue || env->seen_direct_write) {
10246 if (!ops->gen_prologue) {
10247 verbose(env, "bpf verifier is misconfigured\n");
10248 return -EINVAL;
10249 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010250 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10251 env->prog);
10252 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010253 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010254 return -EINVAL;
10255 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070010256 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010257 if (!new_prog)
10258 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070010259
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010260 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010261 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010262 }
10263 }
10264
Joe Stringerc64b7982018-10-02 13:35:33 -070010265 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010266 return 0;
10267
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010268 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010269
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010270 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070010271 bpf_convert_ctx_access_t convert_ctx_access;
10272
Daniel Borkmann62c79892017-01-12 11:51:33 +010010273 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10274 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10275 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070010276 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010277 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +010010278 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10279 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10280 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070010281 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010282 type = BPF_WRITE;
10283 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010284 continue;
10285
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070010286 if (type == BPF_WRITE &&
10287 env->insn_aux_data[i + delta].sanitize_stack_off) {
10288 struct bpf_insn patch[] = {
10289 /* Sanitize suspicious stack slot with zero.
10290 * There are no memory dependencies for this store,
10291 * since it's only using frame pointer and immediate
10292 * constant of zero
10293 */
10294 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
10295 env->insn_aux_data[i + delta].sanitize_stack_off,
10296 0),
10297 /* the original STX instruction will immediately
10298 * overwrite the same stack slot with appropriate value
10299 */
10300 *insn,
10301 };
10302
10303 cnt = ARRAY_SIZE(patch);
10304 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10305 if (!new_prog)
10306 return -ENOMEM;
10307
10308 delta += cnt - 1;
10309 env->prog = new_prog;
10310 insn = new_prog->insnsi + i + delta;
10311 continue;
10312 }
10313
Joe Stringerc64b7982018-10-02 13:35:33 -070010314 switch (env->insn_aux_data[i + delta].ptr_type) {
10315 case PTR_TO_CTX:
10316 if (!ops->convert_ctx_access)
10317 continue;
10318 convert_ctx_access = ops->convert_ctx_access;
10319 break;
10320 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080010321 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070010322 convert_ctx_access = bpf_sock_convert_ctx_access;
10323 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080010324 case PTR_TO_TCP_SOCK:
10325 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
10326 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070010327 case PTR_TO_XDP_SOCK:
10328 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
10329 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010330 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080010331 if (type == BPF_READ) {
10332 insn->code = BPF_LDX | BPF_PROBE_MEM |
10333 BPF_SIZE((insn)->code);
10334 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070010335 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010336 verbose(env, "Writes through BTF pointers are not allowed\n");
10337 return -EINVAL;
10338 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010339 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070010340 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010341 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070010342 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010343
Yonghong Song31fd8582017-06-13 15:52:13 -070010344 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010345 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070010346
10347 /* If the read access is a narrower load of the field,
10348 * convert to a 4/8-byte load, to minimum program type specific
10349 * convert_ctx_access changes. If conversion is successful,
10350 * we will apply proper mask to the result.
10351 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020010352 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010353 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
10354 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070010355 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020010356 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070010357
Daniel Borkmannf96da092017-07-02 02:13:27 +020010358 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010359 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020010360 return -EINVAL;
10361 }
10362
10363 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070010364 if (ctx_field_size == 4)
10365 size_code = BPF_W;
10366 else if (ctx_field_size == 8)
10367 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010368
Daniel Borkmannbc231052018-06-02 23:06:39 +020010369 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070010370 insn->code = BPF_LDX | BPF_MEM | size_code;
10371 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020010372
10373 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070010374 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
10375 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020010376 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
10377 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010378 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010379 return -EINVAL;
10380 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020010381
10382 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020010383 u8 shift = bpf_ctx_narrow_access_offset(
10384 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010385 if (ctx_field_size <= 4) {
10386 if (shift)
10387 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
10388 insn->dst_reg,
10389 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070010390 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020010391 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010392 } else {
10393 if (shift)
10394 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
10395 insn->dst_reg,
10396 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070010397 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020010398 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010399 }
Yonghong Song31fd8582017-06-13 15:52:13 -070010400 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010401
Alexei Starovoitov80419022017-03-15 18:26:41 -070010402 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010403 if (!new_prog)
10404 return -ENOMEM;
10405
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010406 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010407
10408 /* keep walking new program and skip insns we just inserted */
10409 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010410 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010411 }
10412
10413 return 0;
10414}
10415
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010416static int jit_subprogs(struct bpf_verifier_env *env)
10417{
10418 struct bpf_prog *prog = env->prog, **func, *tmp;
10419 int i, j, subprog_start, subprog_end = 0, len, subprog;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010420 struct bpf_map *map_ptr;
Daniel Borkmann7105e822017-12-20 13:42:57 +010010421 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010422 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070010423 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010424
Jiong Wangf910cef2018-05-02 16:17:17 -040010425 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010426 return 0;
10427
Daniel Borkmann7105e822017-12-20 13:42:57 +010010428 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010429 if (insn->code != (BPF_JMP | BPF_CALL) ||
10430 insn->src_reg != BPF_PSEUDO_CALL)
10431 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010432 /* Upon error here we cannot fall back to interpreter but
10433 * need a hard reject of the program. Thus -EFAULT is
10434 * propagated in any case.
10435 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010436 subprog = find_subprog(env, i + insn->imm + 1);
10437 if (subprog < 0) {
10438 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10439 i + insn->imm + 1);
10440 return -EFAULT;
10441 }
10442 /* temporarily remember subprog id inside insn instead of
10443 * aux_data, since next loop will split up all insns into funcs
10444 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010445 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010446 /* remember original imm in case JIT fails and fallback
10447 * to interpreter will be needed
10448 */
10449 env->insn_aux_data[i].call_imm = insn->imm;
10450 /* point imm to __bpf_call_base+1 from JITs point of view */
10451 insn->imm = 1;
10452 }
10453
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010454 err = bpf_prog_alloc_jited_linfo(prog);
10455 if (err)
10456 goto out_undo_insn;
10457
10458 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070010459 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010460 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010461 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010462
Jiong Wangf910cef2018-05-02 16:17:17 -040010463 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010464 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040010465 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010466
10467 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080010468 /* BPF_PROG_RUN doesn't call subprogs directly,
10469 * hence main prog stats include the runtime of subprogs.
10470 * subprogs don't have IDs and not reachable via prog_get_next_id
10471 * func[i]->aux->stats will never be accessed and stays NULL
10472 */
10473 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010474 if (!func[i])
10475 goto out_free;
10476 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
10477 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010010478 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010479 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010010480 if (bpf_prog_calc_tag(func[i]))
10481 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010482 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080010483 func[i]->aux->func_idx = i;
10484 /* the btf and func_info will be freed only at prog->aux */
10485 func[i]->aux->btf = prog->aux->btf;
10486 func[i]->aux->func_info = prog->aux->func_info;
10487
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010488 for (j = 0; j < prog->aux->size_poke_tab; j++) {
10489 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
10490 int ret;
10491
10492 if (!(insn_idx >= subprog_start &&
10493 insn_idx <= subprog_end))
10494 continue;
10495
10496 ret = bpf_jit_add_poke_descriptor(func[i],
10497 &prog->aux->poke_tab[j]);
10498 if (ret < 0) {
10499 verbose(env, "adding tail call poke descriptor failed\n");
10500 goto out_free;
10501 }
10502
10503 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
10504
10505 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
10506 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
10507 if (ret < 0) {
10508 verbose(env, "tracking tail call prog failed\n");
10509 goto out_free;
10510 }
10511 }
10512
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010513 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10514 * Long term would need debug info to populate names
10515 */
10516 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040010517 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010518 func[i]->jit_requested = 1;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010519 func[i]->aux->linfo = prog->aux->linfo;
10520 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
10521 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
10522 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070010523 num_exentries = 0;
10524 insn = func[i]->insnsi;
10525 for (j = 0; j < func[i]->len; j++, insn++) {
10526 if (BPF_CLASS(insn->code) == BPF_LDX &&
10527 BPF_MODE(insn->code) == BPF_PROBE_MEM)
10528 num_exentries++;
10529 }
10530 func[i]->aux->num_exentries = num_exentries;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +020010531 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010532 func[i] = bpf_int_jit_compile(func[i]);
10533 if (!func[i]->jited) {
10534 err = -ENOTSUPP;
10535 goto out_free;
10536 }
10537 cond_resched();
10538 }
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010539
10540 /* Untrack main program's aux structs so that during map_poke_run()
10541 * we will not stumble upon the unfilled poke descriptors; each
10542 * of the main program's poke descs got distributed across subprogs
10543 * and got tracked onto map, so we are sure that none of them will
10544 * be missed after the operation below
10545 */
10546 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10547 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10548
10549 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
10550 }
10551
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010552 /* at this point all bpf functions were successfully JITed
10553 * now populate all bpf_calls with correct addresses and
10554 * run last pass of JIT
10555 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010556 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010557 insn = func[i]->insnsi;
10558 for (j = 0; j < func[i]->len; j++, insn++) {
10559 if (insn->code != (BPF_JMP | BPF_CALL) ||
10560 insn->src_reg != BPF_PSEUDO_CALL)
10561 continue;
10562 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +090010563 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
10564 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010565 }
Sandipan Das2162fed2018-05-24 12:26:45 +053010566
10567 /* we use the aux data to keep a list of the start addresses
10568 * of the JITed images for each function in the program
10569 *
10570 * for some architectures, such as powerpc64, the imm field
10571 * might not be large enough to hold the offset of the start
10572 * address of the callee's JITed image from __bpf_call_base
10573 *
10574 * in such cases, we can lookup the start address of a callee
10575 * by using its subprog id, available from the off field of
10576 * the call instruction, as an index for this list
10577 */
10578 func[i]->aux->func = func;
10579 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010580 }
Jiong Wangf910cef2018-05-02 16:17:17 -040010581 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010582 old_bpf_func = func[i]->bpf_func;
10583 tmp = bpf_int_jit_compile(func[i]);
10584 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
10585 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010586 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010587 goto out_free;
10588 }
10589 cond_resched();
10590 }
10591
10592 /* finally lock prog and jit images for all functions and
10593 * populate kallsysm
10594 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010595 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010596 bpf_prog_lock_ro(func[i]);
10597 bpf_prog_kallsyms_add(func[i]);
10598 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010010599
10600 /* Last step: make now unused interpreter insns from main
10601 * prog consistent for later dump requests, so they can
10602 * later look the same as if they were interpreted only.
10603 */
10604 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Daniel Borkmann7105e822017-12-20 13:42:57 +010010605 if (insn->code != (BPF_JMP | BPF_CALL) ||
10606 insn->src_reg != BPF_PSEUDO_CALL)
10607 continue;
10608 insn->off = env->insn_aux_data[i].call_imm;
10609 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053010610 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010010611 }
10612
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010613 prog->jited = 1;
10614 prog->bpf_func = func[0]->bpf_func;
10615 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040010616 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010617 bpf_prog_free_unused_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010618 return 0;
10619out_free:
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010620 for (i = 0; i < env->subprog_cnt; i++) {
10621 if (!func[i])
10622 continue;
10623
10624 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
10625 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
10626 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
10627 }
10628 bpf_jit_free(func[i]);
10629 }
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010630 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010631out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010632 /* cleanup main prog to be interpreted */
10633 prog->jit_requested = 0;
10634 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10635 if (insn->code != (BPF_JMP | BPF_CALL) ||
10636 insn->src_reg != BPF_PSEUDO_CALL)
10637 continue;
10638 insn->off = 0;
10639 insn->imm = env->insn_aux_data[i].call_imm;
10640 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010641 bpf_prog_free_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010642 return err;
10643}
10644
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010645static int fixup_call_args(struct bpf_verifier_env *env)
10646{
David S. Miller19d28fb2018-01-11 21:27:54 -050010647#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010648 struct bpf_prog *prog = env->prog;
10649 struct bpf_insn *insn = prog->insnsi;
10650 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050010651#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010010652 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010653
Quentin Monnete4052d02018-10-07 12:56:58 +010010654 if (env->prog->jit_requested &&
10655 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050010656 err = jit_subprogs(env);
10657 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010658 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010659 if (err == -EFAULT)
10660 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050010661 }
10662#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020010663 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
10664 /* When JIT fails the progs with bpf2bpf calls and tail_calls
10665 * have to be rejected, since interpreter doesn't support them yet.
10666 */
10667 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10668 return -EINVAL;
10669 }
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010670 for (i = 0; i < prog->len; i++, insn++) {
10671 if (insn->code != (BPF_JMP | BPF_CALL) ||
10672 insn->src_reg != BPF_PSEUDO_CALL)
10673 continue;
10674 depth = get_callee_stack_depth(env, insn, i);
10675 if (depth < 0)
10676 return depth;
10677 bpf_patch_call_args(insn, depth);
10678 }
David S. Miller19d28fb2018-01-11 21:27:54 -050010679 err = 0;
10680#endif
10681 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010682}
10683
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010684/* fixup insn->imm field of bpf_call instructions
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010685 * and inline eligible helpers as explicit sequence of BPF instructions
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010686 *
10687 * this function is called after eBPF program passed verification
10688 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010689static int fixup_bpf_calls(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010690{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010691 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010692 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010693 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010694 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010695 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020010696 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010697 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010698 struct bpf_insn insn_buf[16];
10699 struct bpf_prog *new_prog;
10700 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010701 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010702
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010703 for (i = 0; i < insn_cnt; i++, insn++) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010010704 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10705 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10706 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080010707 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010010708 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10709 struct bpf_insn mask_and_div[] = {
10710 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10711 /* Rx div 0 -> 0 */
10712 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10713 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10714 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10715 *insn,
10716 };
10717 struct bpf_insn mask_and_mod[] = {
10718 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10719 /* Rx mod 0 -> Rx */
10720 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10721 *insn,
10722 };
10723 struct bpf_insn *patchlet;
10724
10725 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10726 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10727 patchlet = mask_and_div + (is64 ? 1 : 0);
10728 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10729 } else {
10730 patchlet = mask_and_mod + (is64 ? 1 : 0);
10731 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10732 }
10733
10734 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080010735 if (!new_prog)
10736 return -ENOMEM;
10737
10738 delta += cnt - 1;
10739 env->prog = prog = new_prog;
10740 insn = new_prog->insnsi + i + delta;
10741 continue;
10742 }
10743
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020010744 if (BPF_CLASS(insn->code) == BPF_LD &&
10745 (BPF_MODE(insn->code) == BPF_ABS ||
10746 BPF_MODE(insn->code) == BPF_IND)) {
10747 cnt = env->ops->gen_ld_abs(insn, insn_buf);
10748 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10749 verbose(env, "bpf verifier is misconfigured\n");
10750 return -EINVAL;
10751 }
10752
10753 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10754 if (!new_prog)
10755 return -ENOMEM;
10756
10757 delta += cnt - 1;
10758 env->prog = prog = new_prog;
10759 insn = new_prog->insnsi + i + delta;
10760 continue;
10761 }
10762
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010763 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10764 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10765 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10766 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10767 struct bpf_insn insn_buf[16];
10768 struct bpf_insn *patch = &insn_buf[0];
10769 bool issrc, isneg;
10770 u32 off_reg;
10771
10772 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010010773 if (!aux->alu_state ||
10774 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010775 continue;
10776
10777 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10778 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10779 BPF_ALU_SANITIZE_SRC;
10780
10781 off_reg = issrc ? insn->src_reg : insn->dst_reg;
10782 if (isneg)
10783 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10784 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10785 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10786 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10787 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10788 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10789 if (issrc) {
10790 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10791 off_reg);
10792 insn->src_reg = BPF_REG_AX;
10793 } else {
10794 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10795 BPF_REG_AX);
10796 }
10797 if (isneg)
10798 insn->code = insn->code == code_add ?
10799 code_sub : code_add;
10800 *patch++ = *insn;
10801 if (issrc && isneg)
10802 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10803 cnt = patch - insn_buf;
10804
10805 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10806 if (!new_prog)
10807 return -ENOMEM;
10808
10809 delta += cnt - 1;
10810 env->prog = prog = new_prog;
10811 insn = new_prog->insnsi + i + delta;
10812 continue;
10813 }
10814
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010815 if (insn->code != (BPF_JMP | BPF_CALL))
10816 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010817 if (insn->src_reg == BPF_PSEUDO_CALL)
10818 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010819
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010820 if (insn->imm == BPF_FUNC_get_route_realm)
10821 prog->dst_needed = 1;
10822 if (insn->imm == BPF_FUNC_get_prandom_u32)
10823 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050010824 if (insn->imm == BPF_FUNC_override_return)
10825 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010826 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040010827 /* If we tail call into other programs, we
10828 * cannot make any assumptions since they can
10829 * be replaced dynamically during runtime in
10830 * the program array.
10831 */
10832 prog->cb_access = 1;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020010833 if (!allow_tail_call_in_subprogs(env))
10834 prog->aux->stack_depth = MAX_BPF_STACK;
10835 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040010836
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010837 /* mark bpf_tail_call as different opcode to avoid
10838 * conditional branch in the interpeter for every normal
10839 * call and to prevent accidental JITing by JIT compiler
10840 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010841 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010842 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070010843 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010844
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010845 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070010846 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010010847 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010848 !bpf_map_key_poisoned(aux) &&
10849 !bpf_map_ptr_poisoned(aux) &&
10850 !bpf_map_ptr_unpriv(aux)) {
10851 struct bpf_jit_poke_descriptor desc = {
10852 .reason = BPF_POKE_REASON_TAIL_CALL,
10853 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10854 .tail_call.key = bpf_map_key_immediate(aux),
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010855 .insn_idx = i + delta,
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010856 };
10857
10858 ret = bpf_jit_add_poke_descriptor(prog, &desc);
10859 if (ret < 0) {
10860 verbose(env, "adding tail call poke descriptor failed\n");
10861 return ret;
10862 }
10863
10864 insn->imm = ret + 1;
10865 continue;
10866 }
10867
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010868 if (!bpf_map_ptr_unpriv(aux))
10869 continue;
10870
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010871 /* instead of changing every JIT dealing with tail_call
10872 * emit two extra insns:
10873 * if (index >= max_entries) goto out;
10874 * index &= array->index_mask;
10875 * to avoid out-of-bounds cpu speculation
10876 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010877 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000010878 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010879 return -EINVAL;
10880 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010881
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010882 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010883 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
10884 map_ptr->max_entries, 2);
10885 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
10886 container_of(map_ptr,
10887 struct bpf_array,
10888 map)->index_mask);
10889 insn_buf[2] = *insn;
10890 cnt = 3;
10891 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10892 if (!new_prog)
10893 return -ENOMEM;
10894
10895 delta += cnt - 1;
10896 env->prog = prog = new_prog;
10897 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010898 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010899 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010900
Daniel Borkmann89c63072017-08-19 03:12:45 +020010901 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020010902 * and other inlining handlers are currently limited to 64 bit
10903 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020010904 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080010905 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020010906 (insn->imm == BPF_FUNC_map_lookup_elem ||
10907 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020010908 insn->imm == BPF_FUNC_map_delete_elem ||
10909 insn->imm == BPF_FUNC_map_push_elem ||
10910 insn->imm == BPF_FUNC_map_pop_elem ||
10911 insn->imm == BPF_FUNC_map_peek_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010912 aux = &env->insn_aux_data[i + delta];
10913 if (bpf_map_ptr_poisoned(aux))
10914 goto patch_call_imm;
10915
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010916 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020010917 ops = map_ptr->ops;
10918 if (insn->imm == BPF_FUNC_map_lookup_elem &&
10919 ops->map_gen_lookup) {
10920 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
10921 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10922 verbose(env, "bpf verifier is misconfigured\n");
10923 return -EINVAL;
10924 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010925
Daniel Borkmann09772d92018-06-02 23:06:35 +020010926 new_prog = bpf_patch_insn_data(env, i + delta,
10927 insn_buf, cnt);
10928 if (!new_prog)
10929 return -ENOMEM;
10930
10931 delta += cnt - 1;
10932 env->prog = prog = new_prog;
10933 insn = new_prog->insnsi + i + delta;
10934 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010935 }
10936
Daniel Borkmann09772d92018-06-02 23:06:35 +020010937 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
10938 (void *(*)(struct bpf_map *map, void *key))NULL));
10939 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
10940 (int (*)(struct bpf_map *map, void *key))NULL));
10941 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
10942 (int (*)(struct bpf_map *map, void *key, void *value,
10943 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020010944 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
10945 (int (*)(struct bpf_map *map, void *value,
10946 u64 flags))NULL));
10947 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
10948 (int (*)(struct bpf_map *map, void *value))NULL));
10949 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
10950 (int (*)(struct bpf_map *map, void *value))NULL));
10951
Daniel Borkmann09772d92018-06-02 23:06:35 +020010952 switch (insn->imm) {
10953 case BPF_FUNC_map_lookup_elem:
10954 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
10955 __bpf_call_base;
10956 continue;
10957 case BPF_FUNC_map_update_elem:
10958 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
10959 __bpf_call_base;
10960 continue;
10961 case BPF_FUNC_map_delete_elem:
10962 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
10963 __bpf_call_base;
10964 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020010965 case BPF_FUNC_map_push_elem:
10966 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
10967 __bpf_call_base;
10968 continue;
10969 case BPF_FUNC_map_pop_elem:
10970 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
10971 __bpf_call_base;
10972 continue;
10973 case BPF_FUNC_map_peek_elem:
10974 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
10975 __bpf_call_base;
10976 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +020010977 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010978
Daniel Borkmann09772d92018-06-02 23:06:35 +020010979 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010980 }
10981
Martin KaFai Lau5576b992020-01-22 15:36:46 -080010982 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10983 insn->imm == BPF_FUNC_jiffies64) {
10984 struct bpf_insn ld_jiffies_addr[2] = {
10985 BPF_LD_IMM64(BPF_REG_0,
10986 (unsigned long)&jiffies),
10987 };
10988
10989 insn_buf[0] = ld_jiffies_addr[0];
10990 insn_buf[1] = ld_jiffies_addr[1];
10991 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
10992 BPF_REG_0, 0);
10993 cnt = 3;
10994
10995 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
10996 cnt);
10997 if (!new_prog)
10998 return -ENOMEM;
10999
11000 delta += cnt - 1;
11001 env->prog = prog = new_prog;
11002 insn = new_prog->insnsi + i + delta;
11003 continue;
11004 }
11005
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011006patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -070011007 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011008 /* all functions that have prototype and verifier allowed
11009 * programs to call them, must be real in-kernel functions
11010 */
11011 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011012 verbose(env,
11013 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011014 func_id_name(insn->imm), insn->imm);
11015 return -EFAULT;
11016 }
11017 insn->imm = fn->func - __bpf_call_base;
11018 }
11019
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011020 /* Since poke tab is now finalized, publish aux to tracker. */
11021 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11022 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11023 if (!map_ptr->ops->map_poke_track ||
11024 !map_ptr->ops->map_poke_untrack ||
11025 !map_ptr->ops->map_poke_run) {
11026 verbose(env, "bpf verifier is misconfigured\n");
11027 return -EINVAL;
11028 }
11029
11030 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11031 if (ret < 0) {
11032 verbose(env, "tracking tail call prog failed\n");
11033 return ret;
11034 }
11035 }
11036
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011037 return 0;
11038}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011039
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011040static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011041{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011042 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011043 int i;
11044
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011045 sl = env->free_list;
11046 while (sl) {
11047 sln = sl->next;
11048 free_verifier_state(&sl->state, false);
11049 kfree(sl);
11050 sl = sln;
11051 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011052 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011053
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011054 if (!env->explored_states)
11055 return;
11056
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011057 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011058 sl = env->explored_states[i];
11059
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070011060 while (sl) {
11061 sln = sl->next;
11062 free_verifier_state(&sl->state, false);
11063 kfree(sl);
11064 sl = sln;
11065 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011066 env->explored_states[i] = NULL;
11067 }
11068}
11069
11070/* The verifier is using insn_aux_data[] to store temporary data during
11071 * verification and to store information for passes that run after the
11072 * verification like dead code sanitization. do_check_common() for subprogram N
11073 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11074 * temporary data after do_check_common() finds that subprogram N cannot be
11075 * verified independently. pass_cnt counts the number of times
11076 * do_check_common() was run and insn->aux->seen tells the pass number
11077 * insn_aux_data was touched. These variables are compared to clear temporary
11078 * data from failed pass. For testing and experiments do_check_common() can be
11079 * run multiple times even when prior attempt to verify is unsuccessful.
11080 */
11081static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11082{
11083 struct bpf_insn *insn = env->prog->insnsi;
11084 struct bpf_insn_aux_data *aux;
11085 int i, class;
11086
11087 for (i = 0; i < env->prog->len; i++) {
11088 class = BPF_CLASS(insn[i].code);
11089 if (class != BPF_LDX && class != BPF_STX)
11090 continue;
11091 aux = &env->insn_aux_data[i];
11092 if (aux->seen != env->pass_cnt)
11093 continue;
11094 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11095 }
11096}
11097
11098static int do_check_common(struct bpf_verifier_env *env, int subprog)
11099{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070011100 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011101 struct bpf_verifier_state *state;
11102 struct bpf_reg_state *regs;
11103 int ret, i;
11104
11105 env->prev_linfo = NULL;
11106 env->pass_cnt++;
11107
11108 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11109 if (!state)
11110 return -ENOMEM;
11111 state->curframe = 0;
11112 state->speculative = false;
11113 state->branches = 1;
11114 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11115 if (!state->frame[0]) {
11116 kfree(state);
11117 return -ENOMEM;
11118 }
11119 env->cur_state = state;
11120 init_func_state(env, state->frame[0],
11121 BPF_MAIN_FUNC /* callsite */,
11122 0 /* frameno */,
11123 subprog);
11124
11125 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011126 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011127 ret = btf_prepare_func_args(env, subprog, regs);
11128 if (ret)
11129 goto out;
11130 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11131 if (regs[i].type == PTR_TO_CTX)
11132 mark_reg_known_zero(env, regs, i);
11133 else if (regs[i].type == SCALAR_VALUE)
11134 mark_reg_unknown(env, regs, i);
11135 }
11136 } else {
11137 /* 1st arg to a function */
11138 regs[BPF_REG_1].type = PTR_TO_CTX;
11139 mark_reg_known_zero(env, regs, BPF_REG_1);
11140 ret = btf_check_func_arg_match(env, subprog, regs);
11141 if (ret == -EFAULT)
11142 /* unlikely verifier bug. abort.
11143 * ret == 0 and ret < 0 are sadly acceptable for
11144 * main() function due to backward compatibility.
11145 * Like socket filter program may be written as:
11146 * int bpf_prog(struct pt_regs *ctx)
11147 * and never dereference that ctx in the program.
11148 * 'struct pt_regs' is a type mismatch for socket
11149 * filter that should be using 'struct __sk_buff'.
11150 */
11151 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011152 }
11153
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011154 ret = do_check(env);
11155out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080011156 /* check for NULL is necessary, since cur_state can be freed inside
11157 * do_check() under memory pressure.
11158 */
11159 if (env->cur_state) {
11160 free_verifier_state(env->cur_state, true);
11161 env->cur_state = NULL;
11162 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070011163 while (!pop_stack(env, NULL, NULL, false));
11164 if (!ret && pop_log)
11165 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011166 free_states(env);
11167 if (ret)
11168 /* clean aux data in case subprog was rejected */
11169 sanitize_insn_aux_data(env);
11170 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011171}
11172
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011173/* Verify all global functions in a BPF program one by one based on their BTF.
11174 * All global functions must pass verification. Otherwise the whole program is rejected.
11175 * Consider:
11176 * int bar(int);
11177 * int foo(int f)
11178 * {
11179 * return bar(f);
11180 * }
11181 * int bar(int b)
11182 * {
11183 * ...
11184 * }
11185 * foo() will be verified first for R1=any_scalar_value. During verification it
11186 * will be assumed that bar() already verified successfully and call to bar()
11187 * from foo() will be checked for type match only. Later bar() will be verified
11188 * independently to check that it's safe for R1=any_scalar_value.
11189 */
11190static int do_check_subprogs(struct bpf_verifier_env *env)
11191{
11192 struct bpf_prog_aux *aux = env->prog->aux;
11193 int i, ret;
11194
11195 if (!aux->func_info)
11196 return 0;
11197
11198 for (i = 1; i < env->subprog_cnt; i++) {
11199 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11200 continue;
11201 env->insn_idx = env->subprog_info[i].start;
11202 WARN_ON_ONCE(env->insn_idx == 0);
11203 ret = do_check_common(env, i);
11204 if (ret) {
11205 return ret;
11206 } else if (env->log.level & BPF_LOG_LEVEL) {
11207 verbose(env,
11208 "Func#%d is safe for any args that match its prototype\n",
11209 i);
11210 }
11211 }
11212 return 0;
11213}
11214
11215static int do_check_main(struct bpf_verifier_env *env)
11216{
11217 int ret;
11218
11219 env->insn_idx = 0;
11220 ret = do_check_common(env, 0);
11221 if (!ret)
11222 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11223 return ret;
11224}
11225
11226
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011227static void print_verification_stats(struct bpf_verifier_env *env)
11228{
11229 int i;
11230
11231 if (env->log.level & BPF_LOG_STATS) {
11232 verbose(env, "verification time %lld usec\n",
11233 div_u64(env->verification_time, 1000));
11234 verbose(env, "stack depth ");
11235 for (i = 0; i < env->subprog_cnt; i++) {
11236 u32 depth = env->subprog_info[i].stack_depth;
11237
11238 verbose(env, "%d", depth);
11239 if (i + 1 < env->subprog_cnt)
11240 verbose(env, "+");
11241 }
11242 verbose(env, "\n");
11243 }
11244 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11245 "total_states %d peak_states %d mark_read %d\n",
11246 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11247 env->max_states_per_insn, env->total_states,
11248 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011249}
11250
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011251static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11252{
11253 const struct btf_type *t, *func_proto;
11254 const struct bpf_struct_ops *st_ops;
11255 const struct btf_member *member;
11256 struct bpf_prog *prog = env->prog;
11257 u32 btf_id, member_idx;
11258 const char *mname;
11259
11260 btf_id = prog->aux->attach_btf_id;
11261 st_ops = bpf_struct_ops_find(btf_id);
11262 if (!st_ops) {
11263 verbose(env, "attach_btf_id %u is not a supported struct\n",
11264 btf_id);
11265 return -ENOTSUPP;
11266 }
11267
11268 t = st_ops->type;
11269 member_idx = prog->expected_attach_type;
11270 if (member_idx >= btf_type_vlen(t)) {
11271 verbose(env, "attach to invalid member idx %u of struct %s\n",
11272 member_idx, st_ops->name);
11273 return -EINVAL;
11274 }
11275
11276 member = &btf_type_member(t)[member_idx];
11277 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11278 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11279 NULL);
11280 if (!func_proto) {
11281 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11282 mname, member_idx, st_ops->name);
11283 return -EINVAL;
11284 }
11285
11286 if (st_ops->check_member) {
11287 int err = st_ops->check_member(t, member);
11288
11289 if (err) {
11290 verbose(env, "attach to unsupported member %s of struct %s\n",
11291 mname, st_ops->name);
11292 return err;
11293 }
11294 }
11295
11296 prog->aux->attach_func_proto = func_proto;
11297 prog->aux->attach_func_name = mname;
11298 env->ops = st_ops->verifier_ops;
11299
11300 return 0;
11301}
KP Singh6ba43b72020-03-04 20:18:50 +010011302#define SECURITY_PREFIX "security_"
11303
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011304static int check_attach_modify_return(unsigned long addr, const char *func_name)
KP Singh6ba43b72020-03-04 20:18:50 +010011305{
KP Singh69191752020-03-05 21:49:55 +010011306 if (within_error_injection_list(addr) ||
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011307 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010011308 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010011309
KP Singh6ba43b72020-03-04 20:18:50 +010011310 return -EINVAL;
11311}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011312
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011313/* non exhaustive list of sleepable bpf_lsm_*() functions */
11314BTF_SET_START(btf_sleepable_lsm_hooks)
11315#ifdef CONFIG_BPF_LSM
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011316BTF_ID(func, bpf_lsm_bprm_committed_creds)
Alexei Starovoitov29523c52020-08-31 09:31:32 -070011317#else
11318BTF_ID_UNUSED
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011319#endif
11320BTF_SET_END(btf_sleepable_lsm_hooks)
11321
11322static int check_sleepable_lsm_hook(u32 btf_id)
11323{
11324 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
11325}
11326
11327/* list of non-sleepable functions that are otherwise on
11328 * ALLOW_ERROR_INJECTION list
11329 */
11330BTF_SET_START(btf_non_sleepable_error_inject)
11331/* Three functions below can be called from sleepable and non-sleepable context.
11332 * Assume non-sleepable from bpf safety point of view.
11333 */
11334BTF_ID(func, __add_to_page_cache_locked)
11335BTF_ID(func, should_fail_alloc_page)
11336BTF_ID(func, should_failslab)
11337BTF_SET_END(btf_non_sleepable_error_inject)
11338
11339static int check_non_sleepable_error_inject(u32 btf_id)
11340{
11341 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11342}
11343
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011344int bpf_check_attach_target(struct bpf_verifier_log *log,
11345 const struct bpf_prog *prog,
11346 const struct bpf_prog *tgt_prog,
11347 u32 btf_id,
11348 struct bpf_attach_target_info *tgt_info)
Martin KaFai Lau38207292019-10-24 17:18:11 -070011349{
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011350 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011351 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011352 int ret = 0, subprog = -1, i;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011353 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011354 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011355 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011356 struct btf *btf;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011357 long addr = 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011358
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011359 if (!btf_id) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011360 bpf_log(log, "Tracing programs must provide btf_id\n");
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011361 return -EINVAL;
11362 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011363 btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011364 if (!btf) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011365 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011366 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11367 return -EINVAL;
11368 }
11369 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011370 if (!t) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011371 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011372 return -EINVAL;
11373 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011374 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011375 if (!tname) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011376 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011377 return -EINVAL;
11378 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011379 if (tgt_prog) {
11380 struct bpf_prog_aux *aux = tgt_prog->aux;
11381
11382 for (i = 0; i < aux->func_info_cnt; i++)
11383 if (aux->func_info[i].type_id == btf_id) {
11384 subprog = i;
11385 break;
11386 }
11387 if (subprog == -1) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011388 bpf_log(log, "Subprog %s doesn't exist\n", tname);
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011389 return -EINVAL;
11390 }
11391 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011392 if (prog_extension) {
11393 if (conservative) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011394 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011395 "Cannot replace static functions\n");
11396 return -EINVAL;
11397 }
11398 if (!prog->jit_requested) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011399 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011400 "Extension programs should be JITed\n");
11401 return -EINVAL;
11402 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011403 }
11404 if (!tgt_prog->jited) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011405 bpf_log(log, "Can attach to only JITed progs\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011406 return -EINVAL;
11407 }
11408 if (tgt_prog->type == prog->type) {
11409 /* Cannot fentry/fexit another fentry/fexit program.
11410 * Cannot attach program extension to another extension.
11411 * It's ok to attach fentry/fexit to extension program.
11412 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011413 bpf_log(log, "Cannot recursively attach\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011414 return -EINVAL;
11415 }
11416 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
11417 prog_extension &&
11418 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
11419 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
11420 /* Program extensions can extend all program types
11421 * except fentry/fexit. The reason is the following.
11422 * The fentry/fexit programs are used for performance
11423 * analysis, stats and can be attached to any program
11424 * type except themselves. When extension program is
11425 * replacing XDP function it is necessary to allow
11426 * performance analysis of all functions. Both original
11427 * XDP program and its program extension. Hence
11428 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11429 * allowed. If extending of fentry/fexit was allowed it
11430 * would be possible to create long call chain
11431 * fentry->extension->fentry->extension beyond
11432 * reasonable stack size. Hence extending fentry is not
11433 * allowed.
11434 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011435 bpf_log(log, "Cannot extend fentry/fexit\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011436 return -EINVAL;
11437 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011438 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011439 if (prog_extension) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011440 bpf_log(log, "Cannot replace kernel functions\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011441 return -EINVAL;
11442 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011443 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011444
11445 switch (prog->expected_attach_type) {
11446 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011447 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011448 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011449 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11450 return -EINVAL;
11451 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070011452 if (!btf_type_is_typedef(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011453 bpf_log(log, "attach_btf_id %u is not a typedef\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070011454 btf_id);
11455 return -EINVAL;
11456 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011457 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011458 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070011459 btf_id, tname);
11460 return -EINVAL;
11461 }
11462 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011463 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011464 if (!btf_type_is_ptr(t))
11465 /* should never happen in valid vmlinux build */
11466 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011467 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011468 if (!btf_type_is_func_proto(t))
11469 /* should never happen in valid vmlinux build */
11470 return -EINVAL;
11471
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011472 break;
Yonghong Song15d83c42020-05-09 10:59:00 -070011473 case BPF_TRACE_ITER:
11474 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011475 bpf_log(log, "attach_btf_id %u is not a function\n",
Yonghong Song15d83c42020-05-09 10:59:00 -070011476 btf_id);
11477 return -EINVAL;
11478 }
11479 t = btf_type_by_id(btf, t->type);
11480 if (!btf_type_is_func_proto(t))
11481 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011482 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
11483 if (ret)
11484 return ret;
11485 break;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011486 default:
11487 if (!prog_extension)
11488 return -EINVAL;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -050011489 fallthrough;
KP Singhae240822020-03-04 20:18:49 +010011490 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010011491 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011492 case BPF_TRACE_FENTRY:
11493 case BPF_TRACE_FEXIT:
11494 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011495 bpf_log(log, "attach_btf_id %u is not a function\n",
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011496 btf_id);
11497 return -EINVAL;
11498 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011499 if (prog_extension &&
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011500 btf_check_type_match(log, prog, btf, t))
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011501 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011502 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011503 if (!btf_type_is_func_proto(t))
11504 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011505
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020011506 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
11507 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
11508 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
11509 return -EINVAL;
11510
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011511 if (tgt_prog && conservative)
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011512 t = NULL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011513
11514 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011515 if (ret < 0)
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011516 return ret;
11517
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011518 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080011519 if (subprog == 0)
11520 addr = (long) tgt_prog->bpf_func;
11521 else
11522 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011523 } else {
11524 addr = kallsyms_lookup_name(tname);
11525 if (!addr) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011526 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011527 "The address of function %s cannot be found\n",
11528 tname);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011529 return -ENOENT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011530 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011531 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011532
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011533 if (prog->aux->sleepable) {
11534 ret = -EINVAL;
11535 switch (prog->type) {
11536 case BPF_PROG_TYPE_TRACING:
11537 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11538 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11539 */
11540 if (!check_non_sleepable_error_inject(btf_id) &&
11541 within_error_injection_list(addr))
11542 ret = 0;
11543 break;
11544 case BPF_PROG_TYPE_LSM:
11545 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11546 * Only some of them are sleepable.
11547 */
11548 if (check_sleepable_lsm_hook(btf_id))
11549 ret = 0;
11550 break;
11551 default:
11552 break;
11553 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011554 if (ret) {
11555 bpf_log(log, "%s is not sleepable\n", tname);
11556 return ret;
11557 }
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011558 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020011559 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020011560 bpf_log(log, "can't modify return codes of BPF programs\n");
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011561 return -EINVAL;
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020011562 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011563 ret = check_attach_modify_return(addr, tname);
11564 if (ret) {
11565 bpf_log(log, "%s() is not modifiable\n", tname);
11566 return ret;
11567 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011568 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011569
11570 break;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011571 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011572 tgt_info->tgt_addr = addr;
11573 tgt_info->tgt_name = tname;
11574 tgt_info->tgt_type = t;
11575 return 0;
11576}
11577
11578static int check_attach_btf_id(struct bpf_verifier_env *env)
11579{
11580 struct bpf_prog *prog = env->prog;
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020011581 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011582 struct bpf_attach_target_info tgt_info = {};
11583 u32 btf_id = prog->aux->attach_btf_id;
11584 struct bpf_trampoline *tr;
11585 int ret;
11586 u64 key;
11587
11588 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
11589 prog->type != BPF_PROG_TYPE_LSM) {
11590 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11591 return -EINVAL;
11592 }
11593
11594 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
11595 return check_struct_ops_btf_id(env);
11596
11597 if (prog->type != BPF_PROG_TYPE_TRACING &&
11598 prog->type != BPF_PROG_TYPE_LSM &&
11599 prog->type != BPF_PROG_TYPE_EXT)
11600 return 0;
11601
11602 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
11603 if (ret)
11604 return ret;
11605
11606 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020011607 /* to make freplace equivalent to their targets, they need to
11608 * inherit env->ops and expected_attach_type for the rest of the
11609 * verification
11610 */
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011611 env->ops = bpf_verifier_ops[tgt_prog->type];
11612 prog->expected_attach_type = tgt_prog->expected_attach_type;
11613 }
11614
11615 /* store info about the attachment target that will be used later */
11616 prog->aux->attach_func_proto = tgt_info.tgt_type;
11617 prog->aux->attach_func_name = tgt_info.tgt_name;
11618
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020011619 if (tgt_prog) {
11620 prog->aux->saved_dst_prog_type = tgt_prog->type;
11621 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
11622 }
11623
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011624 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
11625 prog->aux->attach_btf_trace = true;
11626 return 0;
11627 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
11628 if (!bpf_iter_prog_supported(prog))
11629 return -EINVAL;
11630 return 0;
11631 }
11632
11633 if (prog->type == BPF_PROG_TYPE_LSM) {
11634 ret = bpf_lsm_verify_prog(&env->log, prog);
11635 if (ret < 0)
11636 return ret;
11637 }
11638
11639 key = bpf_trampoline_compute_key(tgt_prog, btf_id);
11640 tr = bpf_trampoline_get(key, &tgt_info);
11641 if (!tr)
11642 return -ENOMEM;
11643
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020011644 prog->aux->dst_trampoline = tr;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020011645 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011646}
11647
Alan Maguire76654e62020-09-28 12:31:03 +010011648struct btf *bpf_get_btf_vmlinux(void)
11649{
11650 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
11651 mutex_lock(&bpf_verifier_lock);
11652 if (!btf_vmlinux)
11653 btf_vmlinux = btf_parse_vmlinux();
11654 mutex_unlock(&bpf_verifier_lock);
11655 }
11656 return btf_vmlinux;
11657}
11658
Yonghong Song838e9692018-11-19 15:29:11 -080011659int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
11660 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011661{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011662 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011663 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070011664 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011665 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011666 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011667
Arnd Bergmanneba0c922017-11-02 12:05:52 +010011668 /* no program is valid */
11669 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
11670 return -EINVAL;
11671
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011672 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011673 * allocate/free it every time bpf_check() is called
11674 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011675 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011676 if (!env)
11677 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011678 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011679
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011680 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070011681 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011682 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011683 ret = -ENOMEM;
11684 if (!env->insn_aux_data)
11685 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011686 for (i = 0; i < len; i++)
11687 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011688 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070011689 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011690 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011691
Alan Maguire76654e62020-09-28 12:31:03 +010011692 bpf_get_btf_vmlinux();
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011693
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011694 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070011695 if (!is_priv)
11696 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011697
11698 if (attr->log_level || attr->log_buf || attr->log_size) {
11699 /* user requested verbose verifier output
11700 * and supplied buffer to store the verification trace
11701 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070011702 log->level = attr->log_level;
11703 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
11704 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011705
11706 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070011707 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070011708 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011709 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011710 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011711 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020011712
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011713 if (IS_ERR(btf_vmlinux)) {
11714 /* Either gcc or pahole or kernel are broken. */
11715 verbose(env, "in-kernel BTF is malformed\n");
11716 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011717 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011718 }
11719
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020011720 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
11721 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070011722 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080011723 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
11724 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011725
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011726 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070011727 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011728 env->bypass_spec_v1 = bpf_bypass_spec_v1();
11729 env->bypass_spec_v4 = bpf_bypass_spec_v4();
11730 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011731
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070011732 if (is_priv)
11733 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
11734
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070011735 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Quentin Monneta40a2632018-11-09 13:03:31 +000011736 ret = bpf_prog_offload_verifier_prep(env->prog);
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070011737 if (ret)
11738 goto skip_full_check;
11739 }
11740
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011741 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011742 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011743 GFP_USER);
11744 ret = -ENOMEM;
11745 if (!env->explored_states)
11746 goto skip_full_check;
11747
Martin KaFai Laud9762e82018-12-13 10:41:48 -080011748 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070011749 if (ret < 0)
11750 goto skip_full_check;
11751
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011752 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080011753 if (ret < 0)
11754 goto skip_full_check;
11755
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011756 ret = check_attach_btf_id(env);
11757 if (ret)
11758 goto skip_full_check;
11759
Hao Luo4976b712020-09-29 16:50:44 -070011760 ret = resolve_pseudo_ldimm64(env);
11761 if (ret < 0)
11762 goto skip_full_check;
11763
Martin KaFai Laud9762e82018-12-13 10:41:48 -080011764 ret = check_cfg(env);
11765 if (ret < 0)
11766 goto skip_full_check;
11767
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011768 ret = do_check_subprogs(env);
11769 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011770
Quentin Monnetc941ce92018-10-07 12:56:47 +010011771 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11772 ret = bpf_prog_offload_finalize(env);
11773
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011774skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011775 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011776
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011777 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080011778 ret = check_max_stack_depth(env);
11779
Jakub Kicinski9b38c402018-12-19 22:13:06 -080011780 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011781 if (is_priv) {
11782 if (ret == 0)
11783 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080011784 if (ret == 0)
11785 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080011786 if (ret == 0)
11787 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080011788 } else {
11789 if (ret == 0)
11790 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011791 }
11792
Jakub Kicinski9b38c402018-12-19 22:13:06 -080011793 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011794 /* program is valid, convert *(u32*)(ctx + off) accesses */
11795 ret = convert_ctx_accesses(env);
11796
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011797 if (ret == 0)
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011798 ret = fixup_bpf_calls(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011799
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011800 /* do 32-bit optimization after insn patching has done so those patched
11801 * insns could be handled correctly.
11802 */
Jiong Wangd6c23082019-05-24 23:25:18 +010011803 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11804 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11805 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11806 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011807 }
11808
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011809 if (ret == 0)
11810 ret = fixup_call_args(env);
11811
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011812 env->verification_time = ktime_get_ns() - start_time;
11813 print_verification_stats(env);
11814
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011815 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011816 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011817 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011818 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011819 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011820 }
11821
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011822 if (ret == 0 && env->used_map_cnt) {
11823 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011824 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11825 sizeof(env->used_maps[0]),
11826 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011827
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011828 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011829 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011830 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011831 }
11832
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011833 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011834 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011835 env->prog->aux->used_map_cnt = env->used_map_cnt;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011836
11837 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11838 * bpf_ld_imm64 instructions
11839 */
11840 convert_pseudo_ld_imm64(env);
11841 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011842
Yonghong Songba64e7d2018-11-24 23:20:44 -080011843 if (ret == 0)
11844 adjust_btf_func(env);
11845
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011846err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011847 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011848 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070011849 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011850 */
11851 release_maps(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020011852
11853 /* extension progs temporarily inherit the attach_type of their targets
11854 for verification purposes, so set it back to zero before returning
11855 */
11856 if (env->prog->type == BPF_PROG_TYPE_EXT)
11857 env->prog->expected_attach_type = 0;
11858
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011859 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011860err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070011861 if (!is_priv)
11862 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011863 vfree(env->insn_aux_data);
11864err_free_env:
11865 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011866 return ret;
11867}