blob: b4c22b5ce5a2b0cc90ff55c0fb8d56705d65af78 [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;
Alexei Starovoitova7658e12019-10-15 20:25:04 -0700241 u32 btf_id;
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200242};
243
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700244struct btf *btf_vmlinux;
245
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700246static DEFINE_MUTEX(bpf_verifier_lock);
247
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800248static const struct bpf_line_info *
249find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
250{
251 const struct bpf_line_info *linfo;
252 const struct bpf_prog *prog;
253 u32 i, nr_linfo;
254
255 prog = env->prog;
256 nr_linfo = prog->aux->nr_linfo;
257
258 if (!nr_linfo || insn_off >= prog->len)
259 return NULL;
260
261 linfo = prog->aux->linfo;
262 for (i = 1; i < nr_linfo; i++)
263 if (insn_off < linfo[i].insn_off)
264 break;
265
266 return &linfo[i - 1];
267}
268
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700269void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
270 va_list args)
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700271{
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700272 unsigned int n;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700273
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700274 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700275
276 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
277 "verifier log line truncated - local buffer too short\n");
278
279 n = min(log->len_total - log->len_used - 1, n);
280 log->kbuf[n] = '\0';
281
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700282 if (log->level == BPF_LOG_KERNEL) {
283 pr_err("BPF:%s\n", log->kbuf);
284 return;
285 }
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700286 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
287 log->len_used += n;
288 else
289 log->ubuf = NULL;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700290}
Jiri Olsaabe08842018-03-23 11:41:28 +0100291
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700292static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
293{
294 char zero = 0;
295
296 if (!bpf_verifier_log_needed(log))
297 return;
298
299 log->len_used = new_pos;
300 if (put_user(zero, log->ubuf + new_pos))
301 log->ubuf = NULL;
302}
303
Jiri Olsaabe08842018-03-23 11:41:28 +0100304/* log_level controls verbosity level of eBPF verifier.
305 * bpf_verifier_log_write() is used to dump the verification trace to the log,
306 * so the user can figure out what's wrong with the program
Quentin Monnet430e68d2018-01-10 12:26:06 +0000307 */
Jiri Olsaabe08842018-03-23 11:41:28 +0100308__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
309 const char *fmt, ...)
310{
311 va_list args;
312
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700313 if (!bpf_verifier_log_needed(&env->log))
314 return;
315
Jiri Olsaabe08842018-03-23 11:41:28 +0100316 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700317 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100318 va_end(args);
319}
320EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
321
322__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
323{
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700324 struct bpf_verifier_env *env = private_data;
Jiri Olsaabe08842018-03-23 11:41:28 +0100325 va_list args;
326
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700327 if (!bpf_verifier_log_needed(&env->log))
328 return;
329
Jiri Olsaabe08842018-03-23 11:41:28 +0100330 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700331 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100332 va_end(args);
333}
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700334
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700335__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
336 const char *fmt, ...)
337{
338 va_list args;
339
340 if (!bpf_verifier_log_needed(log))
341 return;
342
343 va_start(args, fmt);
344 bpf_verifier_vlog(log, fmt, args);
345 va_end(args);
346}
347
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800348static const char *ltrim(const char *s)
349{
350 while (isspace(*s))
351 s++;
352
353 return s;
354}
355
356__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
357 u32 insn_off,
358 const char *prefix_fmt, ...)
359{
360 const struct bpf_line_info *linfo;
361
362 if (!bpf_verifier_log_needed(&env->log))
363 return;
364
365 linfo = find_linfo(env, insn_off);
366 if (!linfo || linfo == env->prev_linfo)
367 return;
368
369 if (prefix_fmt) {
370 va_list args;
371
372 va_start(args, prefix_fmt);
373 bpf_verifier_vlog(&env->log, prefix_fmt, args);
374 va_end(args);
375 }
376
377 verbose(env, "%s\n",
378 ltrim(btf_name_by_offset(env->prog->aux->btf,
379 linfo->line_off)));
380
381 env->prev_linfo = linfo;
382}
383
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200384static bool type_is_pkt_pointer(enum bpf_reg_type type)
385{
386 return type == PTR_TO_PACKET ||
387 type == PTR_TO_PACKET_META;
388}
389
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800390static bool type_is_sk_pointer(enum bpf_reg_type type)
391{
392 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800393 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700394 type == PTR_TO_TCP_SOCK ||
395 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800396}
397
John Fastabendcac616d2020-05-21 13:07:26 -0700398static bool reg_type_not_null(enum bpf_reg_type type)
399{
400 return type == PTR_TO_SOCKET ||
401 type == PTR_TO_TCP_SOCK ||
402 type == PTR_TO_MAP_VALUE ||
Yonghong Song01c66c42020-06-30 10:12:40 -0700403 type == PTR_TO_SOCK_COMMON;
John Fastabendcac616d2020-05-21 13:07:26 -0700404}
405
Joe Stringer840b9612018-10-02 13:35:32 -0700406static bool reg_type_may_be_null(enum bpf_reg_type type)
407{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700408 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800409 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800410 type == PTR_TO_SOCK_COMMON_OR_NULL ||
Yonghong Songb121b342020-05-09 10:59:12 -0700411 type == PTR_TO_TCP_SOCK_OR_NULL ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700412 type == PTR_TO_BTF_ID_OR_NULL ||
Yonghong Songafbf21d2020-07-23 11:41:11 -0700413 type == PTR_TO_MEM_OR_NULL ||
414 type == PTR_TO_RDONLY_BUF_OR_NULL ||
415 type == PTR_TO_RDWR_BUF_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700416}
417
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800418static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
419{
420 return reg->type == PTR_TO_MAP_VALUE &&
421 map_value_has_spin_lock(reg->map_ptr);
422}
423
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700424static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
425{
426 return type == PTR_TO_SOCKET ||
427 type == PTR_TO_SOCKET_OR_NULL ||
428 type == PTR_TO_TCP_SOCK ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700429 type == PTR_TO_TCP_SOCK_OR_NULL ||
430 type == PTR_TO_MEM ||
431 type == PTR_TO_MEM_OR_NULL;
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700432}
433
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700434static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700435{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700436 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700437}
438
439/* Determine whether the function releases some resources allocated by another
440 * function call. The first reference type argument will be assumed to be
441 * released by release_reference().
442 */
443static bool is_release_function(enum bpf_func_id func_id)
444{
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700445 return func_id == BPF_FUNC_sk_release ||
446 func_id == BPF_FUNC_ringbuf_submit ||
447 func_id == BPF_FUNC_ringbuf_discard;
Joe Stringer840b9612018-10-02 13:35:32 -0700448}
449
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200450static bool may_be_acquire_function(enum bpf_func_id func_id)
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800451{
452 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800453 func_id == BPF_FUNC_sk_lookup_udp ||
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200454 func_id == BPF_FUNC_skc_lookup_tcp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700455 func_id == BPF_FUNC_map_lookup_elem ||
456 func_id == BPF_FUNC_ringbuf_reserve;
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200457}
458
459static bool is_acquire_function(enum bpf_func_id func_id,
460 const struct bpf_map *map)
461{
462 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
463
464 if (func_id == BPF_FUNC_sk_lookup_tcp ||
465 func_id == BPF_FUNC_sk_lookup_udp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700466 func_id == BPF_FUNC_skc_lookup_tcp ||
467 func_id == BPF_FUNC_ringbuf_reserve)
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200468 return true;
469
470 if (func_id == BPF_FUNC_map_lookup_elem &&
471 (map_type == BPF_MAP_TYPE_SOCKMAP ||
472 map_type == BPF_MAP_TYPE_SOCKHASH))
473 return true;
474
475 return false;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800476}
477
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700478static bool is_ptr_cast_function(enum bpf_func_id func_id)
479{
480 return func_id == BPF_FUNC_tcp_sock ||
481 func_id == BPF_FUNC_sk_fullsock;
482}
483
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700484/* string representation of 'enum bpf_reg_type' */
485static const char * const reg_type_str[] = {
486 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100487 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700488 [PTR_TO_CTX] = "ctx",
489 [CONST_PTR_TO_MAP] = "map_ptr",
490 [PTR_TO_MAP_VALUE] = "map_value",
491 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700492 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700493 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200494 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700495 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700496 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700497 [PTR_TO_SOCKET] = "sock",
498 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800499 [PTR_TO_SOCK_COMMON] = "sock_common",
500 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800501 [PTR_TO_TCP_SOCK] = "tcp_sock",
502 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700503 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700504 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700505 [PTR_TO_BTF_ID] = "ptr_",
Yonghong Songb121b342020-05-09 10:59:12 -0700506 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700507 [PTR_TO_MEM] = "mem",
508 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
Yonghong Songafbf21d2020-07-23 11:41:11 -0700509 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
510 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
511 [PTR_TO_RDWR_BUF] = "rdwr_buf",
512 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700513};
514
Edward Cree8efea212018-08-22 20:02:44 +0100515static char slot_type_char[] = {
516 [STACK_INVALID] = '?',
517 [STACK_SPILL] = 'r',
518 [STACK_MISC] = 'm',
519 [STACK_ZERO] = '0',
520};
521
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800522static void print_liveness(struct bpf_verifier_env *env,
523 enum bpf_reg_liveness live)
524{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800525 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800526 verbose(env, "_");
527 if (live & REG_LIVE_READ)
528 verbose(env, "r");
529 if (live & REG_LIVE_WRITTEN)
530 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800531 if (live & REG_LIVE_DONE)
532 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800533}
534
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800535static struct bpf_func_state *func(struct bpf_verifier_env *env,
536 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700537{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800538 struct bpf_verifier_state *cur = env->cur_state;
539
540 return cur->frame[reg->frameno];
541}
542
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700543const char *kernel_type_name(u32 id)
544{
545 return btf_name_by_offset(btf_vmlinux,
546 btf_type_by_id(btf_vmlinux, id)->name_off);
547}
548
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800549static void print_verifier_state(struct bpf_verifier_env *env,
550 const struct bpf_func_state *state)
551{
552 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700553 enum bpf_reg_type t;
554 int i;
555
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800556 if (state->frameno)
557 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700558 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700559 reg = &state->regs[i];
560 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700561 if (t == NOT_INIT)
562 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800563 verbose(env, " R%d", i);
564 print_liveness(env, reg->live);
565 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700566 if (t == SCALAR_VALUE && reg->precise)
567 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100568 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
569 tnum_is_const(reg->var_off)) {
570 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700571 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100572 } else {
Yonghong Songb121b342020-05-09 10:59:12 -0700573 if (t == PTR_TO_BTF_ID || t == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700574 verbose(env, "%s", kernel_type_name(reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700575 verbose(env, "(id=%d", reg->id);
576 if (reg_type_may_be_refcounted_or_null(t))
577 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100578 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700579 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200580 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700581 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100582 else if (t == CONST_PTR_TO_MAP ||
583 t == PTR_TO_MAP_VALUE ||
584 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700585 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100586 reg->map_ptr->key_size,
587 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100588 if (tnum_is_const(reg->var_off)) {
589 /* Typically an immediate SCALAR_VALUE, but
590 * could be a pointer whose offset is too big
591 * for reg->off
592 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700593 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100594 } else {
595 if (reg->smin_value != reg->umin_value &&
596 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700597 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100598 (long long)reg->smin_value);
599 if (reg->smax_value != reg->umax_value &&
600 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700601 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100602 (long long)reg->smax_value);
603 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700604 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100605 (unsigned long long)reg->umin_value);
606 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700607 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100608 (unsigned long long)reg->umax_value);
609 if (!tnum_is_unknown(reg->var_off)) {
610 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100611
Edward Cree7d1238f2017-08-07 15:26:56 +0100612 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700613 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100614 }
John Fastabend3f50f132020-03-30 14:36:39 -0700615 if (reg->s32_min_value != reg->smin_value &&
616 reg->s32_min_value != S32_MIN)
617 verbose(env, ",s32_min_value=%d",
618 (int)(reg->s32_min_value));
619 if (reg->s32_max_value != reg->smax_value &&
620 reg->s32_max_value != S32_MAX)
621 verbose(env, ",s32_max_value=%d",
622 (int)(reg->s32_max_value));
623 if (reg->u32_min_value != reg->umin_value &&
624 reg->u32_min_value != U32_MIN)
625 verbose(env, ",u32_min_value=%d",
626 (int)(reg->u32_min_value));
627 if (reg->u32_max_value != reg->umax_value &&
628 reg->u32_max_value != U32_MAX)
629 verbose(env, ",u32_max_value=%d",
630 (int)(reg->u32_max_value));
Edward Creef1174f72017-08-07 15:26:19 +0100631 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700632 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100633 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700634 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700635 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100636 char types_buf[BPF_REG_SIZE + 1];
637 bool valid = false;
638 int j;
639
640 for (j = 0; j < BPF_REG_SIZE; j++) {
641 if (state->stack[i].slot_type[j] != STACK_INVALID)
642 valid = true;
643 types_buf[j] = slot_type_char[
644 state->stack[i].slot_type[j]];
645 }
646 types_buf[BPF_REG_SIZE] = 0;
647 if (!valid)
648 continue;
649 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
650 print_liveness(env, state->stack[i].spilled_ptr.live);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700651 if (state->stack[i].slot_type[0] == STACK_SPILL) {
652 reg = &state->stack[i].spilled_ptr;
653 t = reg->type;
654 verbose(env, "=%s", reg_type_str[t]);
655 if (t == SCALAR_VALUE && reg->precise)
656 verbose(env, "P");
657 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
658 verbose(env, "%lld", reg->var_off.value + reg->off);
659 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100660 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700661 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700662 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700663 if (state->acquired_refs && state->refs[0].id) {
664 verbose(env, " refs=%d", state->refs[0].id);
665 for (i = 1; i < state->acquired_refs; i++)
666 if (state->refs[i].id)
667 verbose(env, ",%d", state->refs[i].id);
668 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700669 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700670}
671
Joe Stringer84dbf352018-10-02 13:35:34 -0700672#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
673static int copy_##NAME##_state(struct bpf_func_state *dst, \
674 const struct bpf_func_state *src) \
675{ \
676 if (!src->FIELD) \
677 return 0; \
678 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
679 /* internal bug, make state invalid to reject the program */ \
680 memset(dst, 0, sizeof(*dst)); \
681 return -EFAULT; \
682 } \
683 memcpy(dst->FIELD, src->FIELD, \
684 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
685 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700686}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700687/* copy_reference_state() */
688COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700689/* copy_stack_state() */
690COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
691#undef COPY_STATE_FN
692
693#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
694static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
695 bool copy_old) \
696{ \
697 u32 old_size = state->COUNT; \
698 struct bpf_##NAME##_state *new_##FIELD; \
699 int slot = size / SIZE; \
700 \
701 if (size <= old_size || !size) { \
702 if (copy_old) \
703 return 0; \
704 state->COUNT = slot * SIZE; \
705 if (!size && old_size) { \
706 kfree(state->FIELD); \
707 state->FIELD = NULL; \
708 } \
709 return 0; \
710 } \
711 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
712 GFP_KERNEL); \
713 if (!new_##FIELD) \
714 return -ENOMEM; \
715 if (copy_old) { \
716 if (state->FIELD) \
717 memcpy(new_##FIELD, state->FIELD, \
718 sizeof(*new_##FIELD) * (old_size / SIZE)); \
719 memset(new_##FIELD + old_size / SIZE, 0, \
720 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
721 } \
722 state->COUNT = slot * SIZE; \
723 kfree(state->FIELD); \
724 state->FIELD = new_##FIELD; \
725 return 0; \
726}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700727/* realloc_reference_state() */
728REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700729/* realloc_stack_state() */
730REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
731#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700732
733/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
734 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800735 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700736 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
737 * which realloc_stack_state() copies over. It points to previous
738 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700739 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700740static int realloc_func_state(struct bpf_func_state *state, int stack_size,
741 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700742{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700743 int err = realloc_reference_state(state, refs_size, copy_old);
744 if (err)
745 return err;
746 return realloc_stack_state(state, stack_size, copy_old);
747}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700748
Joe Stringerfd978bf72018-10-02 13:35:35 -0700749/* Acquire a pointer id from the env and update the state->refs to include
750 * this new pointer reference.
751 * On success, returns a valid pointer id to associate with the register
752 * On failure, returns a negative errno.
753 */
754static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
755{
756 struct bpf_func_state *state = cur_func(env);
757 int new_ofs = state->acquired_refs;
758 int id, err;
759
760 err = realloc_reference_state(state, state->acquired_refs + 1, true);
761 if (err)
762 return err;
763 id = ++env->id_gen;
764 state->refs[new_ofs].id = id;
765 state->refs[new_ofs].insn_idx = insn_idx;
766
767 return id;
768}
769
770/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800771static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700772{
773 int i, last_idx;
774
Joe Stringerfd978bf72018-10-02 13:35:35 -0700775 last_idx = state->acquired_refs - 1;
776 for (i = 0; i < state->acquired_refs; i++) {
777 if (state->refs[i].id == ptr_id) {
778 if (last_idx && i != last_idx)
779 memcpy(&state->refs[i], &state->refs[last_idx],
780 sizeof(*state->refs));
781 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
782 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700783 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700784 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700785 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800786 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700787}
788
789static int transfer_reference_state(struct bpf_func_state *dst,
790 struct bpf_func_state *src)
791{
792 int err = realloc_reference_state(dst, src->acquired_refs, false);
793 if (err)
794 return err;
795 err = copy_reference_state(dst, src);
796 if (err)
797 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700798 return 0;
799}
800
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800801static void free_func_state(struct bpf_func_state *state)
802{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800803 if (!state)
804 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700805 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800806 kfree(state->stack);
807 kfree(state);
808}
809
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700810static void clear_jmp_history(struct bpf_verifier_state *state)
811{
812 kfree(state->jmp_history);
813 state->jmp_history = NULL;
814 state->jmp_history_cnt = 0;
815}
816
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700817static void free_verifier_state(struct bpf_verifier_state *state,
818 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700819{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800820 int i;
821
822 for (i = 0; i <= state->curframe; i++) {
823 free_func_state(state->frame[i]);
824 state->frame[i] = NULL;
825 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700826 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700827 if (free_self)
828 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700829}
830
831/* copy verifier state from src to dst growing dst stack space
832 * when necessary to accommodate larger src stack
833 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800834static int copy_func_state(struct bpf_func_state *dst,
835 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700836{
837 int err;
838
Joe Stringerfd978bf72018-10-02 13:35:35 -0700839 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
840 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700841 if (err)
842 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700843 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
844 err = copy_reference_state(dst, src);
845 if (err)
846 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700847 return copy_stack_state(dst, src);
848}
849
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800850static int copy_verifier_state(struct bpf_verifier_state *dst_state,
851 const struct bpf_verifier_state *src)
852{
853 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700854 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800855 int i, err;
856
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700857 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
858 kfree(dst_state->jmp_history);
859 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
860 if (!dst_state->jmp_history)
861 return -ENOMEM;
862 }
863 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
864 dst_state->jmp_history_cnt = src->jmp_history_cnt;
865
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800866 /* if dst has more stack frames then src frame, free them */
867 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
868 free_func_state(dst_state->frame[i]);
869 dst_state->frame[i] = NULL;
870 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100871 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800872 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800873 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700874 dst_state->branches = src->branches;
875 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700876 dst_state->first_insn_idx = src->first_insn_idx;
877 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800878 for (i = 0; i <= src->curframe; i++) {
879 dst = dst_state->frame[i];
880 if (!dst) {
881 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
882 if (!dst)
883 return -ENOMEM;
884 dst_state->frame[i] = dst;
885 }
886 err = copy_func_state(dst, src->frame[i]);
887 if (err)
888 return err;
889 }
890 return 0;
891}
892
Alexei Starovoitov25897262019-06-15 12:12:20 -0700893static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
894{
895 while (st) {
896 u32 br = --st->branches;
897
898 /* WARN_ON(br > 1) technically makes sense here,
899 * but see comment in push_stack(), hence:
900 */
901 WARN_ONCE((int)br < 0,
902 "BUG update_branch_counts:branches_to_explore=%d\n",
903 br);
904 if (br)
905 break;
906 st = st->parent;
907 }
908}
909
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700910static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700911 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700912{
913 struct bpf_verifier_state *cur = env->cur_state;
914 struct bpf_verifier_stack_elem *elem, *head = env->head;
915 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700916
917 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700918 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700919
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700920 if (cur) {
921 err = copy_verifier_state(cur, &head->st);
922 if (err)
923 return err;
924 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700925 if (pop_log)
926 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700927 if (insn_idx)
928 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700929 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700930 *prev_insn_idx = head->prev_insn_idx;
931 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700932 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700933 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700934 env->head = elem;
935 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700936 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700937}
938
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100939static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100940 int insn_idx, int prev_insn_idx,
941 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700942{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700943 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100944 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700945 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700946
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700947 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700948 if (!elem)
949 goto err;
950
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700951 elem->insn_idx = insn_idx;
952 elem->prev_insn_idx = prev_insn_idx;
953 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700954 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700955 env->head = elem;
956 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700957 err = copy_verifier_state(&elem->st, cur);
958 if (err)
959 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100960 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700961 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
962 verbose(env, "The sequence of %d jumps is too complex.\n",
963 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700964 goto err;
965 }
Alexei Starovoitov25897262019-06-15 12:12:20 -0700966 if (elem->st.parent) {
967 ++elem->st.parent->branches;
968 /* WARN_ON(branches > 2) technically makes sense here,
969 * but
970 * 1. speculative states will bump 'branches' for non-branch
971 * instructions
972 * 2. is_state_visited() heuristics may decide not to create
973 * a new state for a sequence of branches and all such current
974 * and cloned states will be pointing to a single parent state
975 * which might have large 'branches' count.
976 */
977 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700978 return &elem->st;
979err:
Alexei Starovoitov58963512018-01-08 07:51:17 -0800980 free_verifier_state(env->cur_state, true);
981 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700982 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700983 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700984 return NULL;
985}
986
987#define CALLER_SAVED_REGS 6
988static const int caller_saved[CALLER_SAVED_REGS] = {
989 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
990};
991
Daniel Borkmannf54c7892019-12-22 23:37:40 +0100992static void __mark_reg_not_init(const struct bpf_verifier_env *env,
993 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +0100994
Edward Creeb03c9f92017-08-07 15:26:36 +0100995/* Mark the unknown part of a register (variable offset or scalar value) as
996 * known to have the value @imm.
997 */
998static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
999{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001000 /* Clear id, off, and union(map_ptr, range) */
1001 memset(((u8 *)reg) + sizeof(reg->type), 0,
1002 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
Edward Creeb03c9f92017-08-07 15:26:36 +01001003 reg->var_off = tnum_const(imm);
1004 reg->smin_value = (s64)imm;
1005 reg->smax_value = (s64)imm;
1006 reg->umin_value = imm;
1007 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001008
1009 reg->s32_min_value = (s32)imm;
1010 reg->s32_max_value = (s32)imm;
1011 reg->u32_min_value = (u32)imm;
1012 reg->u32_max_value = (u32)imm;
1013}
1014
1015static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1016{
1017 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1018 reg->s32_min_value = (s32)imm;
1019 reg->s32_max_value = (s32)imm;
1020 reg->u32_min_value = (u32)imm;
1021 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001022}
1023
Edward Creef1174f72017-08-07 15:26:19 +01001024/* Mark the 'variable offset' part of a register as zero. This should be
1025 * used only on registers holding a pointer type.
1026 */
1027static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1028{
Edward Creeb03c9f92017-08-07 15:26:36 +01001029 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001030}
1031
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001032static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1033{
1034 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001035 reg->type = SCALAR_VALUE;
1036}
1037
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001038static void mark_reg_known_zero(struct bpf_verifier_env *env,
1039 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001040{
1041 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001042 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001043 /* Something bad happened, let's kill all regs */
1044 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001045 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001046 return;
1047 }
1048 __mark_reg_known_zero(regs + regno);
1049}
1050
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001051static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1052{
1053 return type_is_pkt_pointer(reg->type);
1054}
1055
1056static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1057{
1058 return reg_is_pkt_pointer(reg) ||
1059 reg->type == PTR_TO_PACKET_END;
1060}
1061
1062/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1063static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1064 enum bpf_reg_type which)
1065{
1066 /* The register can already have a range from prior markings.
1067 * This is fine as long as it hasn't been advanced from its
1068 * origin.
1069 */
1070 return reg->type == which &&
1071 reg->id == 0 &&
1072 reg->off == 0 &&
1073 tnum_equals_const(reg->var_off, 0);
1074}
1075
John Fastabend3f50f132020-03-30 14:36:39 -07001076/* Reset the min/max bounds of a register */
1077static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1078{
1079 reg->smin_value = S64_MIN;
1080 reg->smax_value = S64_MAX;
1081 reg->umin_value = 0;
1082 reg->umax_value = U64_MAX;
1083
1084 reg->s32_min_value = S32_MIN;
1085 reg->s32_max_value = S32_MAX;
1086 reg->u32_min_value = 0;
1087 reg->u32_max_value = U32_MAX;
1088}
1089
1090static void __mark_reg64_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
1098static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1099{
1100 reg->s32_min_value = S32_MIN;
1101 reg->s32_max_value = S32_MAX;
1102 reg->u32_min_value = 0;
1103 reg->u32_max_value = U32_MAX;
1104}
1105
1106static void __update_reg32_bounds(struct bpf_reg_state *reg)
1107{
1108 struct tnum var32_off = tnum_subreg(reg->var_off);
1109
1110 /* min signed is max(sign bit) | min(other bits) */
1111 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1112 var32_off.value | (var32_off.mask & S32_MIN));
1113 /* max signed is min(sign bit) | max(other bits) */
1114 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1115 var32_off.value | (var32_off.mask & S32_MAX));
1116 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1117 reg->u32_max_value = min(reg->u32_max_value,
1118 (u32)(var32_off.value | var32_off.mask));
1119}
1120
1121static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001122{
1123 /* min signed is max(sign bit) | min(other bits) */
1124 reg->smin_value = max_t(s64, reg->smin_value,
1125 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1126 /* max signed is min(sign bit) | max(other bits) */
1127 reg->smax_value = min_t(s64, reg->smax_value,
1128 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1129 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1130 reg->umax_value = min(reg->umax_value,
1131 reg->var_off.value | reg->var_off.mask);
1132}
1133
John Fastabend3f50f132020-03-30 14:36:39 -07001134static void __update_reg_bounds(struct bpf_reg_state *reg)
1135{
1136 __update_reg32_bounds(reg);
1137 __update_reg64_bounds(reg);
1138}
1139
Edward Creeb03c9f92017-08-07 15:26:36 +01001140/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001141static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1142{
1143 /* Learn sign from signed bounds.
1144 * If we cannot cross the sign boundary, then signed and unsigned bounds
1145 * are the same, so combine. This works even in the negative case, e.g.
1146 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1147 */
1148 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1149 reg->s32_min_value = reg->u32_min_value =
1150 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1151 reg->s32_max_value = reg->u32_max_value =
1152 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1153 return;
1154 }
1155 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1156 * boundary, so we must be careful.
1157 */
1158 if ((s32)reg->u32_max_value >= 0) {
1159 /* Positive. We can't learn anything from the smin, but smax
1160 * is positive, hence safe.
1161 */
1162 reg->s32_min_value = reg->u32_min_value;
1163 reg->s32_max_value = reg->u32_max_value =
1164 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1165 } else if ((s32)reg->u32_min_value < 0) {
1166 /* Negative. We can't learn anything from the smax, but smin
1167 * is negative, hence safe.
1168 */
1169 reg->s32_min_value = reg->u32_min_value =
1170 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1171 reg->s32_max_value = reg->u32_max_value;
1172 }
1173}
1174
1175static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001176{
1177 /* Learn sign from signed bounds.
1178 * If we cannot cross the sign boundary, then signed and unsigned bounds
1179 * are the same, so combine. This works even in the negative case, e.g.
1180 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1181 */
1182 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1183 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1184 reg->umin_value);
1185 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1186 reg->umax_value);
1187 return;
1188 }
1189 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1190 * boundary, so we must be careful.
1191 */
1192 if ((s64)reg->umax_value >= 0) {
1193 /* Positive. We can't learn anything from the smin, but smax
1194 * is positive, hence safe.
1195 */
1196 reg->smin_value = reg->umin_value;
1197 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1198 reg->umax_value);
1199 } else if ((s64)reg->umin_value < 0) {
1200 /* Negative. We can't learn anything from the smax, but smin
1201 * is negative, hence safe.
1202 */
1203 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1204 reg->umin_value);
1205 reg->smax_value = reg->umax_value;
1206 }
1207}
1208
John Fastabend3f50f132020-03-30 14:36:39 -07001209static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1210{
1211 __reg32_deduce_bounds(reg);
1212 __reg64_deduce_bounds(reg);
1213}
1214
Edward Creeb03c9f92017-08-07 15:26:36 +01001215/* Attempts to improve var_off based on unsigned min/max information */
1216static void __reg_bound_offset(struct bpf_reg_state *reg)
1217{
John Fastabend3f50f132020-03-30 14:36:39 -07001218 struct tnum var64_off = tnum_intersect(reg->var_off,
1219 tnum_range(reg->umin_value,
1220 reg->umax_value));
1221 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1222 tnum_range(reg->u32_min_value,
1223 reg->u32_max_value));
1224
1225 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001226}
1227
John Fastabend3f50f132020-03-30 14:36:39 -07001228static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001229{
John Fastabend3f50f132020-03-30 14:36:39 -07001230 reg->umin_value = reg->u32_min_value;
1231 reg->umax_value = reg->u32_max_value;
1232 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1233 * but must be positive otherwise set to worse case bounds
1234 * and refine later from tnum.
1235 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001236 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001237 reg->smax_value = reg->s32_max_value;
1238 else
1239 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001240 if (reg->s32_min_value >= 0)
1241 reg->smin_value = reg->s32_min_value;
1242 else
1243 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001244}
1245
1246static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1247{
1248 /* special case when 64-bit register has upper 32-bit register
1249 * zeroed. Typically happens after zext or <<32, >>32 sequence
1250 * allowing us to use 32-bit bounds directly,
1251 */
1252 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1253 __reg_assign_32_into_64(reg);
1254 } else {
1255 /* Otherwise the best we can do is push lower 32bit known and
1256 * unknown bits into register (var_off set from jmp logic)
1257 * then learn as much as possible from the 64-bit tnum
1258 * known and unknown bits. The previous smin/smax bounds are
1259 * invalid here because of jmp32 compare so mark them unknown
1260 * so they do not impact tnum bounds calculation.
1261 */
1262 __mark_reg64_unbounded(reg);
1263 __update_reg_bounds(reg);
1264 }
1265
1266 /* Intersecting with the old var_off might have improved our bounds
1267 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1268 * then new var_off is (0; 0x7f...fc) which improves our umax.
1269 */
1270 __reg_deduce_bounds(reg);
1271 __reg_bound_offset(reg);
1272 __update_reg_bounds(reg);
1273}
1274
1275static bool __reg64_bound_s32(s64 a)
1276{
1277 if (a > S32_MIN && a < S32_MAX)
1278 return true;
1279 return false;
1280}
1281
1282static bool __reg64_bound_u32(u64 a)
1283{
1284 if (a > U32_MIN && a < U32_MAX)
1285 return true;
1286 return false;
1287}
1288
1289static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1290{
1291 __mark_reg32_unbounded(reg);
1292
1293 if (__reg64_bound_s32(reg->smin_value))
1294 reg->s32_min_value = (s32)reg->smin_value;
1295 if (__reg64_bound_s32(reg->smax_value))
1296 reg->s32_max_value = (s32)reg->smax_value;
1297 if (__reg64_bound_u32(reg->umin_value))
1298 reg->u32_min_value = (u32)reg->umin_value;
1299 if (__reg64_bound_u32(reg->umax_value))
1300 reg->u32_max_value = (u32)reg->umax_value;
1301
1302 /* Intersecting with the old var_off might have improved our bounds
1303 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1304 * then new var_off is (0; 0x7f...fc) which improves our umax.
1305 */
1306 __reg_deduce_bounds(reg);
1307 __reg_bound_offset(reg);
1308 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001309}
1310
Edward Creef1174f72017-08-07 15:26:19 +01001311/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001312static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1313 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001314{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001315 /*
1316 * Clear type, id, off, and union(map_ptr, range) and
1317 * padding between 'type' and union
1318 */
1319 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001320 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001321 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001322 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001323 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001324 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001325}
1326
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001327static void mark_reg_unknown(struct bpf_verifier_env *env,
1328 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001329{
1330 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001331 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001332 /* Something bad happened, let's kill all regs except FP */
1333 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001334 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001335 return;
1336 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001337 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001338}
1339
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001340static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1341 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001342{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001343 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001344 reg->type = NOT_INIT;
1345}
1346
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001347static void mark_reg_not_init(struct bpf_verifier_env *env,
1348 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001349{
Edward Creef1174f72017-08-07 15:26:19 +01001350 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001351 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001352 /* Something bad happened, let's kill all regs except FP */
1353 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001354 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001355 return;
1356 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001357 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001358}
1359
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001360static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1361 struct bpf_reg_state *regs, u32 regno,
1362 enum bpf_reg_type reg_type, u32 btf_id)
1363{
1364 if (reg_type == SCALAR_VALUE) {
1365 mark_reg_unknown(env, regs, regno);
1366 return;
1367 }
1368 mark_reg_known_zero(env, regs, regno);
1369 regs[regno].type = PTR_TO_BTF_ID;
1370 regs[regno].btf_id = btf_id;
1371}
1372
Jiong Wang5327ed32019-05-24 23:25:12 +01001373#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001374static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001375 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001376{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001377 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001378 int i;
1379
Edward Creedc503a82017-08-15 20:34:35 +01001380 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001381 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001382 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001383 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001384 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001385 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001386
1387 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001388 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001389 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001390 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001391}
1392
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001393#define BPF_MAIN_FUNC (-1)
1394static void init_func_state(struct bpf_verifier_env *env,
1395 struct bpf_func_state *state,
1396 int callsite, int frameno, int subprogno)
1397{
1398 state->callsite = callsite;
1399 state->frameno = frameno;
1400 state->subprogno = subprogno;
1401 init_reg_state(env, state);
1402}
1403
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001404enum reg_arg_type {
1405 SRC_OP, /* register is used as source operand */
1406 DST_OP, /* register is used as destination operand */
1407 DST_OP_NO_MARK /* same as above, check only, don't mark */
1408};
1409
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001410static int cmp_subprogs(const void *a, const void *b)
1411{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001412 return ((struct bpf_subprog_info *)a)->start -
1413 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001414}
1415
1416static int find_subprog(struct bpf_verifier_env *env, int off)
1417{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001418 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001419
Jiong Wang9c8105b2018-05-02 16:17:18 -04001420 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1421 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001422 if (!p)
1423 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001424 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001425
1426}
1427
1428static int add_subprog(struct bpf_verifier_env *env, int off)
1429{
1430 int insn_cnt = env->prog->len;
1431 int ret;
1432
1433 if (off >= insn_cnt || off < 0) {
1434 verbose(env, "call to invalid destination\n");
1435 return -EINVAL;
1436 }
1437 ret = find_subprog(env, off);
1438 if (ret >= 0)
1439 return 0;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001440 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001441 verbose(env, "too many subprograms\n");
1442 return -E2BIG;
1443 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04001444 env->subprog_info[env->subprog_cnt++].start = off;
1445 sort(env->subprog_info, env->subprog_cnt,
1446 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001447 return 0;
1448}
1449
1450static int check_subprogs(struct bpf_verifier_env *env)
1451{
1452 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001453 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001454 struct bpf_insn *insn = env->prog->insnsi;
1455 int insn_cnt = env->prog->len;
1456
Jiong Wangf910cef2018-05-02 16:17:17 -04001457 /* Add entry function. */
1458 ret = add_subprog(env, 0);
1459 if (ret < 0)
1460 return ret;
1461
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001462 /* determine subprog starts. The end is one before the next starts */
1463 for (i = 0; i < insn_cnt; i++) {
1464 if (insn[i].code != (BPF_JMP | BPF_CALL))
1465 continue;
1466 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1467 continue;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001468 if (!env->bpf_capable) {
1469 verbose(env,
1470 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001471 return -EPERM;
1472 }
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001473 ret = add_subprog(env, i + insn[i].imm + 1);
1474 if (ret < 0)
1475 return ret;
1476 }
1477
Jiong Wang4cb3d992018-05-02 16:17:19 -04001478 /* Add a fake 'exit' subprog which could simplify subprog iteration
1479 * logic. 'subprog_cnt' should not be increased.
1480 */
1481 subprog[env->subprog_cnt].start = insn_cnt;
1482
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001483 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001484 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001485 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001486
1487 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001488 subprog_start = subprog[cur_subprog].start;
1489 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001490 for (i = 0; i < insn_cnt; i++) {
1491 u8 code = insn[i].code;
1492
Jiong Wang092ed092019-01-26 12:26:01 -05001493 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001494 goto next;
1495 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1496 goto next;
1497 off = i + insn[i].off + 1;
1498 if (off < subprog_start || off >= subprog_end) {
1499 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1500 return -EINVAL;
1501 }
1502next:
1503 if (i == subprog_end - 1) {
1504 /* to avoid fall-through from one subprog into another
1505 * the last insn of the subprog should be either exit
1506 * or unconditional jump back
1507 */
1508 if (code != (BPF_JMP | BPF_EXIT) &&
1509 code != (BPF_JMP | BPF_JA)) {
1510 verbose(env, "last insn is not an exit or jmp\n");
1511 return -EINVAL;
1512 }
1513 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001514 cur_subprog++;
1515 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001516 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001517 }
1518 }
1519 return 0;
1520}
1521
Edward Cree679c7822018-08-22 20:02:19 +01001522/* Parentage chain of this register (or stack slot) should take care of all
1523 * issues like callee-saved registers, stack slot allocation time, etc.
1524 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001525static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001526 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001527 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001528{
1529 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001530 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001531
1532 while (parent) {
1533 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001534 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001535 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001536 if (parent->live & REG_LIVE_DONE) {
1537 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1538 reg_type_str[parent->type],
1539 parent->var_off.value, parent->off);
1540 return -EFAULT;
1541 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001542 /* The first condition is more likely to be true than the
1543 * second, checked it first.
1544 */
1545 if ((parent->live & REG_LIVE_READ) == flag ||
1546 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001547 /* The parentage chain never changes and
1548 * this parent was already marked as LIVE_READ.
1549 * There is no need to keep walking the chain again and
1550 * keep re-marking all parents as LIVE_READ.
1551 * This case happens when the same register is read
1552 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001553 * Also, if parent has the stronger REG_LIVE_READ64 set,
1554 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001555 */
1556 break;
Edward Creedc503a82017-08-15 20:34:35 +01001557 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001558 parent->live |= flag;
1559 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1560 if (flag == REG_LIVE_READ64)
1561 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001562 state = parent;
1563 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001564 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001565 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001566 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001567
1568 if (env->longest_mark_read_walk < cnt)
1569 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001570 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001571}
1572
Jiong Wang5327ed32019-05-24 23:25:12 +01001573/* This function is supposed to be used by the following 32-bit optimization
1574 * code only. It returns TRUE if the source or destination register operates
1575 * on 64-bit, otherwise return FALSE.
1576 */
1577static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1578 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1579{
1580 u8 code, class, op;
1581
1582 code = insn->code;
1583 class = BPF_CLASS(code);
1584 op = BPF_OP(code);
1585 if (class == BPF_JMP) {
1586 /* BPF_EXIT for "main" will reach here. Return TRUE
1587 * conservatively.
1588 */
1589 if (op == BPF_EXIT)
1590 return true;
1591 if (op == BPF_CALL) {
1592 /* BPF to BPF call will reach here because of marking
1593 * caller saved clobber with DST_OP_NO_MARK for which we
1594 * don't care the register def because they are anyway
1595 * marked as NOT_INIT already.
1596 */
1597 if (insn->src_reg == BPF_PSEUDO_CALL)
1598 return false;
1599 /* Helper call will reach here because of arg type
1600 * check, conservatively return TRUE.
1601 */
1602 if (t == SRC_OP)
1603 return true;
1604
1605 return false;
1606 }
1607 }
1608
1609 if (class == BPF_ALU64 || class == BPF_JMP ||
1610 /* BPF_END always use BPF_ALU class. */
1611 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1612 return true;
1613
1614 if (class == BPF_ALU || class == BPF_JMP32)
1615 return false;
1616
1617 if (class == BPF_LDX) {
1618 if (t != SRC_OP)
1619 return BPF_SIZE(code) == BPF_DW;
1620 /* LDX source must be ptr. */
1621 return true;
1622 }
1623
1624 if (class == BPF_STX) {
1625 if (reg->type != SCALAR_VALUE)
1626 return true;
1627 return BPF_SIZE(code) == BPF_DW;
1628 }
1629
1630 if (class == BPF_LD) {
1631 u8 mode = BPF_MODE(code);
1632
1633 /* LD_IMM64 */
1634 if (mode == BPF_IMM)
1635 return true;
1636
1637 /* Both LD_IND and LD_ABS return 32-bit data. */
1638 if (t != SRC_OP)
1639 return false;
1640
1641 /* Implicit ctx ptr. */
1642 if (regno == BPF_REG_6)
1643 return true;
1644
1645 /* Explicit source could be any width. */
1646 return true;
1647 }
1648
1649 if (class == BPF_ST)
1650 /* The only source register for BPF_ST is a ptr. */
1651 return true;
1652
1653 /* Conservatively return true at default. */
1654 return true;
1655}
1656
Jiong Wangb325fbc2019-05-24 23:25:13 +01001657/* Return TRUE if INSN doesn't have explicit value define. */
1658static bool insn_no_def(struct bpf_insn *insn)
1659{
1660 u8 class = BPF_CLASS(insn->code);
1661
1662 return (class == BPF_JMP || class == BPF_JMP32 ||
1663 class == BPF_STX || class == BPF_ST);
1664}
1665
1666/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1667static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1668{
1669 if (insn_no_def(insn))
1670 return false;
1671
1672 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1673}
1674
Jiong Wang5327ed32019-05-24 23:25:12 +01001675static void mark_insn_zext(struct bpf_verifier_env *env,
1676 struct bpf_reg_state *reg)
1677{
1678 s32 def_idx = reg->subreg_def;
1679
1680 if (def_idx == DEF_NOT_SUBREG)
1681 return;
1682
1683 env->insn_aux_data[def_idx - 1].zext_dst = true;
1684 /* The dst will be zero extended, so won't be sub-register anymore. */
1685 reg->subreg_def = DEF_NOT_SUBREG;
1686}
1687
Edward Creedc503a82017-08-15 20:34:35 +01001688static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001689 enum reg_arg_type t)
1690{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001691 struct bpf_verifier_state *vstate = env->cur_state;
1692 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01001693 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01001694 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01001695 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01001696
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001697 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001698 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001699 return -EINVAL;
1700 }
1701
Jiong Wangc342dc12019-04-12 22:59:37 +01001702 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01001703 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001704 if (t == SRC_OP) {
1705 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01001706 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001707 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001708 return -EACCES;
1709 }
Edward Cree679c7822018-08-22 20:02:19 +01001710 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01001711 if (regno == BPF_REG_FP)
1712 return 0;
1713
Jiong Wang5327ed32019-05-24 23:25:12 +01001714 if (rw64)
1715 mark_insn_zext(env, reg);
1716
1717 return mark_reg_read(env, reg, reg->parent,
1718 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001719 } else {
1720 /* check whether register used as dest operand can be written to */
1721 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001722 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001723 return -EACCES;
1724 }
Jiong Wangc342dc12019-04-12 22:59:37 +01001725 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01001726 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001727 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001728 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001729 }
1730 return 0;
1731}
1732
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001733/* for any branch, call, exit record the history of jmps in the given state */
1734static int push_jmp_history(struct bpf_verifier_env *env,
1735 struct bpf_verifier_state *cur)
1736{
1737 u32 cnt = cur->jmp_history_cnt;
1738 struct bpf_idx_pair *p;
1739
1740 cnt++;
1741 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1742 if (!p)
1743 return -ENOMEM;
1744 p[cnt - 1].idx = env->insn_idx;
1745 p[cnt - 1].prev_idx = env->prev_insn_idx;
1746 cur->jmp_history = p;
1747 cur->jmp_history_cnt = cnt;
1748 return 0;
1749}
1750
1751/* Backtrack one insn at a time. If idx is not at the top of recorded
1752 * history then previous instruction came from straight line execution.
1753 */
1754static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1755 u32 *history)
1756{
1757 u32 cnt = *history;
1758
1759 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1760 i = st->jmp_history[cnt - 1].prev_idx;
1761 (*history)--;
1762 } else {
1763 i--;
1764 }
1765 return i;
1766}
1767
1768/* For given verifier state backtrack_insn() is called from the last insn to
1769 * the first insn. Its purpose is to compute a bitmask of registers and
1770 * stack slots that needs precision in the parent verifier state.
1771 */
1772static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1773 u32 *reg_mask, u64 *stack_mask)
1774{
1775 const struct bpf_insn_cbs cbs = {
1776 .cb_print = verbose,
1777 .private_data = env,
1778 };
1779 struct bpf_insn *insn = env->prog->insnsi + idx;
1780 u8 class = BPF_CLASS(insn->code);
1781 u8 opcode = BPF_OP(insn->code);
1782 u8 mode = BPF_MODE(insn->code);
1783 u32 dreg = 1u << insn->dst_reg;
1784 u32 sreg = 1u << insn->src_reg;
1785 u32 spi;
1786
1787 if (insn->code == 0)
1788 return 0;
1789 if (env->log.level & BPF_LOG_LEVEL) {
1790 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1791 verbose(env, "%d: ", idx);
1792 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1793 }
1794
1795 if (class == BPF_ALU || class == BPF_ALU64) {
1796 if (!(*reg_mask & dreg))
1797 return 0;
1798 if (opcode == BPF_MOV) {
1799 if (BPF_SRC(insn->code) == BPF_X) {
1800 /* dreg = sreg
1801 * dreg needs precision after this insn
1802 * sreg needs precision before this insn
1803 */
1804 *reg_mask &= ~dreg;
1805 *reg_mask |= sreg;
1806 } else {
1807 /* dreg = K
1808 * dreg needs precision after this insn.
1809 * Corresponding register is already marked
1810 * as precise=true in this verifier state.
1811 * No further markings in parent are necessary
1812 */
1813 *reg_mask &= ~dreg;
1814 }
1815 } else {
1816 if (BPF_SRC(insn->code) == BPF_X) {
1817 /* dreg += sreg
1818 * both dreg and sreg need precision
1819 * before this insn
1820 */
1821 *reg_mask |= sreg;
1822 } /* else dreg += K
1823 * dreg still needs precision before this insn
1824 */
1825 }
1826 } else if (class == BPF_LDX) {
1827 if (!(*reg_mask & dreg))
1828 return 0;
1829 *reg_mask &= ~dreg;
1830
1831 /* scalars can only be spilled into stack w/o losing precision.
1832 * Load from any other memory can be zero extended.
1833 * The desire to keep that precision is already indicated
1834 * by 'precise' mark in corresponding register of this state.
1835 * No further tracking necessary.
1836 */
1837 if (insn->src_reg != BPF_REG_FP)
1838 return 0;
1839 if (BPF_SIZE(insn->code) != BPF_DW)
1840 return 0;
1841
1842 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1843 * that [fp - off] slot contains scalar that needs to be
1844 * tracked with precision
1845 */
1846 spi = (-insn->off - 1) / BPF_REG_SIZE;
1847 if (spi >= 64) {
1848 verbose(env, "BUG spi %d\n", spi);
1849 WARN_ONCE(1, "verifier backtracking bug");
1850 return -EFAULT;
1851 }
1852 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001853 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001854 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001855 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001856 * to access memory. It means backtracking
1857 * encountered a case of pointer subtraction.
1858 */
1859 return -ENOTSUPP;
1860 /* scalars can only be spilled into stack */
1861 if (insn->dst_reg != BPF_REG_FP)
1862 return 0;
1863 if (BPF_SIZE(insn->code) != BPF_DW)
1864 return 0;
1865 spi = (-insn->off - 1) / BPF_REG_SIZE;
1866 if (spi >= 64) {
1867 verbose(env, "BUG spi %d\n", spi);
1868 WARN_ONCE(1, "verifier backtracking bug");
1869 return -EFAULT;
1870 }
1871 if (!(*stack_mask & (1ull << spi)))
1872 return 0;
1873 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001874 if (class == BPF_STX)
1875 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001876 } else if (class == BPF_JMP || class == BPF_JMP32) {
1877 if (opcode == BPF_CALL) {
1878 if (insn->src_reg == BPF_PSEUDO_CALL)
1879 return -ENOTSUPP;
1880 /* regular helper call sets R0 */
1881 *reg_mask &= ~1;
1882 if (*reg_mask & 0x3f) {
1883 /* if backtracing was looking for registers R1-R5
1884 * they should have been found already.
1885 */
1886 verbose(env, "BUG regs %x\n", *reg_mask);
1887 WARN_ONCE(1, "verifier backtracking bug");
1888 return -EFAULT;
1889 }
1890 } else if (opcode == BPF_EXIT) {
1891 return -ENOTSUPP;
1892 }
1893 } else if (class == BPF_LD) {
1894 if (!(*reg_mask & dreg))
1895 return 0;
1896 *reg_mask &= ~dreg;
1897 /* It's ld_imm64 or ld_abs or ld_ind.
1898 * For ld_imm64 no further tracking of precision
1899 * into parent is necessary
1900 */
1901 if (mode == BPF_IND || mode == BPF_ABS)
1902 /* to be analyzed */
1903 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001904 }
1905 return 0;
1906}
1907
1908/* the scalar precision tracking algorithm:
1909 * . at the start all registers have precise=false.
1910 * . scalar ranges are tracked as normal through alu and jmp insns.
1911 * . once precise value of the scalar register is used in:
1912 * . ptr + scalar alu
1913 * . if (scalar cond K|scalar)
1914 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1915 * backtrack through the verifier states and mark all registers and
1916 * stack slots with spilled constants that these scalar regisers
1917 * should be precise.
1918 * . during state pruning two registers (or spilled stack slots)
1919 * are equivalent if both are not precise.
1920 *
1921 * Note the verifier cannot simply walk register parentage chain,
1922 * since many different registers and stack slots could have been
1923 * used to compute single precise scalar.
1924 *
1925 * The approach of starting with precise=true for all registers and then
1926 * backtrack to mark a register as not precise when the verifier detects
1927 * that program doesn't care about specific value (e.g., when helper
1928 * takes register as ARG_ANYTHING parameter) is not safe.
1929 *
1930 * It's ok to walk single parentage chain of the verifier states.
1931 * It's possible that this backtracking will go all the way till 1st insn.
1932 * All other branches will be explored for needing precision later.
1933 *
1934 * The backtracking needs to deal with cases like:
1935 * 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)
1936 * r9 -= r8
1937 * r5 = r9
1938 * if r5 > 0x79f goto pc+7
1939 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1940 * r5 += 1
1941 * ...
1942 * call bpf_perf_event_output#25
1943 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1944 *
1945 * and this case:
1946 * r6 = 1
1947 * call foo // uses callee's r6 inside to compute r0
1948 * r0 += r6
1949 * if r0 == 0 goto
1950 *
1951 * to track above reg_mask/stack_mask needs to be independent for each frame.
1952 *
1953 * Also if parent's curframe > frame where backtracking started,
1954 * the verifier need to mark registers in both frames, otherwise callees
1955 * may incorrectly prune callers. This is similar to
1956 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1957 *
1958 * For now backtracking falls back into conservative marking.
1959 */
1960static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1961 struct bpf_verifier_state *st)
1962{
1963 struct bpf_func_state *func;
1964 struct bpf_reg_state *reg;
1965 int i, j;
1966
1967 /* big hammer: mark all scalars precise in this path.
1968 * pop_stack may still get !precise scalars.
1969 */
1970 for (; st; st = st->parent)
1971 for (i = 0; i <= st->curframe; i++) {
1972 func = st->frame[i];
1973 for (j = 0; j < BPF_REG_FP; j++) {
1974 reg = &func->regs[j];
1975 if (reg->type != SCALAR_VALUE)
1976 continue;
1977 reg->precise = true;
1978 }
1979 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1980 if (func->stack[j].slot_type[0] != STACK_SPILL)
1981 continue;
1982 reg = &func->stack[j].spilled_ptr;
1983 if (reg->type != SCALAR_VALUE)
1984 continue;
1985 reg->precise = true;
1986 }
1987 }
1988}
1989
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001990static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1991 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001992{
1993 struct bpf_verifier_state *st = env->cur_state;
1994 int first_idx = st->first_insn_idx;
1995 int last_idx = env->insn_idx;
1996 struct bpf_func_state *func;
1997 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001998 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
1999 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002000 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002001 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002002 int i, err;
2003
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002004 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002005 return 0;
2006
2007 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002008 if (regno >= 0) {
2009 reg = &func->regs[regno];
2010 if (reg->type != SCALAR_VALUE) {
2011 WARN_ONCE(1, "backtracing misuse");
2012 return -EFAULT;
2013 }
2014 if (!reg->precise)
2015 new_marks = true;
2016 else
2017 reg_mask = 0;
2018 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002019 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002020
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002021 while (spi >= 0) {
2022 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2023 stack_mask = 0;
2024 break;
2025 }
2026 reg = &func->stack[spi].spilled_ptr;
2027 if (reg->type != SCALAR_VALUE) {
2028 stack_mask = 0;
2029 break;
2030 }
2031 if (!reg->precise)
2032 new_marks = true;
2033 else
2034 stack_mask = 0;
2035 reg->precise = true;
2036 break;
2037 }
2038
2039 if (!new_marks)
2040 return 0;
2041 if (!reg_mask && !stack_mask)
2042 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002043 for (;;) {
2044 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002045 u32 history = st->jmp_history_cnt;
2046
2047 if (env->log.level & BPF_LOG_LEVEL)
2048 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2049 for (i = last_idx;;) {
2050 if (skip_first) {
2051 err = 0;
2052 skip_first = false;
2053 } else {
2054 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2055 }
2056 if (err == -ENOTSUPP) {
2057 mark_all_scalars_precise(env, st);
2058 return 0;
2059 } else if (err) {
2060 return err;
2061 }
2062 if (!reg_mask && !stack_mask)
2063 /* Found assignment(s) into tracked register in this state.
2064 * Since this state is already marked, just return.
2065 * Nothing to be tracked further in the parent state.
2066 */
2067 return 0;
2068 if (i == first_idx)
2069 break;
2070 i = get_prev_insn_idx(st, i, &history);
2071 if (i >= env->prog->len) {
2072 /* This can happen if backtracking reached insn 0
2073 * and there are still reg_mask or stack_mask
2074 * to backtrack.
2075 * It means the backtracking missed the spot where
2076 * particular register was initialized with a constant.
2077 */
2078 verbose(env, "BUG backtracking idx %d\n", i);
2079 WARN_ONCE(1, "verifier backtracking bug");
2080 return -EFAULT;
2081 }
2082 }
2083 st = st->parent;
2084 if (!st)
2085 break;
2086
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002087 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002088 func = st->frame[st->curframe];
2089 bitmap_from_u64(mask, reg_mask);
2090 for_each_set_bit(i, mask, 32) {
2091 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002092 if (reg->type != SCALAR_VALUE) {
2093 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002094 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002095 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002096 if (!reg->precise)
2097 new_marks = true;
2098 reg->precise = true;
2099 }
2100
2101 bitmap_from_u64(mask, stack_mask);
2102 for_each_set_bit(i, mask, 64) {
2103 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002104 /* the sequence of instructions:
2105 * 2: (bf) r3 = r10
2106 * 3: (7b) *(u64 *)(r3 -8) = r0
2107 * 4: (79) r4 = *(u64 *)(r10 -8)
2108 * doesn't contain jmps. It's backtracked
2109 * as a single block.
2110 * During backtracking insn 3 is not recognized as
2111 * stack access, so at the end of backtracking
2112 * stack slot fp-8 is still marked in stack_mask.
2113 * However the parent state may not have accessed
2114 * fp-8 and it's "unallocated" stack space.
2115 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002116 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002117 mark_all_scalars_precise(env, st);
2118 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002119 }
2120
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002121 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2122 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002123 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002124 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002125 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002126 if (reg->type != SCALAR_VALUE) {
2127 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002128 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002129 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002130 if (!reg->precise)
2131 new_marks = true;
2132 reg->precise = true;
2133 }
2134 if (env->log.level & BPF_LOG_LEVEL) {
2135 print_verifier_state(env, func);
2136 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2137 new_marks ? "didn't have" : "already had",
2138 reg_mask, stack_mask);
2139 }
2140
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002141 if (!reg_mask && !stack_mask)
2142 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002143 if (!new_marks)
2144 break;
2145
2146 last_idx = st->last_insn_idx;
2147 first_idx = st->first_insn_idx;
2148 }
2149 return 0;
2150}
2151
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002152static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2153{
2154 return __mark_chain_precision(env, regno, -1);
2155}
2156
2157static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2158{
2159 return __mark_chain_precision(env, -1, spi);
2160}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002161
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002162static bool is_spillable_regtype(enum bpf_reg_type type)
2163{
2164 switch (type) {
2165 case PTR_TO_MAP_VALUE:
2166 case PTR_TO_MAP_VALUE_OR_NULL:
2167 case PTR_TO_STACK:
2168 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002169 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002170 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002171 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002172 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002173 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002174 case PTR_TO_SOCKET:
2175 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002176 case PTR_TO_SOCK_COMMON:
2177 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002178 case PTR_TO_TCP_SOCK:
2179 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002180 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002181 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002182 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002183 case PTR_TO_RDONLY_BUF:
2184 case PTR_TO_RDONLY_BUF_OR_NULL:
2185 case PTR_TO_RDWR_BUF:
2186 case PTR_TO_RDWR_BUF_OR_NULL:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002187 return true;
2188 default:
2189 return false;
2190 }
2191}
2192
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002193/* Does this register contain a constant zero? */
2194static bool register_is_null(struct bpf_reg_state *reg)
2195{
2196 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2197}
2198
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002199static bool register_is_const(struct bpf_reg_state *reg)
2200{
2201 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2202}
2203
Jann Horn6e7e63c2020-04-17 02:00:06 +02002204static bool __is_pointer_value(bool allow_ptr_leaks,
2205 const struct bpf_reg_state *reg)
2206{
2207 if (allow_ptr_leaks)
2208 return false;
2209
2210 return reg->type != SCALAR_VALUE;
2211}
2212
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002213static void save_register_state(struct bpf_func_state *state,
2214 int spi, struct bpf_reg_state *reg)
2215{
2216 int i;
2217
2218 state->stack[spi].spilled_ptr = *reg;
2219 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2220
2221 for (i = 0; i < BPF_REG_SIZE; i++)
2222 state->stack[spi].slot_type[i] = STACK_SPILL;
2223}
2224
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002225/* check_stack_read/write functions track spill/fill of registers,
2226 * stack boundary and alignment are checked in check_mem_access()
2227 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002228static int check_stack_write(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002229 struct bpf_func_state *state, /* func where register points to */
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002230 int off, int size, int value_regno, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002231{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002232 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002233 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002234 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002235 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002236
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002237 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07002238 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002239 if (err)
2240 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002241 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2242 * so it's aligned access and [off, off + size) are within stack limits
2243 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002244 if (!env->allow_ptr_leaks &&
2245 state->stack[spi].slot_type[0] == STACK_SPILL &&
2246 size != BPF_REG_SIZE) {
2247 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2248 return -EACCES;
2249 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002250
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002251 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002252 if (value_regno >= 0)
2253 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002254
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002255 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002256 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002257 if (dst_reg != BPF_REG_FP) {
2258 /* The backtracking logic can only recognize explicit
2259 * stack slot address like [fp - 8]. Other spill of
2260 * scalar via different register has to be conervative.
2261 * Backtrack from here and mark all registers as precise
2262 * that contributed into 'reg' being a constant.
2263 */
2264 err = mark_chain_precision(env, value_regno);
2265 if (err)
2266 return err;
2267 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002268 save_register_state(state, spi, reg);
2269 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002270 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002271 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002272 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002273 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002274 return -EACCES;
2275 }
2276
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002277 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002278 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2279 return -EINVAL;
2280 }
2281
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002282 if (!env->bypass_spec_v4) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002283 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002284
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002285 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2286 register_is_const(&state->stack[spi].spilled_ptr))
2287 sanitize = true;
2288 for (i = 0; i < BPF_REG_SIZE; i++)
2289 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2290 sanitize = true;
2291 break;
2292 }
2293 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002294 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2295 int soff = (-spi - 1) * BPF_REG_SIZE;
2296
2297 /* detected reuse of integer stack slot with a pointer
2298 * which means either llvm is reusing stack slot or
2299 * an attacker is trying to exploit CVE-2018-3639
2300 * (speculative store bypass)
2301 * Have to sanitize that slot with preemptive
2302 * store of zero.
2303 */
2304 if (*poff && *poff != soff) {
2305 /* disallow programs where single insn stores
2306 * into two different stack slots, since verifier
2307 * cannot sanitize them
2308 */
2309 verbose(env,
2310 "insn %d cannot access two stack slots fp%d and fp%d",
2311 insn_idx, *poff, soff);
2312 return -EINVAL;
2313 }
2314 *poff = soff;
2315 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002316 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002317 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002318 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002319 u8 type = STACK_MISC;
2320
Edward Cree679c7822018-08-22 20:02:19 +01002321 /* regular write of data into stack destroys any spilled ptr */
2322 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002323 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2324 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2325 for (i = 0; i < BPF_REG_SIZE; i++)
2326 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002327
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002328 /* only mark the slot as written if all 8 bytes were written
2329 * otherwise read propagation may incorrectly stop too soon
2330 * when stack slots are partially written.
2331 * This heuristic means that read propagation will be
2332 * conservative, since it will add reg_live_read marks
2333 * to stack slots all the way to first state when programs
2334 * writes+reads less than 8 bytes
2335 */
2336 if (size == BPF_REG_SIZE)
2337 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2338
2339 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002340 if (reg && register_is_null(reg)) {
2341 /* backtracking doesn't work for STACK_ZERO yet. */
2342 err = mark_chain_precision(env, value_regno);
2343 if (err)
2344 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002345 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002346 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002347
Jiong Wang0bae2d42018-12-15 03:34:40 -05002348 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002349 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002350 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002351 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002352 }
2353 return 0;
2354}
2355
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002356static int check_stack_read(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002357 struct bpf_func_state *reg_state /* func where register points to */,
2358 int off, int size, int value_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002359{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002360 struct bpf_verifier_state *vstate = env->cur_state;
2361 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002362 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002363 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002364 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002365
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002366 if (reg_state->allocated_stack <= slot) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002367 verbose(env, "invalid read from stack off %d+0 size %d\n",
2368 off, size);
2369 return -EACCES;
2370 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002371 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002372 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002373
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002374 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002375 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002376 if (reg->type != SCALAR_VALUE) {
2377 verbose_linfo(env, env->insn_idx, "; ");
2378 verbose(env, "invalid size of register fill\n");
2379 return -EACCES;
2380 }
2381 if (value_regno >= 0) {
2382 mark_reg_unknown(env, state->regs, value_regno);
2383 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2384 }
2385 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2386 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002387 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002388 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002389 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002390 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002391 return -EACCES;
2392 }
2393 }
2394
Edward Creedc503a82017-08-15 20:34:35 +01002395 if (value_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002396 /* restore register state from stack */
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002397 state->regs[value_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002398 /* mark reg as written since spilled pointer state likely
2399 * has its liveness marks cleared by is_state_visited()
2400 * which resets stack/reg liveness for state transitions
2401 */
2402 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02002403 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2404 /* If value_regno==-1, the caller is asking us whether
2405 * it is acceptable to use this value as a SCALAR_VALUE
2406 * (e.g. for XADD).
2407 * We must not allow unprivileged callers to do that
2408 * with spilled pointers.
2409 */
2410 verbose(env, "leaking pointer from stack off %d\n",
2411 off);
2412 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01002413 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002414 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002415 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002416 int zeros = 0;
2417
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002418 for (i = 0; i < size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002419 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2420 continue;
2421 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2422 zeros++;
2423 continue;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002424 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002425 verbose(env, "invalid read from stack off %d+%d size %d\n",
2426 off, i, size);
2427 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002428 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002429 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002430 if (value_regno >= 0) {
2431 if (zeros == size) {
2432 /* any size read into register is zero extended,
2433 * so the whole register == const_zero
2434 */
2435 __mark_reg_const_zero(&state->regs[value_regno]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002436 /* backtracking doesn't support STACK_ZERO yet,
2437 * so mark it precise here, so that later
2438 * backtracking can stop here.
2439 * Backtracking may not need this if this register
2440 * doesn't participate in pointer adjustment.
2441 * Forward propagation of precise flag is not
2442 * necessary either. This mark is only to stop
2443 * backtracking. Any register that contributed
2444 * to const 0 was marked precise before spill.
2445 */
2446 state->regs[value_regno].precise = true;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002447 } else {
2448 /* have read misc data from the stack */
2449 mark_reg_unknown(env, state->regs, value_regno);
2450 }
2451 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2452 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002453 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002454 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002455}
2456
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002457static int check_stack_access(struct bpf_verifier_env *env,
2458 const struct bpf_reg_state *reg,
2459 int off, int size)
2460{
2461 /* Stack accesses must be at a fixed offset, so that we
2462 * can determine what type of data were returned. See
2463 * check_stack_read().
2464 */
2465 if (!tnum_is_const(reg->var_off)) {
2466 char tn_buf[48];
2467
2468 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrey Ignatov1fbd20f2019-04-03 23:22:43 -07002469 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002470 tn_buf, off, size);
2471 return -EACCES;
2472 }
2473
2474 if (off >= 0 || off < -MAX_BPF_STACK) {
2475 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2476 return -EACCES;
2477 }
2478
2479 return 0;
2480}
2481
Daniel Borkmann591fe982019-04-09 23:20:05 +02002482static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2483 int off, int size, enum bpf_access_type type)
2484{
2485 struct bpf_reg_state *regs = cur_regs(env);
2486 struct bpf_map *map = regs[regno].map_ptr;
2487 u32 cap = bpf_map_flags_to_cap(map);
2488
2489 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2490 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2491 map->value_size, off, size);
2492 return -EACCES;
2493 }
2494
2495 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2496 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2497 map->value_size, off, size);
2498 return -EACCES;
2499 }
2500
2501 return 0;
2502}
2503
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002504/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2505static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2506 int off, int size, u32 mem_size,
2507 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002508{
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002509 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2510 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002511
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002512 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2513 return 0;
2514
2515 reg = &cur_regs(env)[regno];
2516 switch (reg->type) {
2517 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002518 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002519 mem_size, off, size);
2520 break;
2521 case PTR_TO_PACKET:
2522 case PTR_TO_PACKET_META:
2523 case PTR_TO_PACKET_END:
2524 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2525 off, size, regno, reg->id, off, mem_size);
2526 break;
2527 case PTR_TO_MEM:
2528 default:
2529 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2530 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002531 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002532
2533 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002534}
2535
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002536/* check read/write into a memory region with possible variable offset */
2537static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2538 int off, int size, u32 mem_size,
2539 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002540{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002541 struct bpf_verifier_state *vstate = env->cur_state;
2542 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002543 struct bpf_reg_state *reg = &state->regs[regno];
2544 int err;
2545
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002546 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01002547 * need to try adding each of min_value and max_value to off
2548 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002549 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002550 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002551 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002552
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002553 /* The minimum value is only important with signed
2554 * comparisons where we can't assume the floor of a
2555 * value is 0. If we are using signed variables for our
2556 * index'es we need to make sure that whatever we use
2557 * will have a set floor within our range.
2558 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002559 if (reg->smin_value < 0 &&
2560 (reg->smin_value == S64_MIN ||
2561 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2562 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002563 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 -08002564 regno);
2565 return -EACCES;
2566 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002567 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2568 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002569 if (err) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002570 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002571 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002572 return err;
2573 }
2574
Edward Creeb03c9f92017-08-07 15:26:36 +01002575 /* If we haven't set a max value then we need to bail since we can't be
2576 * sure we won't do bad things.
2577 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002578 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002579 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002580 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002581 regno);
2582 return -EACCES;
2583 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002584 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2585 mem_size, zero_size_allowed);
2586 if (err) {
2587 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002588 regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002589 return err;
2590 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002591
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002592 return 0;
2593}
2594
2595/* check read/write into a map element with possible variable offset */
2596static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2597 int off, int size, bool zero_size_allowed)
2598{
2599 struct bpf_verifier_state *vstate = env->cur_state;
2600 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2601 struct bpf_reg_state *reg = &state->regs[regno];
2602 struct bpf_map *map = reg->map_ptr;
2603 int err;
2604
2605 err = check_mem_region_access(env, regno, off, size, map->value_size,
2606 zero_size_allowed);
2607 if (err)
2608 return err;
2609
2610 if (map_value_has_spin_lock(map)) {
2611 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002612
2613 /* if any part of struct bpf_spin_lock can be touched by
2614 * load/store reject this program.
2615 * To check that [x1, x2) overlaps with [y1, y2)
2616 * it is sufficient to check x1 < y2 && y1 < x2.
2617 */
2618 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2619 lock < reg->umax_value + off + size) {
2620 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2621 return -EACCES;
2622 }
2623 }
Edward Creef1174f72017-08-07 15:26:19 +01002624 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002625}
2626
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002627#define MAX_PACKET_OFF 0xffff
2628
Udip Pant7e407812020-08-25 16:20:00 -07002629static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2630{
2631 return prog->aux->linked_prog ? prog->aux->linked_prog->type
2632 : prog->type;
2633}
2634
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01002635static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002636 const struct bpf_call_arg_meta *meta,
2637 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002638{
Udip Pant7e407812020-08-25 16:20:00 -07002639 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2640
2641 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002642 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002643 case BPF_PROG_TYPE_LWT_IN:
2644 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01002645 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07002646 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002647 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02002648 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002649 if (t == BPF_WRITE)
2650 return false;
Alexander Alemayhu7e57fbb2017-02-14 00:02:35 +01002651 /* fallthrough */
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002652
2653 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002654 case BPF_PROG_TYPE_SCHED_CLS:
2655 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002656 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002657 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07002658 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07002659 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002660 if (meta)
2661 return meta->pkt_access;
2662
2663 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002664 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07002665
2666 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2667 if (t == BPF_WRITE)
2668 env->seen_direct_write = true;
2669
2670 return true;
2671
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002672 default:
2673 return false;
2674 }
2675}
2676
Edward Creef1174f72017-08-07 15:26:19 +01002677static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002678 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01002679{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002680 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01002681 struct bpf_reg_state *reg = &regs[regno];
2682 int err;
2683
2684 /* We may have added a variable offset to the packet pointer; but any
2685 * reg->range we have comes after that. We are only checking the fixed
2686 * offset.
2687 */
2688
2689 /* We don't allow negative numbers, because we aren't tracking enough
2690 * detail to prove they're safe.
2691 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002692 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002693 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 +01002694 regno);
2695 return -EACCES;
2696 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002697 err = __check_mem_access(env, regno, off, size, reg->range,
2698 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01002699 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002700 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01002701 return err;
2702 }
Jiong Wange6478152018-11-08 04:08:42 -05002703
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002704 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05002705 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2706 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002707 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05002708 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2709 */
2710 env->prog->aux->max_pkt_offset =
2711 max_t(u32, env->prog->aux->max_pkt_offset,
2712 off + reg->umax_value + size - 1);
2713
Edward Creef1174f72017-08-07 15:26:19 +01002714 return err;
2715}
2716
2717/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07002718static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002719 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2720 u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002721{
Daniel Borkmannf96da092017-07-02 02:13:27 +02002722 struct bpf_insn_access_aux info = {
2723 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002724 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02002725 };
Yonghong Song31fd8582017-06-13 15:52:13 -07002726
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07002727 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07002728 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02002729 /* A non zero info.ctx_field_size indicates that this field is a
2730 * candidate for later verifier transformation to load the whole
2731 * field and then apply a mask when accessed with a narrower
2732 * access than actual ctx access size. A zero info.ctx_field_size
2733 * will only allow for whole field access and rejects any other
2734 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07002735 */
Yonghong Song23994632017-06-22 15:07:39 -07002736 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07002737
Yonghong Songb121b342020-05-09 10:59:12 -07002738 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002739 *btf_id = info.btf_id;
2740 else
2741 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002742 /* remember the offset of last byte accessed in ctx */
2743 if (env->prog->aux->max_ctx_offset < off + size)
2744 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002745 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002746 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002747
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002748 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002749 return -EACCES;
2750}
2751
Petar Penkovd58e4682018-09-14 07:46:18 -07002752static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2753 int size)
2754{
2755 if (size < 0 || off < 0 ||
2756 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2757 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2758 off, size);
2759 return -EACCES;
2760 }
2761 return 0;
2762}
2763
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002764static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2765 u32 regno, int off, int size,
2766 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07002767{
2768 struct bpf_reg_state *regs = cur_regs(env);
2769 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002770 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002771 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07002772
2773 if (reg->smin_value < 0) {
2774 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2775 regno);
2776 return -EACCES;
2777 }
2778
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002779 switch (reg->type) {
2780 case PTR_TO_SOCK_COMMON:
2781 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2782 break;
2783 case PTR_TO_SOCKET:
2784 valid = bpf_sock_is_valid_access(off, size, t, &info);
2785 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002786 case PTR_TO_TCP_SOCK:
2787 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2788 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002789 case PTR_TO_XDP_SOCK:
2790 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2791 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002792 default:
2793 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07002794 }
2795
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002796
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002797 if (valid) {
2798 env->insn_aux_data[insn_idx].ctx_field_size =
2799 info.ctx_field_size;
2800 return 0;
2801 }
2802
2803 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2804 regno, reg_type_str[reg->type], off, size);
2805
2806 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07002807}
2808
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002809static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2810{
2811 return cur_regs(env) + regno;
2812}
2813
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002814static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2815{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002816 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002817}
2818
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002819static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2820{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002821 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002822
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002823 return reg->type == PTR_TO_CTX;
2824}
2825
2826static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2827{
2828 const struct bpf_reg_state *reg = reg_state(env, regno);
2829
2830 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002831}
2832
Daniel Borkmannca369602018-02-23 22:29:05 +01002833static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2834{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002835 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01002836
2837 return type_is_pkt_pointer(reg->type);
2838}
2839
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02002840static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2841{
2842 const struct bpf_reg_state *reg = reg_state(env, regno);
2843
2844 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2845 return reg->type == PTR_TO_FLOW_KEYS;
2846}
2847
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002848static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2849 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07002850 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002851{
Edward Creef1174f72017-08-07 15:26:19 +01002852 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07002853 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07002854
2855 /* Byte size accesses are always allowed. */
2856 if (!strict || size == 1)
2857 return 0;
2858
David S. Millere4eda882017-05-22 12:27:07 -04002859 /* For platforms that do not have a Kconfig enabling
2860 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2861 * NET_IP_ALIGN is universally set to '2'. And on platforms
2862 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2863 * to this code only in strict mode where we want to emulate
2864 * the NET_IP_ALIGN==2 checking. Therefore use an
2865 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07002866 */
David S. Millere4eda882017-05-22 12:27:07 -04002867 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01002868
2869 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2870 if (!tnum_is_aligned(reg_off, size)) {
2871 char tn_buf[48];
2872
2873 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002874 verbose(env,
2875 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002876 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002877 return -EACCES;
2878 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002879
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002880 return 0;
2881}
2882
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002883static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2884 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01002885 const char *pointer_desc,
2886 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002887{
Edward Creef1174f72017-08-07 15:26:19 +01002888 struct tnum reg_off;
2889
2890 /* Byte size accesses are always allowed. */
2891 if (!strict || size == 1)
2892 return 0;
2893
2894 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2895 if (!tnum_is_aligned(reg_off, size)) {
2896 char tn_buf[48];
2897
2898 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002899 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002900 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002901 return -EACCES;
2902 }
2903
2904 return 0;
2905}
2906
David S. Millere07b98d2017-05-10 11:38:07 -07002907static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01002908 const struct bpf_reg_state *reg, int off,
2909 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002910{
Daniel Borkmannca369602018-02-23 22:29:05 +01002911 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01002912 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07002913
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002914 switch (reg->type) {
2915 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002916 case PTR_TO_PACKET_META:
2917 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2918 * right in front, treat it the very same way.
2919 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002920 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07002921 case PTR_TO_FLOW_KEYS:
2922 pointer_desc = "flow keys ";
2923 break;
Edward Creef1174f72017-08-07 15:26:19 +01002924 case PTR_TO_MAP_VALUE:
2925 pointer_desc = "value ";
2926 break;
2927 case PTR_TO_CTX:
2928 pointer_desc = "context ";
2929 break;
2930 case PTR_TO_STACK:
2931 pointer_desc = "stack ";
Jann Horna5ec6ae2017-12-18 20:11:58 -08002932 /* The stack spill tracking logic in check_stack_write()
2933 * and check_stack_read() relies on stack accesses being
2934 * aligned.
2935 */
2936 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01002937 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07002938 case PTR_TO_SOCKET:
2939 pointer_desc = "sock ";
2940 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002941 case PTR_TO_SOCK_COMMON:
2942 pointer_desc = "sock_common ";
2943 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002944 case PTR_TO_TCP_SOCK:
2945 pointer_desc = "tcp_sock ";
2946 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002947 case PTR_TO_XDP_SOCK:
2948 pointer_desc = "xdp_sock ";
2949 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002950 default:
Edward Creef1174f72017-08-07 15:26:19 +01002951 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002952 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002953 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2954 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002955}
2956
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002957static int update_stack_depth(struct bpf_verifier_env *env,
2958 const struct bpf_func_state *func,
2959 int off)
2960{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002961 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002962
2963 if (stack >= -off)
2964 return 0;
2965
2966 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04002967 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002968 return 0;
2969}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002970
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002971/* starting from main bpf function walk all instructions of the function
2972 * and recursively walk all callees that given function can call.
2973 * Ignore jump and exit insns.
2974 * Since recursion is prevented by check_cfg() this algorithm
2975 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2976 */
2977static int check_max_stack_depth(struct bpf_verifier_env *env)
2978{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002979 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2980 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002981 struct bpf_insn *insn = env->prog->insnsi;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002982 int ret_insn[MAX_CALL_FRAMES];
2983 int ret_prog[MAX_CALL_FRAMES];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002984
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002985process_func:
2986 /* round up to 32-bytes, since this is granularity
2987 * of interpreter stack size
2988 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04002989 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002990 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002991 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002992 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002993 return -EACCES;
2994 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002995continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04002996 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002997 for (; i < subprog_end; i++) {
2998 if (insn[i].code != (BPF_JMP | BPF_CALL))
2999 continue;
3000 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3001 continue;
3002 /* remember insn and function to return to */
3003 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003004 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003005
3006 /* find the callee */
3007 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003008 idx = find_subprog(env, i);
3009 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003010 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3011 i);
3012 return -EFAULT;
3013 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003014 frame++;
3015 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003016 verbose(env, "the call stack of %d frames is too deep !\n",
3017 frame);
3018 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003019 }
3020 goto process_func;
3021 }
3022 /* end of for() loop means the last insn of the 'subprog'
3023 * was reached. Doesn't matter whether it was JA or EXIT
3024 */
3025 if (frame == 0)
3026 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003027 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003028 frame--;
3029 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003030 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003031 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003032}
3033
David S. Miller19d28fb2018-01-11 21:27:54 -05003034#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003035static int get_callee_stack_depth(struct bpf_verifier_env *env,
3036 const struct bpf_insn *insn, int idx)
3037{
3038 int start = idx + insn->imm + 1, subprog;
3039
3040 subprog = find_subprog(env, start);
3041 if (subprog < 0) {
3042 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3043 start);
3044 return -EFAULT;
3045 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04003046 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003047}
David S. Miller19d28fb2018-01-11 21:27:54 -05003048#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003049
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003050int check_ctx_reg(struct bpf_verifier_env *env,
3051 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02003052{
3053 /* Access to ctx or passing it to a helper is only allowed in
3054 * its original, unmodified form.
3055 */
3056
3057 if (reg->off) {
3058 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3059 regno, reg->off);
3060 return -EACCES;
3061 }
3062
3063 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3064 char tn_buf[48];
3065
3066 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3067 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3068 return -EACCES;
3069 }
3070
3071 return 0;
3072}
3073
Yonghong Songafbf21d2020-07-23 11:41:11 -07003074static int __check_buffer_access(struct bpf_verifier_env *env,
3075 const char *buf_info,
3076 const struct bpf_reg_state *reg,
3077 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07003078{
3079 if (off < 0) {
3080 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003081 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003082 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07003083 return -EACCES;
3084 }
3085 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3086 char tn_buf[48];
3087
3088 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3089 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003090 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07003091 regno, off, tn_buf);
3092 return -EACCES;
3093 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07003094
3095 return 0;
3096}
3097
3098static int check_tp_buffer_access(struct bpf_verifier_env *env,
3099 const struct bpf_reg_state *reg,
3100 int regno, int off, int size)
3101{
3102 int err;
3103
3104 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3105 if (err)
3106 return err;
3107
Matt Mullins9df1c282019-04-26 11:49:47 -07003108 if (off + size > env->prog->aux->max_tp_access)
3109 env->prog->aux->max_tp_access = off + size;
3110
3111 return 0;
3112}
3113
Yonghong Songafbf21d2020-07-23 11:41:11 -07003114static int check_buffer_access(struct bpf_verifier_env *env,
3115 const struct bpf_reg_state *reg,
3116 int regno, int off, int size,
3117 bool zero_size_allowed,
3118 const char *buf_info,
3119 u32 *max_access)
3120{
3121 int err;
3122
3123 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3124 if (err)
3125 return err;
3126
3127 if (off + size > *max_access)
3128 *max_access = off + size;
3129
3130 return 0;
3131}
3132
John Fastabend3f50f132020-03-30 14:36:39 -07003133/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3134static void zext_32_to_64(struct bpf_reg_state *reg)
3135{
3136 reg->var_off = tnum_subreg(reg->var_off);
3137 __reg_assign_32_into_64(reg);
3138}
Matt Mullins9df1c282019-04-26 11:49:47 -07003139
Jann Horn0c17d1d2017-12-18 20:11:55 -08003140/* truncate register to smaller size (in bytes)
3141 * must be called with size < BPF_REG_SIZE
3142 */
3143static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3144{
3145 u64 mask;
3146
3147 /* clear high bits in bit representation */
3148 reg->var_off = tnum_cast(reg->var_off, size);
3149
3150 /* fix arithmetic bounds */
3151 mask = ((u64)1 << (size * 8)) - 1;
3152 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3153 reg->umin_value &= mask;
3154 reg->umax_value &= mask;
3155 } else {
3156 reg->umin_value = 0;
3157 reg->umax_value = mask;
3158 }
3159 reg->smin_value = reg->umin_value;
3160 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07003161
3162 /* If size is smaller than 32bit register the 32bit register
3163 * values are also truncated so we push 64-bit bounds into
3164 * 32-bit bounds. Above were truncated < 32-bits already.
3165 */
3166 if (size >= 4)
3167 return;
3168 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08003169}
3170
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003171static bool bpf_map_is_rdonly(const struct bpf_map *map)
3172{
3173 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3174}
3175
3176static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3177{
3178 void *ptr;
3179 u64 addr;
3180 int err;
3181
3182 err = map->ops->map_direct_value_addr(map, &addr, off);
3183 if (err)
3184 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07003185 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003186
3187 switch (size) {
3188 case sizeof(u8):
3189 *val = (u64)*(u8 *)ptr;
3190 break;
3191 case sizeof(u16):
3192 *val = (u64)*(u16 *)ptr;
3193 break;
3194 case sizeof(u32):
3195 *val = (u64)*(u32 *)ptr;
3196 break;
3197 case sizeof(u64):
3198 *val = *(u64 *)ptr;
3199 break;
3200 default:
3201 return -EINVAL;
3202 }
3203 return 0;
3204}
3205
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003206static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3207 struct bpf_reg_state *regs,
3208 int regno, int off, int size,
3209 enum bpf_access_type atype,
3210 int value_regno)
3211{
3212 struct bpf_reg_state *reg = regs + regno;
3213 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3214 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3215 u32 btf_id;
3216 int ret;
3217
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003218 if (off < 0) {
3219 verbose(env,
3220 "R%d is ptr_%s invalid negative access: off=%d\n",
3221 regno, tname, off);
3222 return -EACCES;
3223 }
3224 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3225 char tn_buf[48];
3226
3227 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3228 verbose(env,
3229 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3230 regno, tname, off, tn_buf);
3231 return -EACCES;
3232 }
3233
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003234 if (env->ops->btf_struct_access) {
3235 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3236 atype, &btf_id);
3237 } else {
3238 if (atype != BPF_READ) {
3239 verbose(env, "only read is supported\n");
3240 return -EACCES;
3241 }
3242
3243 ret = btf_struct_access(&env->log, t, off, size, atype,
3244 &btf_id);
3245 }
3246
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003247 if (ret < 0)
3248 return ret;
3249
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003250 if (atype == BPF_READ && value_regno >= 0)
3251 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003252
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003253 return 0;
3254}
3255
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003256static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3257 struct bpf_reg_state *regs,
3258 int regno, int off, int size,
3259 enum bpf_access_type atype,
3260 int value_regno)
3261{
3262 struct bpf_reg_state *reg = regs + regno;
3263 struct bpf_map *map = reg->map_ptr;
3264 const struct btf_type *t;
3265 const char *tname;
3266 u32 btf_id;
3267 int ret;
3268
3269 if (!btf_vmlinux) {
3270 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3271 return -ENOTSUPP;
3272 }
3273
3274 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3275 verbose(env, "map_ptr access not supported for map type %d\n",
3276 map->map_type);
3277 return -ENOTSUPP;
3278 }
3279
3280 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3281 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3282
3283 if (!env->allow_ptr_to_map_access) {
3284 verbose(env,
3285 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3286 tname);
3287 return -EPERM;
3288 }
3289
3290 if (off < 0) {
3291 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3292 regno, tname, off);
3293 return -EACCES;
3294 }
3295
3296 if (atype != BPF_READ) {
3297 verbose(env, "only read from %s is supported\n", tname);
3298 return -EACCES;
3299 }
3300
3301 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3302 if (ret < 0)
3303 return ret;
3304
3305 if (value_regno >= 0)
3306 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3307
3308 return 0;
3309}
3310
3311
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003312/* check whether memory at (regno + off) is accessible for t = (read | write)
3313 * if t==write, value_regno is a register which value is stored into memory
3314 * if t==read, value_regno is a register which will receive the value from memory
3315 * if t==write && value_regno==-1, some unknown value is stored into memory
3316 * if t==read && value_regno==-1, don't care what we read from memory
3317 */
Daniel Borkmannca369602018-02-23 22:29:05 +01003318static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3319 int off, int bpf_size, enum bpf_access_type t,
3320 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003321{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003322 struct bpf_reg_state *regs = cur_regs(env);
3323 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003324 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003325 int size, err = 0;
3326
3327 size = bpf_size_to_bytes(bpf_size);
3328 if (size < 0)
3329 return size;
3330
Edward Creef1174f72017-08-07 15:26:19 +01003331 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01003332 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003333 if (err)
3334 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003335
Edward Creef1174f72017-08-07 15:26:19 +01003336 /* for access checks, reg->off is just part of off */
3337 off += reg->off;
3338
3339 if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003340 if (t == BPF_WRITE && value_regno >= 0 &&
3341 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003342 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003343 return -EACCES;
3344 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02003345 err = check_map_access_type(env, regno, off, size, t);
3346 if (err)
3347 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003348 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003349 if (!err && t == BPF_READ && value_regno >= 0) {
3350 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003351
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003352 /* if map is read-only, track its contents as scalars */
3353 if (tnum_is_const(reg->var_off) &&
3354 bpf_map_is_rdonly(map) &&
3355 map->ops->map_direct_value_addr) {
3356 int map_off = off + reg->var_off.value;
3357 u64 val = 0;
3358
3359 err = bpf_map_direct_read(map, map_off, size,
3360 &val);
3361 if (err)
3362 return err;
3363
3364 regs[value_regno].type = SCALAR_VALUE;
3365 __mark_reg_known(&regs[value_regno], val);
3366 } else {
3367 mark_reg_unknown(env, regs, value_regno);
3368 }
3369 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003370 } else if (reg->type == PTR_TO_MEM) {
3371 if (t == BPF_WRITE && value_regno >= 0 &&
3372 is_pointer_value(env, value_regno)) {
3373 verbose(env, "R%d leaks addr into mem\n", value_regno);
3374 return -EACCES;
3375 }
3376 err = check_mem_region_access(env, regno, off, size,
3377 reg->mem_size, false);
3378 if (!err && t == BPF_READ && value_regno >= 0)
3379 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07003380 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01003381 enum bpf_reg_type reg_type = SCALAR_VALUE;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003382 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07003383
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003384 if (t == BPF_WRITE && value_regno >= 0 &&
3385 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003386 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003387 return -EACCES;
3388 }
Edward Creef1174f72017-08-07 15:26:19 +01003389
Daniel Borkmann58990d12018-06-07 17:40:03 +02003390 err = check_ctx_reg(env, reg, regno);
3391 if (err < 0)
3392 return err;
3393
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003394 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3395 if (err)
3396 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003397 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01003398 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003399 * PTR_TO_PACKET[_META,_END]. In the latter
3400 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01003401 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003402 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003403 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003404 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003405 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003406 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003407 if (reg_type_may_be_null(reg_type))
3408 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01003409 /* A load of ctx field could have different
3410 * actual load size with the one encoded in the
3411 * insn. When the dst is PTR, it is for sure not
3412 * a sub-register.
3413 */
3414 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07003415 if (reg_type == PTR_TO_BTF_ID ||
3416 reg_type == PTR_TO_BTF_ID_OR_NULL)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003417 regs[value_regno].btf_id = btf_id;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003418 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003419 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003420 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003421
Edward Creef1174f72017-08-07 15:26:19 +01003422 } else if (reg->type == PTR_TO_STACK) {
Edward Creef1174f72017-08-07 15:26:19 +01003423 off += reg->var_off.value;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003424 err = check_stack_access(env, reg, off, size);
3425 if (err)
3426 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003427
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003428 state = func(env, reg);
3429 err = update_stack_depth(env, state, off);
3430 if (err)
3431 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003432
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003433 if (t == BPF_WRITE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003434 err = check_stack_write(env, state, off, size,
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07003435 value_regno, insn_idx);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003436 else
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003437 err = check_stack_read(env, state, off, size,
3438 value_regno);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003439 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003440 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003441 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003442 return -EACCES;
3443 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003444 if (t == BPF_WRITE && value_regno >= 0 &&
3445 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003446 verbose(env, "R%d leaks addr into packet\n",
3447 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003448 return -EACCES;
3449 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08003450 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003451 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003452 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07003453 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3454 if (t == BPF_WRITE && value_regno >= 0 &&
3455 is_pointer_value(env, value_regno)) {
3456 verbose(env, "R%d leaks addr into flow keys\n",
3457 value_regno);
3458 return -EACCES;
3459 }
3460
3461 err = check_flow_keys_access(env, off, size);
3462 if (!err && t == BPF_READ && value_regno >= 0)
3463 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003464 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07003465 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003466 verbose(env, "R%d cannot write into %s\n",
3467 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07003468 return -EACCES;
3469 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003470 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07003471 if (!err && value_regno >= 0)
3472 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07003473 } else if (reg->type == PTR_TO_TP_BUFFER) {
3474 err = check_tp_buffer_access(env, reg, regno, off, size);
3475 if (!err && t == BPF_READ && value_regno >= 0)
3476 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003477 } else if (reg->type == PTR_TO_BTF_ID) {
3478 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3479 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003480 } else if (reg->type == CONST_PTR_TO_MAP) {
3481 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3482 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07003483 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3484 if (t == BPF_WRITE) {
3485 verbose(env, "R%d cannot write into %s\n",
3486 regno, reg_type_str[reg->type]);
3487 return -EACCES;
3488 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003489 err = check_buffer_access(env, reg, regno, off, size, false,
3490 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003491 &env->prog->aux->max_rdonly_access);
3492 if (!err && value_regno >= 0)
3493 mark_reg_unknown(env, regs, value_regno);
3494 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003495 err = check_buffer_access(env, reg, regno, off, size, false,
3496 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003497 &env->prog->aux->max_rdwr_access);
3498 if (!err && t == BPF_READ && value_regno >= 0)
3499 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003500 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003501 verbose(env, "R%d invalid mem access '%s'\n", regno,
3502 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003503 return -EACCES;
3504 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003505
Edward Creef1174f72017-08-07 15:26:19 +01003506 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003507 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01003508 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08003509 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003510 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003511 return err;
3512}
3513
Yonghong Song31fd8582017-06-13 15:52:13 -07003514static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003515{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003516 int err;
3517
3518 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3519 insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003520 verbose(env, "BPF_XADD uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003521 return -EINVAL;
3522 }
3523
3524 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003525 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003526 if (err)
3527 return err;
3528
3529 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003530 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003531 if (err)
3532 return err;
3533
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003534 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003535 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003536 return -EACCES;
3537 }
3538
Daniel Borkmannca369602018-02-23 22:29:05 +01003539 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003540 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003541 is_flow_key_reg(env, insn->dst_reg) ||
3542 is_sk_reg(env, insn->dst_reg)) {
Daniel Borkmannca369602018-02-23 22:29:05 +01003543 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003544 insn->dst_reg,
3545 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003546 return -EACCES;
3547 }
3548
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003549 /* check whether atomic_add can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003550 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003551 BPF_SIZE(insn->code), BPF_READ, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003552 if (err)
3553 return err;
3554
3555 /* check whether atomic_add can write into the same memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003556 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003557 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003558}
3559
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003560static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3561 int off, int access_size,
3562 bool zero_size_allowed)
3563{
3564 struct bpf_reg_state *reg = reg_state(env, regno);
3565
3566 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3567 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3568 if (tnum_is_const(reg->var_off)) {
3569 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3570 regno, off, access_size);
3571 } else {
3572 char tn_buf[48];
3573
3574 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3575 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3576 regno, tn_buf, access_size);
3577 }
3578 return -EACCES;
3579 }
3580 return 0;
3581}
3582
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003583/* when register 'regno' is passed into function that will read 'access_size'
3584 * bytes from that pointer, make sure that it's within stack boundary
Edward Creef1174f72017-08-07 15:26:19 +01003585 * and all elements of stack are initialized.
3586 * Unlike most pointer bounds-checking functions, this one doesn't take an
3587 * 'off' argument, so it has to add in reg->off itself.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003588 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003589static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
Daniel Borkmann435faee12016-04-13 00:10:51 +02003590 int access_size, bool zero_size_allowed,
3591 struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003592{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003593 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003594 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003595 int err, min_off, max_off, i, j, slot, spi;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003596
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003597 if (reg->type != PTR_TO_STACK) {
Edward Creef1174f72017-08-07 15:26:19 +01003598 /* Allow zero-byte read from NULL, regardless of pointer type */
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003599 if (zero_size_allowed && access_size == 0 &&
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003600 register_is_null(reg))
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003601 return 0;
3602
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003603 verbose(env, "R%d type=%s expected=%s\n", regno,
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003604 reg_type_str[reg->type],
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003605 reg_type_str[PTR_TO_STACK]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003606 return -EACCES;
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003607 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003608
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003609 if (tnum_is_const(reg->var_off)) {
3610 min_off = max_off = reg->var_off.value + reg->off;
3611 err = __check_stack_boundary(env, regno, min_off, access_size,
3612 zero_size_allowed);
3613 if (err)
3614 return err;
3615 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07003616 /* Variable offset is prohibited for unprivileged mode for
3617 * simplicity since it requires corresponding support in
3618 * Spectre masking for stack ALU.
3619 * See also retrieve_ptr_limit().
3620 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07003621 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07003622 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01003623
Andrey Ignatov088ec262019-04-03 23:22:39 -07003624 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3625 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3626 regno, tn_buf);
3627 return -EACCES;
3628 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07003629 /* Only initialized buffer on stack is allowed to be accessed
3630 * with variable offset. With uninitialized buffer it's hard to
3631 * guarantee that whole memory is marked as initialized on
3632 * helper return since specific bounds are unknown what may
3633 * cause uninitialized stack leaking.
3634 */
3635 if (meta && meta->raw_mode)
3636 meta = NULL;
3637
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003638 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3639 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3640 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3641 regno);
3642 return -EACCES;
3643 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003644 min_off = reg->smin_value + reg->off;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003645 max_off = reg->smax_value + reg->off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003646 err = __check_stack_boundary(env, regno, min_off, access_size,
3647 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003648 if (err) {
3649 verbose(env, "R%d min value is outside of stack bound\n",
3650 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003651 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003652 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003653 err = __check_stack_boundary(env, regno, max_off, access_size,
3654 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003655 if (err) {
3656 verbose(env, "R%d max value is outside of stack bound\n",
3657 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003658 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003659 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003660 }
3661
Daniel Borkmann435faee12016-04-13 00:10:51 +02003662 if (meta && meta->raw_mode) {
3663 meta->access_size = access_size;
3664 meta->regno = regno;
3665 return 0;
3666 }
3667
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003668 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003669 u8 *stype;
3670
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003671 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003672 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003673 if (state->allocated_stack <= slot)
3674 goto err;
3675 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3676 if (*stype == STACK_MISC)
3677 goto mark;
3678 if (*stype == STACK_ZERO) {
3679 /* helper can write anything into the stack */
3680 *stype = STACK_MISC;
3681 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003682 }
Yonghong Song1d68f222020-05-09 10:59:15 -07003683
3684 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3685 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3686 goto mark;
3687
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003688 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3689 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003690 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003691 for (j = 0; j < BPF_REG_SIZE; j++)
3692 state->stack[spi].slot_type[j] = STACK_MISC;
3693 goto mark;
3694 }
3695
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003696err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003697 if (tnum_is_const(reg->var_off)) {
3698 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3699 min_off, i - min_off, access_size);
3700 } else {
3701 char tn_buf[48];
3702
3703 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3704 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3705 tn_buf, i - min_off, access_size);
3706 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003707 return -EACCES;
3708mark:
3709 /* reading any byte out of 8-byte 'spill_slot' will cause
3710 * the whole slot to be marked as 'read'
3711 */
Edward Cree679c7822018-08-22 20:02:19 +01003712 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01003713 state->stack[spi].spilled_ptr.parent,
3714 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003715 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003716 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003717}
3718
Gianluca Borello06c1c042017-01-09 10:19:49 -08003719static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3720 int access_size, bool zero_size_allowed,
3721 struct bpf_call_arg_meta *meta)
3722{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003723 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08003724
Edward Creef1174f72017-08-07 15:26:19 +01003725 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08003726 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003727 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08003728 return check_packet_access(env, regno, reg->off, access_size,
3729 zero_size_allowed);
Gianluca Borello06c1c042017-01-09 10:19:49 -08003730 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02003731 if (check_map_access_type(env, regno, reg->off, access_size,
3732 meta && meta->raw_mode ? BPF_WRITE :
3733 BPF_READ))
3734 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003735 return check_map_access(env, regno, reg->off, access_size,
3736 zero_size_allowed);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003737 case PTR_TO_MEM:
3738 return check_mem_region_access(env, regno, reg->off,
3739 access_size, reg->mem_size,
3740 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07003741 case PTR_TO_RDONLY_BUF:
3742 if (meta && meta->raw_mode)
3743 return -EACCES;
3744 return check_buffer_access(env, reg, regno, reg->off,
3745 access_size, zero_size_allowed,
3746 "rdonly",
3747 &env->prog->aux->max_rdonly_access);
3748 case PTR_TO_RDWR_BUF:
3749 return check_buffer_access(env, reg, regno, reg->off,
3750 access_size, zero_size_allowed,
3751 "rdwr",
3752 &env->prog->aux->max_rdwr_access);
Edward Creef1174f72017-08-07 15:26:19 +01003753 default: /* scalar_value|ptr_to_stack or invalid ptr */
Gianluca Borello06c1c042017-01-09 10:19:49 -08003754 return check_stack_boundary(env, regno, access_size,
3755 zero_size_allowed, meta);
3756 }
3757}
3758
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003759/* Implementation details:
3760 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3761 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3762 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3763 * value_or_null->value transition, since the verifier only cares about
3764 * the range of access to valid map value pointer and doesn't care about actual
3765 * address of the map element.
3766 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3767 * reg->id > 0 after value_or_null->value transition. By doing so
3768 * two bpf_map_lookups will be considered two different pointers that
3769 * point to different bpf_spin_locks.
3770 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3771 * dead-locks.
3772 * Since only one bpf_spin_lock is allowed the checks are simpler than
3773 * reg_is_refcounted() logic. The verifier needs to remember only
3774 * one spin_lock instead of array of acquired_refs.
3775 * cur_state->active_spin_lock remembers which map value element got locked
3776 * and clears it after bpf_spin_unlock.
3777 */
3778static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3779 bool is_lock)
3780{
3781 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3782 struct bpf_verifier_state *cur = env->cur_state;
3783 bool is_const = tnum_is_const(reg->var_off);
3784 struct bpf_map *map = reg->map_ptr;
3785 u64 val = reg->var_off.value;
3786
3787 if (reg->type != PTR_TO_MAP_VALUE) {
3788 verbose(env, "R%d is not a pointer to map_value\n", regno);
3789 return -EINVAL;
3790 }
3791 if (!is_const) {
3792 verbose(env,
3793 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3794 regno);
3795 return -EINVAL;
3796 }
3797 if (!map->btf) {
3798 verbose(env,
3799 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3800 map->name);
3801 return -EINVAL;
3802 }
3803 if (!map_value_has_spin_lock(map)) {
3804 if (map->spin_lock_off == -E2BIG)
3805 verbose(env,
3806 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3807 map->name);
3808 else if (map->spin_lock_off == -ENOENT)
3809 verbose(env,
3810 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3811 map->name);
3812 else
3813 verbose(env,
3814 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3815 map->name);
3816 return -EINVAL;
3817 }
3818 if (map->spin_lock_off != val + reg->off) {
3819 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3820 val + reg->off);
3821 return -EINVAL;
3822 }
3823 if (is_lock) {
3824 if (cur->active_spin_lock) {
3825 verbose(env,
3826 "Locking two bpf_spin_locks are not allowed\n");
3827 return -EINVAL;
3828 }
3829 cur->active_spin_lock = reg->id;
3830 } else {
3831 if (!cur->active_spin_lock) {
3832 verbose(env, "bpf_spin_unlock without taking a lock\n");
3833 return -EINVAL;
3834 }
3835 if (cur->active_spin_lock != reg->id) {
3836 verbose(env, "bpf_spin_unlock of different lock\n");
3837 return -EINVAL;
3838 }
3839 cur->active_spin_lock = 0;
3840 }
3841 return 0;
3842}
3843
Daniel Borkmann90133412018-01-20 01:24:29 +01003844static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3845{
3846 return type == ARG_PTR_TO_MEM ||
3847 type == ARG_PTR_TO_MEM_OR_NULL ||
3848 type == ARG_PTR_TO_UNINIT_MEM;
3849}
3850
3851static bool arg_type_is_mem_size(enum bpf_arg_type type)
3852{
3853 return type == ARG_CONST_SIZE ||
3854 type == ARG_CONST_SIZE_OR_ZERO;
3855}
3856
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003857static bool arg_type_is_alloc_mem_ptr(enum bpf_arg_type type)
3858{
3859 return type == ARG_PTR_TO_ALLOC_MEM ||
3860 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
3861}
3862
3863static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3864{
3865 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3866}
3867
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003868static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3869{
3870 return type == ARG_PTR_TO_INT ||
3871 type == ARG_PTR_TO_LONG;
3872}
3873
3874static int int_ptr_type_to_size(enum bpf_arg_type type)
3875{
3876 if (type == ARG_PTR_TO_INT)
3877 return sizeof(u32);
3878 else if (type == ARG_PTR_TO_LONG)
3879 return sizeof(u64);
3880
3881 return -EINVAL;
3882}
3883
Lorenz Bauer912f4422020-08-21 11:29:46 +01003884static int resolve_map_arg_type(struct bpf_verifier_env *env,
3885 const struct bpf_call_arg_meta *meta,
3886 enum bpf_arg_type *arg_type)
3887{
3888 if (!meta->map_ptr) {
3889 /* kernel subsystem misconfigured verifier */
3890 verbose(env, "invalid map_ptr to access map->type\n");
3891 return -EACCES;
3892 }
3893
3894 switch (meta->map_ptr->map_type) {
3895 case BPF_MAP_TYPE_SOCKMAP:
3896 case BPF_MAP_TYPE_SOCKHASH:
3897 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
3898 *arg_type = ARG_PTR_TO_SOCKET;
3899 } else {
3900 verbose(env, "invalid arg_type for sockmap/sockhash\n");
3901 return -EINVAL;
3902 }
3903 break;
3904
3905 default:
3906 break;
3907 }
3908 return 0;
3909}
3910
Yonghong Songaf7ec132020-06-23 16:08:09 -07003911static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
3912 struct bpf_call_arg_meta *meta,
3913 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003914{
Yonghong Songaf7ec132020-06-23 16:08:09 -07003915 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003916 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003917 enum bpf_reg_type expected_type, type = reg->type;
Yonghong Songaf7ec132020-06-23 16:08:09 -07003918 enum bpf_arg_type arg_type = fn->arg_type[arg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003919 int err = 0;
3920
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003921 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003922 return 0;
3923
Edward Creedc503a82017-08-15 20:34:35 +01003924 err = check_reg_arg(env, regno, SRC_OP);
3925 if (err)
3926 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003927
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003928 if (arg_type == ARG_ANYTHING) {
3929 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003930 verbose(env, "R%d leaks addr into helper function\n",
3931 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003932 return -EACCES;
3933 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003934 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003935 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003936
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003937 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003938 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003939 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003940 return -EACCES;
3941 }
3942
Lorenz Bauer912f4422020-08-21 11:29:46 +01003943 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
3944 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3945 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
3946 err = resolve_map_arg_type(env, meta, &arg_type);
3947 if (err)
3948 return err;
3949 }
3950
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003951 if (arg_type == ARG_PTR_TO_MAP_KEY ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003952 arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003953 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3954 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003955 expected_type = PTR_TO_STACK;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003956 if (register_is_null(reg) &&
3957 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
3958 /* final test in check_stack_boundary() */;
3959 else if (!type_is_pkt_pointer(type) &&
3960 type != PTR_TO_MAP_VALUE &&
3961 type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003962 goto err_type;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003963 } else if (arg_type == ARG_CONST_SIZE ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003964 arg_type == ARG_CONST_SIZE_OR_ZERO ||
3965 arg_type == ARG_CONST_ALLOC_SIZE_OR_ZERO) {
Edward Creef1174f72017-08-07 15:26:19 +01003966 expected_type = SCALAR_VALUE;
3967 if (type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003968 goto err_type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003969 } else if (arg_type == ARG_CONST_MAP_PTR) {
3970 expected_type = CONST_PTR_TO_MAP;
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003971 if (type != expected_type)
3972 goto err_type;
Daniel Borkmannf3189032020-03-27 16:58:52 +01003973 } else if (arg_type == ARG_PTR_TO_CTX ||
3974 arg_type == ARG_PTR_TO_CTX_OR_NULL) {
Alexei Starovoitov608cd712015-03-26 19:53:57 -07003975 expected_type = PTR_TO_CTX;
Daniel Borkmannf3189032020-03-27 16:58:52 +01003976 if (!(register_is_null(reg) &&
3977 arg_type == ARG_PTR_TO_CTX_OR_NULL)) {
3978 if (type != expected_type)
3979 goto err_type;
3980 err = check_ctx_reg(env, reg, regno);
3981 if (err < 0)
3982 return err;
3983 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003984 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
3985 expected_type = PTR_TO_SOCK_COMMON;
3986 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3987 if (!type_is_sk_pointer(type))
3988 goto err_type;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003989 if (reg->ref_obj_id) {
3990 if (meta->ref_obj_id) {
3991 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3992 regno, reg->ref_obj_id,
3993 meta->ref_obj_id);
3994 return -EFAULT;
3995 }
3996 meta->ref_obj_id = reg->ref_obj_id;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003997 }
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02003998 } else if (arg_type == ARG_PTR_TO_SOCKET ||
3999 arg_type == ARG_PTR_TO_SOCKET_OR_NULL) {
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004000 expected_type = PTR_TO_SOCKET;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02004001 if (!(register_is_null(reg) &&
4002 arg_type == ARG_PTR_TO_SOCKET_OR_NULL)) {
4003 if (type != expected_type)
4004 goto err_type;
4005 }
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004006 } else if (arg_type == ARG_PTR_TO_BTF_ID) {
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004007 bool ids_match = false;
4008
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004009 expected_type = PTR_TO_BTF_ID;
4010 if (type != expected_type)
4011 goto err_type;
Yonghong Songaf7ec132020-06-23 16:08:09 -07004012 if (!fn->check_btf_id) {
4013 if (reg->btf_id != meta->btf_id) {
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004014 ids_match = btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4015 meta->btf_id);
4016 if (!ids_match) {
4017 verbose(env, "Helper has type %s got %s in R%d\n",
4018 kernel_type_name(meta->btf_id),
4019 kernel_type_name(reg->btf_id), regno);
4020 return -EACCES;
4021 }
Yonghong Songaf7ec132020-06-23 16:08:09 -07004022 }
4023 } else if (!fn->check_btf_id(reg->btf_id, arg)) {
4024 verbose(env, "Helper does not support %s in R%d\n",
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004025 kernel_type_name(reg->btf_id), regno);
4026
4027 return -EACCES;
4028 }
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004029 if ((reg->off && !ids_match) || !tnum_is_const(reg->var_off) || reg->var_off.value) {
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004030 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4031 regno);
4032 return -EACCES;
4033 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004034 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4035 if (meta->func_id == BPF_FUNC_spin_lock) {
4036 if (process_spin_lock(env, regno, true))
4037 return -EACCES;
4038 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4039 if (process_spin_lock(env, regno, false))
4040 return -EACCES;
4041 } else {
4042 verbose(env, "verifier internal error\n");
4043 return -EFAULT;
4044 }
Daniel Borkmann90133412018-01-20 01:24:29 +01004045 } else if (arg_type_is_mem_ptr(arg_type)) {
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01004046 expected_type = PTR_TO_STACK;
4047 /* One exception here. In case function allows for NULL to be
Edward Creef1174f72017-08-07 15:26:19 +01004048 * passed in as argument, it's a SCALAR_VALUE type. Final test
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01004049 * happens during stack boundary checking.
4050 */
Alexei Starovoitov914cb782017-11-30 21:31:40 -08004051 if (register_is_null(reg) &&
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004052 (arg_type == ARG_PTR_TO_MEM_OR_NULL ||
4053 arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL))
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004054 /* final test in check_stack_boundary() */;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004055 else if (!type_is_pkt_pointer(type) &&
4056 type != PTR_TO_MAP_VALUE &&
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004057 type != PTR_TO_MEM &&
Yonghong Songafbf21d2020-07-23 11:41:11 -07004058 type != PTR_TO_RDONLY_BUF &&
4059 type != PTR_TO_RDWR_BUF &&
Edward Creef1174f72017-08-07 15:26:19 +01004060 type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004061 goto err_type;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004062 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004063 } else if (arg_type_is_alloc_mem_ptr(arg_type)) {
4064 expected_type = PTR_TO_MEM;
4065 if (register_is_null(reg) &&
4066 arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL)
4067 /* final test in check_stack_boundary() */;
4068 else if (type != expected_type)
4069 goto err_type;
4070 if (meta->ref_obj_id) {
4071 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4072 regno, reg->ref_obj_id,
4073 meta->ref_obj_id);
4074 return -EFAULT;
4075 }
4076 meta->ref_obj_id = reg->ref_obj_id;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004077 } else if (arg_type_is_int_ptr(arg_type)) {
4078 expected_type = PTR_TO_STACK;
4079 if (!type_is_pkt_pointer(type) &&
4080 type != PTR_TO_MAP_VALUE &&
4081 type != expected_type)
4082 goto err_type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004083 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004084 verbose(env, "unsupported arg_type %d\n", arg_type);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004085 return -EFAULT;
4086 }
4087
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004088 if (arg_type == ARG_CONST_MAP_PTR) {
4089 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004090 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004091 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4092 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4093 * check that [key, key + map->key_size) are within
4094 * stack limits and initialized
4095 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004096 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004097 /* in function declaration map_ptr must come before
4098 * map_key, so that it's verified and known before
4099 * we have to check map_key here. Otherwise it means
4100 * that kernel subsystem misconfigured verifier
4101 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004102 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004103 return -EACCES;
4104 }
Paul Chaignond71962f2018-04-24 15:07:54 +02004105 err = check_helper_mem_access(env, regno,
4106 meta->map_ptr->key_size, false,
4107 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004108 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004109 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4110 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004111 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004112 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4113 * check [value, value + map->value_size) validity
4114 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004115 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004116 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004117 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004118 return -EACCES;
4119 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004120 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02004121 err = check_helper_mem_access(env, regno,
4122 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004123 meta);
Daniel Borkmann90133412018-01-20 01:24:29 +01004124 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004125 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004126
John Fastabend10060502020-03-30 14:36:19 -07004127 /* This is used to refine r0 return value bounds for helpers
4128 * that enforce this value as an upper bound on return values.
4129 * See do_refine_retval_range() for helpers that can refine
4130 * the return value. C type of helper is u32 so we pull register
4131 * bound from umax_value however, if negative verifier errors
4132 * out. Only upper bounds can be learned because retval is an
4133 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07004134 */
John Fastabend10060502020-03-30 14:36:19 -07004135 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004136
Edward Creef1174f72017-08-07 15:26:19 +01004137 /* The register is SCALAR_VALUE; the access check
4138 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08004139 */
Edward Creef1174f72017-08-07 15:26:19 +01004140 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08004141 /* For unprivileged variable accesses, disable raw
4142 * mode so that the program is required to
4143 * initialize all the memory that the helper could
4144 * just partially fill up.
4145 */
4146 meta = NULL;
4147
Edward Creeb03c9f92017-08-07 15:26:36 +01004148 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004149 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004150 regno);
4151 return -EACCES;
4152 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08004153
Edward Creeb03c9f92017-08-07 15:26:36 +01004154 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004155 err = check_helper_mem_access(env, regno - 1, 0,
4156 zero_size_allowed,
4157 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004158 if (err)
4159 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004160 }
Edward Creef1174f72017-08-07 15:26:19 +01004161
Edward Creeb03c9f92017-08-07 15:26:36 +01004162 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004163 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004164 regno);
4165 return -EACCES;
4166 }
4167 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01004168 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01004169 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07004170 if (!err)
4171 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004172 } else if (arg_type_is_alloc_size(arg_type)) {
4173 if (!tnum_is_const(reg->var_off)) {
4174 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4175 regno);
4176 return -EACCES;
4177 }
4178 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004179 } else if (arg_type_is_int_ptr(arg_type)) {
4180 int size = int_ptr_type_to_size(arg_type);
4181
4182 err = check_helper_mem_access(env, regno, size, false, meta);
4183 if (err)
4184 return err;
4185 err = check_ptr_alignment(env, reg, 0, size, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004186 }
4187
4188 return err;
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004189err_type:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004190 verbose(env, "R%d type=%s expected=%s\n", regno,
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004191 reg_type_str[type], reg_type_str[expected_type]);
4192 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004193}
4194
Lorenz Bauer01262402020-08-21 11:29:47 +01004195static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4196{
4197 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07004198 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01004199
4200 if (func_id != BPF_FUNC_map_update_elem)
4201 return false;
4202
4203 /* It's not possible to get access to a locked struct sock in these
4204 * contexts, so updating is safe.
4205 */
4206 switch (type) {
4207 case BPF_PROG_TYPE_TRACING:
4208 if (eatype == BPF_TRACE_ITER)
4209 return true;
4210 break;
4211 case BPF_PROG_TYPE_SOCKET_FILTER:
4212 case BPF_PROG_TYPE_SCHED_CLS:
4213 case BPF_PROG_TYPE_SCHED_ACT:
4214 case BPF_PROG_TYPE_XDP:
4215 case BPF_PROG_TYPE_SK_REUSEPORT:
4216 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4217 case BPF_PROG_TYPE_SK_LOOKUP:
4218 return true;
4219 default:
4220 break;
4221 }
4222
4223 verbose(env, "cannot update sockmap in this context\n");
4224 return false;
4225}
4226
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004227static int check_map_func_compatibility(struct bpf_verifier_env *env,
4228 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00004229{
Kaixu Xia35578d72015-08-06 07:02:35 +00004230 if (!map)
4231 return 0;
4232
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004233 /* We need a two way check, first is from map perspective ... */
4234 switch (map->map_type) {
4235 case BPF_MAP_TYPE_PROG_ARRAY:
4236 if (func_id != BPF_FUNC_tail_call)
4237 goto error;
4238 break;
4239 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4240 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07004241 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004242 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004243 func_id != BPF_FUNC_perf_event_read_value &&
4244 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004245 goto error;
4246 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004247 case BPF_MAP_TYPE_RINGBUF:
4248 if (func_id != BPF_FUNC_ringbuf_output &&
4249 func_id != BPF_FUNC_ringbuf_reserve &&
4250 func_id != BPF_FUNC_ringbuf_submit &&
4251 func_id != BPF_FUNC_ringbuf_discard &&
4252 func_id != BPF_FUNC_ringbuf_query)
4253 goto error;
4254 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004255 case BPF_MAP_TYPE_STACK_TRACE:
4256 if (func_id != BPF_FUNC_get_stackid)
4257 goto error;
4258 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07004259 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04004260 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004261 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004262 goto error;
4263 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004264 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00004265 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07004266 if (func_id != BPF_FUNC_get_local_storage)
4267 goto error;
4268 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07004269 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004270 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02004271 if (func_id != BPF_FUNC_redirect_map &&
4272 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07004273 goto error;
4274 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004275 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4276 * appear.
4277 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02004278 case BPF_MAP_TYPE_CPUMAP:
4279 if (func_id != BPF_FUNC_redirect_map)
4280 goto error;
4281 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07004282 case BPF_MAP_TYPE_XSKMAP:
4283 if (func_id != BPF_FUNC_redirect_map &&
4284 func_id != BPF_FUNC_map_lookup_elem)
4285 goto error;
4286 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004287 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07004288 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004289 if (func_id != BPF_FUNC_map_lookup_elem)
4290 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07004291 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004292 case BPF_MAP_TYPE_SOCKMAP:
4293 if (func_id != BPF_FUNC_sk_redirect_map &&
4294 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07004295 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004296 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004297 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004298 func_id != BPF_FUNC_map_lookup_elem &&
4299 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07004300 goto error;
4301 break;
John Fastabend81110382018-05-14 10:00:17 -07004302 case BPF_MAP_TYPE_SOCKHASH:
4303 if (func_id != BPF_FUNC_sk_redirect_hash &&
4304 func_id != BPF_FUNC_sock_hash_update &&
4305 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004306 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004307 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004308 func_id != BPF_FUNC_map_lookup_elem &&
4309 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07004310 goto error;
4311 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004312 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4313 if (func_id != BPF_FUNC_sk_select_reuseport)
4314 goto error;
4315 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004316 case BPF_MAP_TYPE_QUEUE:
4317 case BPF_MAP_TYPE_STACK:
4318 if (func_id != BPF_FUNC_map_peek_elem &&
4319 func_id != BPF_FUNC_map_pop_elem &&
4320 func_id != BPF_FUNC_map_push_elem)
4321 goto error;
4322 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004323 case BPF_MAP_TYPE_SK_STORAGE:
4324 if (func_id != BPF_FUNC_sk_storage_get &&
4325 func_id != BPF_FUNC_sk_storage_delete)
4326 goto error;
4327 break;
KP Singh8ea63682020-08-25 20:29:17 +02004328 case BPF_MAP_TYPE_INODE_STORAGE:
4329 if (func_id != BPF_FUNC_inode_storage_get &&
4330 func_id != BPF_FUNC_inode_storage_delete)
4331 goto error;
4332 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004333 default:
4334 break;
4335 }
4336
4337 /* ... and second from the function itself. */
4338 switch (func_id) {
4339 case BPF_FUNC_tail_call:
4340 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4341 goto error;
Jiong Wangf910cef2018-05-02 16:17:17 -04004342 if (env->subprog_cnt > 1) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004343 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
4344 return -EINVAL;
4345 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004346 break;
4347 case BPF_FUNC_perf_event_read:
4348 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07004349 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004350 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004351 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004352 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4353 goto error;
4354 break;
4355 case BPF_FUNC_get_stackid:
4356 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4357 goto error;
4358 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004359 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02004360 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004361 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4362 goto error;
4363 break;
John Fastabend97f91a72017-07-17 09:29:18 -07004364 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02004365 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004366 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004367 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4368 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07004369 goto error;
4370 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004371 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07004372 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07004373 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07004374 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4375 goto error;
4376 break;
John Fastabend81110382018-05-14 10:00:17 -07004377 case BPF_FUNC_sk_redirect_hash:
4378 case BPF_FUNC_msg_redirect_hash:
4379 case BPF_FUNC_sock_hash_update:
4380 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07004381 goto error;
4382 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004383 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00004384 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4385 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07004386 goto error;
4387 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004388 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004389 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4390 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4391 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004392 goto error;
4393 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004394 case BPF_FUNC_map_peek_elem:
4395 case BPF_FUNC_map_pop_elem:
4396 case BPF_FUNC_map_push_elem:
4397 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4398 map->map_type != BPF_MAP_TYPE_STACK)
4399 goto error;
4400 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004401 case BPF_FUNC_sk_storage_get:
4402 case BPF_FUNC_sk_storage_delete:
4403 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4404 goto error;
4405 break;
KP Singh8ea63682020-08-25 20:29:17 +02004406 case BPF_FUNC_inode_storage_get:
4407 case BPF_FUNC_inode_storage_delete:
4408 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4409 goto error;
4410 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004411 default:
4412 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00004413 }
4414
4415 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004416error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004417 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004418 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004419 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00004420}
4421
Daniel Borkmann90133412018-01-20 01:24:29 +01004422static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004423{
4424 int count = 0;
4425
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004426 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004427 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004428 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004429 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004430 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004431 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004432 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004433 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004434 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02004435 count++;
4436
Daniel Borkmann90133412018-01-20 01:24:29 +01004437 /* We only support one arg being in raw mode at the moment,
4438 * which is sufficient for the helper functions we have
4439 * right now.
4440 */
4441 return count <= 1;
4442}
4443
4444static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4445 enum bpf_arg_type arg_next)
4446{
4447 return (arg_type_is_mem_ptr(arg_curr) &&
4448 !arg_type_is_mem_size(arg_next)) ||
4449 (!arg_type_is_mem_ptr(arg_curr) &&
4450 arg_type_is_mem_size(arg_next));
4451}
4452
4453static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4454{
4455 /* bpf_xxx(..., buf, len) call will access 'len'
4456 * bytes from memory 'buf'. Both arg types need
4457 * to be paired, so make sure there's no buggy
4458 * helper function specification.
4459 */
4460 if (arg_type_is_mem_size(fn->arg1_type) ||
4461 arg_type_is_mem_ptr(fn->arg5_type) ||
4462 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4463 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4464 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4465 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4466 return false;
4467
4468 return true;
4469}
4470
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004471static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004472{
4473 int count = 0;
4474
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004475 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004476 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004477 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004478 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004479 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004480 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004481 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004482 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004483 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07004484 count++;
4485
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004486 /* A reference acquiring function cannot acquire
4487 * another refcounted ptr.
4488 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004489 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004490 return false;
4491
Joe Stringerfd978bf72018-10-02 13:35:35 -07004492 /* We only support one arg being unreferenced at the moment,
4493 * which is sufficient for the helper functions we have right now.
4494 */
4495 return count <= 1;
4496}
4497
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004498static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01004499{
4500 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07004501 check_arg_pair_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004502 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02004503}
4504
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004505/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4506 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01004507 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004508static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4509 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004510{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01004511 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004512 int i;
4513
4514 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004515 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004516 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004517
Joe Stringerf3709f62018-10-02 13:35:29 -07004518 bpf_for_each_spilled_reg(i, state, reg) {
4519 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004520 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004521 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01004522 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004523 }
4524}
4525
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004526static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4527{
4528 struct bpf_verifier_state *vstate = env->cur_state;
4529 int i;
4530
4531 for (i = 0; i <= vstate->curframe; i++)
4532 __clear_all_pkt_pointers(env, vstate->frame[i]);
4533}
4534
Joe Stringerfd978bf72018-10-02 13:35:35 -07004535static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004536 struct bpf_func_state *state,
4537 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004538{
4539 struct bpf_reg_state *regs = state->regs, *reg;
4540 int i;
4541
4542 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004543 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004544 mark_reg_unknown(env, regs, i);
4545
4546 bpf_for_each_spilled_reg(i, state, reg) {
4547 if (!reg)
4548 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004549 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01004550 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07004551 }
4552}
4553
4554/* The pointer with the specified id has released its reference to kernel
4555 * resources. Identify all copies of the same pointer and clear the reference.
4556 */
4557static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004558 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07004559{
4560 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004561 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004562 int i;
4563
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004564 err = release_reference_state(cur_func(env), ref_obj_id);
4565 if (err)
4566 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004567
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004568 for (i = 0; i <= vstate->curframe; i++)
4569 release_reg_references(env, vstate->frame[i], ref_obj_id);
4570
4571 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004572}
4573
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004574static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4575 struct bpf_reg_state *regs)
4576{
4577 int i;
4578
4579 /* after the call registers r0 - r5 were scratched */
4580 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4581 mark_reg_not_init(env, regs, caller_saved[i]);
4582 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4583 }
4584}
4585
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004586static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4587 int *insn_idx)
4588{
4589 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004590 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004591 struct bpf_func_state *caller, *callee;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004592 int i, err, subprog, target_insn;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004593 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004594
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08004595 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004596 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08004597 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004598 return -E2BIG;
4599 }
4600
4601 target_insn = *insn_idx + insn->imm;
4602 subprog = find_subprog(env, target_insn + 1);
4603 if (subprog < 0) {
4604 verbose(env, "verifier bug. No program starts at insn %d\n",
4605 target_insn + 1);
4606 return -EFAULT;
4607 }
4608
4609 caller = state->frame[state->curframe];
4610 if (state->frame[state->curframe + 1]) {
4611 verbose(env, "verifier bug. Frame %d already allocated\n",
4612 state->curframe + 1);
4613 return -EFAULT;
4614 }
4615
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004616 func_info_aux = env->prog->aux->func_info_aux;
4617 if (func_info_aux)
4618 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4619 err = btf_check_func_arg_match(env, subprog, caller->regs);
4620 if (err == -EFAULT)
4621 return err;
4622 if (is_global) {
4623 if (err) {
4624 verbose(env, "Caller passes invalid args into func#%d\n",
4625 subprog);
4626 return err;
4627 } else {
4628 if (env->log.level & BPF_LOG_LEVEL)
4629 verbose(env,
4630 "Func#%d is global and valid. Skipping.\n",
4631 subprog);
4632 clear_caller_saved_regs(env, caller->regs);
4633
4634 /* All global functions return SCALAR_VALUE */
4635 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4636
4637 /* continue with next insn after call */
4638 return 0;
4639 }
4640 }
4641
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004642 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4643 if (!callee)
4644 return -ENOMEM;
4645 state->frame[state->curframe + 1] = callee;
4646
4647 /* callee cannot access r0, r6 - r9 for reading and has to write
4648 * into its own stack before reading from it.
4649 * callee can read/write into caller's stack
4650 */
4651 init_func_state(env, callee,
4652 /* remember the callsite, it will be used by bpf_exit */
4653 *insn_idx /* callsite */,
4654 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04004655 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004656
Joe Stringerfd978bf72018-10-02 13:35:35 -07004657 /* Transfer references to the callee */
4658 err = transfer_reference_state(callee, caller);
4659 if (err)
4660 return err;
4661
Edward Cree679c7822018-08-22 20:02:19 +01004662 /* copy r1 - r5 args that callee can access. The copy includes parent
4663 * pointers, which connects us up to the liveness chain
4664 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004665 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4666 callee->regs[i] = caller->regs[i];
4667
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004668 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004669
4670 /* only increment it after check_reg_arg() finished */
4671 state->curframe++;
4672
4673 /* and go analyze first insn of the callee */
4674 *insn_idx = target_insn;
4675
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004676 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004677 verbose(env, "caller:\n");
4678 print_verifier_state(env, caller);
4679 verbose(env, "callee:\n");
4680 print_verifier_state(env, callee);
4681 }
4682 return 0;
4683}
4684
4685static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4686{
4687 struct bpf_verifier_state *state = env->cur_state;
4688 struct bpf_func_state *caller, *callee;
4689 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004690 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004691
4692 callee = state->frame[state->curframe];
4693 r0 = &callee->regs[BPF_REG_0];
4694 if (r0->type == PTR_TO_STACK) {
4695 /* technically it's ok to return caller's stack pointer
4696 * (or caller's caller's pointer) back to the caller,
4697 * since these pointers are valid. Only current stack
4698 * pointer will be invalid as soon as function exits,
4699 * but let's be conservative
4700 */
4701 verbose(env, "cannot return stack pointer to the caller\n");
4702 return -EINVAL;
4703 }
4704
4705 state->curframe--;
4706 caller = state->frame[state->curframe];
4707 /* return to the caller whatever r0 had in the callee */
4708 caller->regs[BPF_REG_0] = *r0;
4709
Joe Stringerfd978bf72018-10-02 13:35:35 -07004710 /* Transfer references to the caller */
4711 err = transfer_reference_state(caller, callee);
4712 if (err)
4713 return err;
4714
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004715 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004716 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004717 verbose(env, "returning from callee:\n");
4718 print_verifier_state(env, callee);
4719 verbose(env, "to caller at %d:\n", *insn_idx);
4720 print_verifier_state(env, caller);
4721 }
4722 /* clear everything in the callee */
4723 free_func_state(callee);
4724 state->frame[state->curframe + 1] = NULL;
4725 return 0;
4726}
4727
Yonghong Song849fa502018-04-28 22:28:09 -07004728static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4729 int func_id,
4730 struct bpf_call_arg_meta *meta)
4731{
4732 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4733
4734 if (ret_type != RET_INTEGER ||
4735 (func_id != BPF_FUNC_get_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02004736 func_id != BPF_FUNC_probe_read_str &&
4737 func_id != BPF_FUNC_probe_read_kernel_str &&
4738 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07004739 return;
4740
John Fastabend10060502020-03-30 14:36:19 -07004741 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07004742 ret_reg->s32_max_value = meta->msize_max_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004743 __reg_deduce_bounds(ret_reg);
4744 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07004745 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07004746}
4747
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004748static int
4749record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4750 int func_id, int insn_idx)
4751{
4752 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02004753 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004754
4755 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02004756 func_id != BPF_FUNC_map_lookup_elem &&
4757 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004758 func_id != BPF_FUNC_map_delete_elem &&
4759 func_id != BPF_FUNC_map_push_elem &&
4760 func_id != BPF_FUNC_map_pop_elem &&
4761 func_id != BPF_FUNC_map_peek_elem)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004762 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02004763
Daniel Borkmann591fe982019-04-09 23:20:05 +02004764 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004765 verbose(env, "kernel subsystem misconfigured verifier\n");
4766 return -EINVAL;
4767 }
4768
Daniel Borkmann591fe982019-04-09 23:20:05 +02004769 /* In case of read-only, some additional restrictions
4770 * need to be applied in order to prevent altering the
4771 * state of the map from program side.
4772 */
4773 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4774 (func_id == BPF_FUNC_map_delete_elem ||
4775 func_id == BPF_FUNC_map_update_elem ||
4776 func_id == BPF_FUNC_map_push_elem ||
4777 func_id == BPF_FUNC_map_pop_elem)) {
4778 verbose(env, "write into map forbidden\n");
4779 return -EACCES;
4780 }
4781
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004782 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004783 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004784 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004785 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004786 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004787 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004788 return 0;
4789}
4790
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004791static int
4792record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4793 int func_id, int insn_idx)
4794{
4795 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4796 struct bpf_reg_state *regs = cur_regs(env), *reg;
4797 struct bpf_map *map = meta->map_ptr;
4798 struct tnum range;
4799 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004800 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004801
4802 if (func_id != BPF_FUNC_tail_call)
4803 return 0;
4804 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4805 verbose(env, "kernel subsystem misconfigured verifier\n");
4806 return -EINVAL;
4807 }
4808
4809 range = tnum_range(0, map->max_entries - 1);
4810 reg = &regs[BPF_REG_3];
4811
4812 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4813 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4814 return 0;
4815 }
4816
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004817 err = mark_chain_precision(env, BPF_REG_3);
4818 if (err)
4819 return err;
4820
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004821 val = reg->var_off.value;
4822 if (bpf_map_key_unseen(aux))
4823 bpf_map_key_store(aux, val);
4824 else if (!bpf_map_key_poisoned(aux) &&
4825 bpf_map_key_immediate(aux) != val)
4826 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4827 return 0;
4828}
4829
Joe Stringerfd978bf72018-10-02 13:35:35 -07004830static int check_reference_leak(struct bpf_verifier_env *env)
4831{
4832 struct bpf_func_state *state = cur_func(env);
4833 int i;
4834
4835 for (i = 0; i < state->acquired_refs; i++) {
4836 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4837 state->refs[i].id, state->refs[i].insn_idx);
4838 }
4839 return state->acquired_refs ? -EINVAL : 0;
4840}
4841
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004842static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004843{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004844 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004845 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004846 struct bpf_call_arg_meta meta;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004847 bool changes_data;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004848 int i, err;
4849
4850 /* find function prototype */
4851 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004852 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4853 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004854 return -EINVAL;
4855 }
4856
Jakub Kicinski00176a32017-10-16 16:40:54 -07004857 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07004858 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004859 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004860 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4861 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004862 return -EINVAL;
4863 }
4864
4865 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01004866 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02004867 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004868 return -EINVAL;
4869 }
4870
Jiri Olsaeae2e832020-08-25 21:21:19 +02004871 if (fn->allowed && !fn->allowed(env->prog)) {
4872 verbose(env, "helper call is not allowed in probe\n");
4873 return -EINVAL;
4874 }
4875
Daniel Borkmann04514d12017-12-14 21:07:25 +01004876 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08004877 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01004878 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4879 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4880 func_id_name(func_id), func_id);
4881 return -EINVAL;
4882 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004883
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004884 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02004885 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004886
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004887 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004888 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004889 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004890 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004891 return err;
4892 }
4893
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004894 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004895 /* check args */
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004896 for (i = 0; i < 5; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07004897 if (!fn->check_btf_id) {
4898 err = btf_resolve_helper_id(&env->log, fn, i);
4899 if (err > 0)
4900 meta.btf_id = err;
4901 }
4902 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004903 if (err)
4904 return err;
4905 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004906
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004907 err = record_func_map(env, &meta, func_id, insn_idx);
4908 if (err)
4909 return err;
4910
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004911 err = record_func_key(env, &meta, func_id, insn_idx);
4912 if (err)
4913 return err;
4914
Daniel Borkmann435faee12016-04-13 00:10:51 +02004915 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4916 * is inferred from register state.
4917 */
4918 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01004919 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4920 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004921 if (err)
4922 return err;
4923 }
4924
Joe Stringerfd978bf72018-10-02 13:35:35 -07004925 if (func_id == BPF_FUNC_tail_call) {
4926 err = check_reference_leak(env);
4927 if (err) {
4928 verbose(env, "tail_call would lead to reference leak\n");
4929 return err;
4930 }
4931 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004932 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004933 if (err) {
4934 verbose(env, "func %s#%d reference has not been acquired before\n",
4935 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07004936 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004937 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07004938 }
4939
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004940 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07004941
4942 /* check that flags argument in get_local_storage(map, flags) is 0,
4943 * this is required because get_local_storage() can't return an error.
4944 */
4945 if (func_id == BPF_FUNC_get_local_storage &&
4946 !register_is_null(&regs[BPF_REG_2])) {
4947 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4948 return -EINVAL;
4949 }
4950
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004951 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01004952 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004953 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01004954 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4955 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004956
Jiong Wang5327ed32019-05-24 23:25:12 +01004957 /* helper call returns 64-bit value. */
4958 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4959
Edward Creedc503a82017-08-15 20:34:35 +01004960 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004961 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01004962 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004963 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004964 } else if (fn->ret_type == RET_VOID) {
4965 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07004966 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4967 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01004968 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004969 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004970 /* remember map_ptr, so that check_map_access()
4971 * can check 'value_size' boundary of memory access
4972 * to map element returned from bpf_map_lookup_elem()
4973 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004974 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004975 verbose(env,
4976 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004977 return -EINVAL;
4978 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004979 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01004980 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4981 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08004982 if (map_value_has_spin_lock(meta.map_ptr))
4983 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01004984 } else {
4985 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4986 regs[BPF_REG_0].id = ++env->id_gen;
4987 }
Joe Stringerc64b7982018-10-02 13:35:33 -07004988 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4989 mark_reg_known_zero(env, regs, BPF_REG_0);
4990 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08004991 regs[BPF_REG_0].id = ++env->id_gen;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08004992 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4993 mark_reg_known_zero(env, regs, BPF_REG_0);
4994 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4995 regs[BPF_REG_0].id = ++env->id_gen;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08004996 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4997 mark_reg_known_zero(env, regs, BPF_REG_0);
4998 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4999 regs[BPF_REG_0].id = ++env->id_gen;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005000 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5001 mark_reg_known_zero(env, regs, BPF_REG_0);
5002 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5003 regs[BPF_REG_0].id = ++env->id_gen;
5004 regs[BPF_REG_0].mem_size = meta.mem_size;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005005 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5006 int ret_btf_id;
5007
5008 mark_reg_known_zero(env, regs, BPF_REG_0);
5009 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5010 ret_btf_id = *fn->ret_btf_id;
5011 if (ret_btf_id == 0) {
5012 verbose(env, "invalid return type %d of func %s#%d\n",
5013 fn->ret_type, func_id_name(func_id), func_id);
5014 return -EINVAL;
5015 }
5016 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005017 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005018 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005019 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005020 return -EINVAL;
5021 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005022
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005023 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005024 /* For release_reference() */
5025 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005026 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005027 int id = acquire_reference_state(env, insn_idx);
5028
5029 if (id < 0)
5030 return id;
5031 /* For mark_ptr_or_null_reg() */
5032 regs[BPF_REG_0].id = id;
5033 /* For release_reference() */
5034 regs[BPF_REG_0].ref_obj_id = id;
5035 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005036
Yonghong Song849fa502018-04-28 22:28:09 -07005037 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5038
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005039 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00005040 if (err)
5041 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005042
Song Liufa28dcb2020-06-29 23:28:44 -07005043 if ((func_id == BPF_FUNC_get_stack ||
5044 func_id == BPF_FUNC_get_task_stack) &&
5045 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07005046 const char *err_str;
5047
5048#ifdef CONFIG_PERF_EVENTS
5049 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5050 err_str = "cannot get callchain buffer for func %s#%d\n";
5051#else
5052 err = -ENOTSUPP;
5053 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5054#endif
5055 if (err) {
5056 verbose(env, err_str, func_id_name(func_id), func_id);
5057 return err;
5058 }
5059
5060 env->prog->has_callchain_buf = true;
5061 }
5062
Song Liu5d99cb2c2020-07-23 11:06:45 -07005063 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5064 env->prog->call_get_stack = true;
5065
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005066 if (changes_data)
5067 clear_all_pkt_pointers(env);
5068 return 0;
5069}
5070
Edward Creeb03c9f92017-08-07 15:26:36 +01005071static bool signed_add_overflows(s64 a, s64 b)
5072{
5073 /* Do the add in u64, where overflow is well-defined */
5074 s64 res = (s64)((u64)a + (u64)b);
5075
5076 if (b < 0)
5077 return res > a;
5078 return res < a;
5079}
5080
John Fastabend3f50f132020-03-30 14:36:39 -07005081static bool signed_add32_overflows(s64 a, s64 b)
5082{
5083 /* Do the add in u32, where overflow is well-defined */
5084 s32 res = (s32)((u32)a + (u32)b);
5085
5086 if (b < 0)
5087 return res > a;
5088 return res < a;
5089}
5090
5091static bool signed_sub_overflows(s32 a, s32 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01005092{
5093 /* Do the sub in u64, where overflow is well-defined */
5094 s64 res = (s64)((u64)a - (u64)b);
5095
5096 if (b < 0)
5097 return res < a;
5098 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07005099}
5100
John Fastabend3f50f132020-03-30 14:36:39 -07005101static bool signed_sub32_overflows(s32 a, s32 b)
5102{
5103 /* Do the sub in u64, where overflow is well-defined */
5104 s32 res = (s32)((u32)a - (u32)b);
5105
5106 if (b < 0)
5107 return res < a;
5108 return res > a;
5109}
5110
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005111static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5112 const struct bpf_reg_state *reg,
5113 enum bpf_reg_type type)
5114{
5115 bool known = tnum_is_const(reg->var_off);
5116 s64 val = reg->var_off.value;
5117 s64 smin = reg->smin_value;
5118
5119 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5120 verbose(env, "math between %s pointer and %lld is not allowed\n",
5121 reg_type_str[type], val);
5122 return false;
5123 }
5124
5125 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5126 verbose(env, "%s pointer offset %d is not allowed\n",
5127 reg_type_str[type], reg->off);
5128 return false;
5129 }
5130
5131 if (smin == S64_MIN) {
5132 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5133 reg_type_str[type]);
5134 return false;
5135 }
5136
5137 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5138 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5139 smin, reg_type_str[type]);
5140 return false;
5141 }
5142
5143 return true;
5144}
5145
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005146static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5147{
5148 return &env->insn_aux_data[env->insn_idx];
5149}
5150
5151static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5152 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5153{
5154 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5155 (opcode == BPF_SUB && !off_is_neg);
5156 u32 off;
5157
5158 switch (ptr_reg->type) {
5159 case PTR_TO_STACK:
Andrey Ignatov088ec262019-04-03 23:22:39 -07005160 /* Indirect variable offset stack access is prohibited in
5161 * unprivileged mode so it's not handled here.
5162 */
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005163 off = ptr_reg->off + ptr_reg->var_off.value;
5164 if (mask_to_left)
5165 *ptr_limit = MAX_BPF_STACK + off;
5166 else
5167 *ptr_limit = -off;
5168 return 0;
5169 case PTR_TO_MAP_VALUE:
5170 if (mask_to_left) {
5171 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5172 } else {
5173 off = ptr_reg->smin_value + ptr_reg->off;
5174 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5175 }
5176 return 0;
5177 default:
5178 return -EINVAL;
5179 }
5180}
5181
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005182static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5183 const struct bpf_insn *insn)
5184{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005185 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005186}
5187
5188static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5189 u32 alu_state, u32 alu_limit)
5190{
5191 /* If we arrived here from different branches with different
5192 * state or limits to sanitize, then this won't work.
5193 */
5194 if (aux->alu_state &&
5195 (aux->alu_state != alu_state ||
5196 aux->alu_limit != alu_limit))
5197 return -EACCES;
5198
5199 /* Corresponding fixup done in fixup_bpf_calls(). */
5200 aux->alu_state = alu_state;
5201 aux->alu_limit = alu_limit;
5202 return 0;
5203}
5204
5205static int sanitize_val_alu(struct bpf_verifier_env *env,
5206 struct bpf_insn *insn)
5207{
5208 struct bpf_insn_aux_data *aux = cur_aux(env);
5209
5210 if (can_skip_alu_sanitation(env, insn))
5211 return 0;
5212
5213 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5214}
5215
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005216static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5217 struct bpf_insn *insn,
5218 const struct bpf_reg_state *ptr_reg,
5219 struct bpf_reg_state *dst_reg,
5220 bool off_is_neg)
5221{
5222 struct bpf_verifier_state *vstate = env->cur_state;
5223 struct bpf_insn_aux_data *aux = cur_aux(env);
5224 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5225 u8 opcode = BPF_OP(insn->code);
5226 u32 alu_state, alu_limit;
5227 struct bpf_reg_state tmp;
5228 bool ret;
5229
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005230 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005231 return 0;
5232
5233 /* We already marked aux for masking from non-speculative
5234 * paths, thus we got here in the first place. We only care
5235 * to explore bad access from here.
5236 */
5237 if (vstate->speculative)
5238 goto do_sim;
5239
5240 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5241 alu_state |= ptr_is_dst_reg ?
5242 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5243
5244 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5245 return 0;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005246 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005247 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005248do_sim:
5249 /* Simulate and find potential out-of-bounds access under
5250 * speculative execution from truncation as a result of
5251 * masking when off was not within expected range. If off
5252 * sits in dst, then we temporarily need to move ptr there
5253 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5254 * for cases where we use K-based arithmetic in one direction
5255 * and truncated reg-based in the other in order to explore
5256 * bad access.
5257 */
5258 if (!ptr_is_dst_reg) {
5259 tmp = *dst_reg;
5260 *dst_reg = *ptr_reg;
5261 }
5262 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08005263 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005264 *dst_reg = tmp;
5265 return !ret ? -EFAULT : 0;
5266}
5267
Edward Creef1174f72017-08-07 15:26:19 +01005268/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01005269 * Caller should also handle BPF_MOV case separately.
5270 * If we return -EACCES, caller may want to try again treating pointer as a
5271 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5272 */
5273static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5274 struct bpf_insn *insn,
5275 const struct bpf_reg_state *ptr_reg,
5276 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04005277{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005278 struct bpf_verifier_state *vstate = env->cur_state;
5279 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5280 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01005281 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01005282 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5283 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5284 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5285 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01005286 u32 dst = insn->dst_reg, src = insn->src_reg;
Josef Bacik48461132016-09-28 10:54:32 -04005287 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005288 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04005289
Edward Creef1174f72017-08-07 15:26:19 +01005290 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04005291
Daniel Borkmann6f161012018-01-18 01:15:21 +01005292 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5293 smin_val > smax_val || umin_val > umax_val) {
5294 /* Taint dst register if offset had invalid bounds derived from
5295 * e.g. dead branches.
5296 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005297 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01005298 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04005299 }
5300
Edward Creef1174f72017-08-07 15:26:19 +01005301 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5302 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07005303 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5304 __mark_reg_unknown(env, dst_reg);
5305 return 0;
5306 }
5307
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005308 verbose(env,
5309 "R%d 32-bit pointer arithmetic prohibited\n",
5310 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005311 return -EACCES;
5312 }
David S. Millerd1174412017-05-10 11:22:52 -07005313
Joe Stringeraad2eea2018-10-02 13:35:30 -07005314 switch (ptr_reg->type) {
5315 case PTR_TO_MAP_VALUE_OR_NULL:
5316 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5317 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01005318 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07005319 case CONST_PTR_TO_MAP:
5320 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07005321 case PTR_TO_SOCKET:
5322 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005323 case PTR_TO_SOCK_COMMON:
5324 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005325 case PTR_TO_TCP_SOCK:
5326 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07005327 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07005328 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5329 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01005330 return -EACCES;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01005331 case PTR_TO_MAP_VALUE:
5332 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5333 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5334 off_reg == dst_reg ? dst : src);
5335 return -EACCES;
5336 }
5337 /* fall-through */
Joe Stringeraad2eea2018-10-02 13:35:30 -07005338 default:
5339 break;
Edward Creef1174f72017-08-07 15:26:19 +01005340 }
5341
5342 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5343 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04005344 */
Edward Creef1174f72017-08-07 15:26:19 +01005345 dst_reg->type = ptr_reg->type;
5346 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05005347
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005348 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5349 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5350 return -EINVAL;
5351
John Fastabend3f50f132020-03-30 14:36:39 -07005352 /* pointer types do not carry 32-bit bounds at the moment. */
5353 __mark_reg32_unbounded(dst_reg);
5354
Josef Bacik48461132016-09-28 10:54:32 -04005355 switch (opcode) {
5356 case BPF_ADD:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005357 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5358 if (ret < 0) {
5359 verbose(env, "R%d tried to add from different maps or paths\n", dst);
5360 return ret;
5361 }
Edward Creef1174f72017-08-07 15:26:19 +01005362 /* We can take a fixed offset as long as it doesn't overflow
5363 * the s32 'off' field
5364 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005365 if (known && (ptr_reg->off + smin_val ==
5366 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01005367 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01005368 dst_reg->smin_value = smin_ptr;
5369 dst_reg->smax_value = smax_ptr;
5370 dst_reg->umin_value = umin_ptr;
5371 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01005372 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01005373 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01005374 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01005375 break;
5376 }
Edward Creef1174f72017-08-07 15:26:19 +01005377 /* A new variable offset is created. Note that off_reg->off
5378 * == 0, since it's a scalar.
5379 * dst_reg gets the pointer type and since some positive
5380 * integer value was added to the pointer, give it a new 'id'
5381 * if it's a PTR_TO_PACKET.
5382 * this creates a new 'base' pointer, off_reg (variable) gets
5383 * added into the variable offset, and we copy the fixed offset
5384 * from ptr_reg.
5385 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005386 if (signed_add_overflows(smin_ptr, smin_val) ||
5387 signed_add_overflows(smax_ptr, smax_val)) {
5388 dst_reg->smin_value = S64_MIN;
5389 dst_reg->smax_value = S64_MAX;
5390 } else {
5391 dst_reg->smin_value = smin_ptr + smin_val;
5392 dst_reg->smax_value = smax_ptr + smax_val;
5393 }
5394 if (umin_ptr + umin_val < umin_ptr ||
5395 umax_ptr + umax_val < umax_ptr) {
5396 dst_reg->umin_value = 0;
5397 dst_reg->umax_value = U64_MAX;
5398 } else {
5399 dst_reg->umin_value = umin_ptr + umin_val;
5400 dst_reg->umax_value = umax_ptr + umax_val;
5401 }
Edward Creef1174f72017-08-07 15:26:19 +01005402 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5403 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01005404 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005405 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01005406 dst_reg->id = ++env->id_gen;
5407 /* something was added to pkt_ptr, set range to zero */
Daniel Borkmann09625902018-11-01 00:05:52 +01005408 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01005409 }
Josef Bacik48461132016-09-28 10:54:32 -04005410 break;
5411 case BPF_SUB:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005412 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5413 if (ret < 0) {
5414 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5415 return ret;
5416 }
Edward Creef1174f72017-08-07 15:26:19 +01005417 if (dst_reg == off_reg) {
5418 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005419 verbose(env, "R%d tried to subtract pointer from scalar\n",
5420 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005421 return -EACCES;
5422 }
5423 /* We don't allow subtraction from FP, because (according to
5424 * test_verifier.c test "invalid fp arithmetic", JITs might not
5425 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01005426 */
Edward Creef1174f72017-08-07 15:26:19 +01005427 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005428 verbose(env, "R%d subtraction from stack pointer prohibited\n",
5429 dst);
Edward Creef1174f72017-08-07 15:26:19 +01005430 return -EACCES;
5431 }
Edward Creeb03c9f92017-08-07 15:26:36 +01005432 if (known && (ptr_reg->off - smin_val ==
5433 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01005434 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01005435 dst_reg->smin_value = smin_ptr;
5436 dst_reg->smax_value = smax_ptr;
5437 dst_reg->umin_value = umin_ptr;
5438 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01005439 dst_reg->var_off = ptr_reg->var_off;
5440 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01005441 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01005442 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01005443 break;
5444 }
Edward Creef1174f72017-08-07 15:26:19 +01005445 /* A new variable offset is created. If the subtrahend is known
5446 * nonnegative, then any reg->range we had before is still good.
5447 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005448 if (signed_sub_overflows(smin_ptr, smax_val) ||
5449 signed_sub_overflows(smax_ptr, smin_val)) {
5450 /* Overflow possible, we know nothing */
5451 dst_reg->smin_value = S64_MIN;
5452 dst_reg->smax_value = S64_MAX;
5453 } else {
5454 dst_reg->smin_value = smin_ptr - smax_val;
5455 dst_reg->smax_value = smax_ptr - smin_val;
5456 }
5457 if (umin_ptr < umax_val) {
5458 /* Overflow possible, we know nothing */
5459 dst_reg->umin_value = 0;
5460 dst_reg->umax_value = U64_MAX;
5461 } else {
5462 /* Cannot overflow (as long as bounds are consistent) */
5463 dst_reg->umin_value = umin_ptr - umax_val;
5464 dst_reg->umax_value = umax_ptr - umin_val;
5465 }
Edward Creef1174f72017-08-07 15:26:19 +01005466 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5467 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01005468 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005469 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01005470 dst_reg->id = ++env->id_gen;
5471 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01005472 if (smin_val < 0)
Daniel Borkmann09625902018-11-01 00:05:52 +01005473 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01005474 }
5475 break;
5476 case BPF_AND:
5477 case BPF_OR:
5478 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005479 /* bitwise ops on pointers are troublesome, prohibit. */
5480 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5481 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01005482 return -EACCES;
5483 default:
5484 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005485 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5486 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01005487 return -EACCES;
5488 }
5489
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005490 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5491 return -EINVAL;
5492
Edward Creeb03c9f92017-08-07 15:26:36 +01005493 __update_reg_bounds(dst_reg);
5494 __reg_deduce_bounds(dst_reg);
5495 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01005496
5497 /* For unprivileged we require that resulting offset must be in bounds
5498 * in order to be able to sanitize access later on.
5499 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005500 if (!env->bypass_spec_v1) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01005501 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5502 check_map_access(env, dst, dst_reg->off, 1, false)) {
5503 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5504 "prohibited for !root\n", dst);
5505 return -EACCES;
5506 } else if (dst_reg->type == PTR_TO_STACK &&
5507 check_stack_access(env, dst_reg, dst_reg->off +
5508 dst_reg->var_off.value, 1)) {
5509 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5510 "prohibited for !root\n", dst);
5511 return -EACCES;
5512 }
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01005513 }
5514
Edward Creef1174f72017-08-07 15:26:19 +01005515 return 0;
5516}
5517
John Fastabend3f50f132020-03-30 14:36:39 -07005518static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5519 struct bpf_reg_state *src_reg)
5520{
5521 s32 smin_val = src_reg->s32_min_value;
5522 s32 smax_val = src_reg->s32_max_value;
5523 u32 umin_val = src_reg->u32_min_value;
5524 u32 umax_val = src_reg->u32_max_value;
5525
5526 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5527 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5528 dst_reg->s32_min_value = S32_MIN;
5529 dst_reg->s32_max_value = S32_MAX;
5530 } else {
5531 dst_reg->s32_min_value += smin_val;
5532 dst_reg->s32_max_value += smax_val;
5533 }
5534 if (dst_reg->u32_min_value + umin_val < umin_val ||
5535 dst_reg->u32_max_value + umax_val < umax_val) {
5536 dst_reg->u32_min_value = 0;
5537 dst_reg->u32_max_value = U32_MAX;
5538 } else {
5539 dst_reg->u32_min_value += umin_val;
5540 dst_reg->u32_max_value += umax_val;
5541 }
5542}
5543
John Fastabend07cd2632020-03-24 10:38:15 -07005544static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5545 struct bpf_reg_state *src_reg)
5546{
5547 s64 smin_val = src_reg->smin_value;
5548 s64 smax_val = src_reg->smax_value;
5549 u64 umin_val = src_reg->umin_value;
5550 u64 umax_val = src_reg->umax_value;
5551
5552 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5553 signed_add_overflows(dst_reg->smax_value, smax_val)) {
5554 dst_reg->smin_value = S64_MIN;
5555 dst_reg->smax_value = S64_MAX;
5556 } else {
5557 dst_reg->smin_value += smin_val;
5558 dst_reg->smax_value += smax_val;
5559 }
5560 if (dst_reg->umin_value + umin_val < umin_val ||
5561 dst_reg->umax_value + umax_val < umax_val) {
5562 dst_reg->umin_value = 0;
5563 dst_reg->umax_value = U64_MAX;
5564 } else {
5565 dst_reg->umin_value += umin_val;
5566 dst_reg->umax_value += umax_val;
5567 }
John Fastabend3f50f132020-03-30 14:36:39 -07005568}
5569
5570static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5571 struct bpf_reg_state *src_reg)
5572{
5573 s32 smin_val = src_reg->s32_min_value;
5574 s32 smax_val = src_reg->s32_max_value;
5575 u32 umin_val = src_reg->u32_min_value;
5576 u32 umax_val = src_reg->u32_max_value;
5577
5578 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5579 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5580 /* Overflow possible, we know nothing */
5581 dst_reg->s32_min_value = S32_MIN;
5582 dst_reg->s32_max_value = S32_MAX;
5583 } else {
5584 dst_reg->s32_min_value -= smax_val;
5585 dst_reg->s32_max_value -= smin_val;
5586 }
5587 if (dst_reg->u32_min_value < umax_val) {
5588 /* Overflow possible, we know nothing */
5589 dst_reg->u32_min_value = 0;
5590 dst_reg->u32_max_value = U32_MAX;
5591 } else {
5592 /* Cannot overflow (as long as bounds are consistent) */
5593 dst_reg->u32_min_value -= umax_val;
5594 dst_reg->u32_max_value -= umin_val;
5595 }
John Fastabend07cd2632020-03-24 10:38:15 -07005596}
5597
5598static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5599 struct bpf_reg_state *src_reg)
5600{
5601 s64 smin_val = src_reg->smin_value;
5602 s64 smax_val = src_reg->smax_value;
5603 u64 umin_val = src_reg->umin_value;
5604 u64 umax_val = src_reg->umax_value;
5605
5606 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5607 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5608 /* Overflow possible, we know nothing */
5609 dst_reg->smin_value = S64_MIN;
5610 dst_reg->smax_value = S64_MAX;
5611 } else {
5612 dst_reg->smin_value -= smax_val;
5613 dst_reg->smax_value -= smin_val;
5614 }
5615 if (dst_reg->umin_value < umax_val) {
5616 /* Overflow possible, we know nothing */
5617 dst_reg->umin_value = 0;
5618 dst_reg->umax_value = U64_MAX;
5619 } else {
5620 /* Cannot overflow (as long as bounds are consistent) */
5621 dst_reg->umin_value -= umax_val;
5622 dst_reg->umax_value -= umin_val;
5623 }
John Fastabend3f50f132020-03-30 14:36:39 -07005624}
5625
5626static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5627 struct bpf_reg_state *src_reg)
5628{
5629 s32 smin_val = src_reg->s32_min_value;
5630 u32 umin_val = src_reg->u32_min_value;
5631 u32 umax_val = src_reg->u32_max_value;
5632
5633 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5634 /* Ain't nobody got time to multiply that sign */
5635 __mark_reg32_unbounded(dst_reg);
5636 return;
5637 }
5638 /* Both values are positive, so we can work with unsigned and
5639 * copy the result to signed (unless it exceeds S32_MAX).
5640 */
5641 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5642 /* Potential overflow, we know nothing */
5643 __mark_reg32_unbounded(dst_reg);
5644 return;
5645 }
5646 dst_reg->u32_min_value *= umin_val;
5647 dst_reg->u32_max_value *= umax_val;
5648 if (dst_reg->u32_max_value > S32_MAX) {
5649 /* Overflow possible, we know nothing */
5650 dst_reg->s32_min_value = S32_MIN;
5651 dst_reg->s32_max_value = S32_MAX;
5652 } else {
5653 dst_reg->s32_min_value = dst_reg->u32_min_value;
5654 dst_reg->s32_max_value = dst_reg->u32_max_value;
5655 }
John Fastabend07cd2632020-03-24 10:38:15 -07005656}
5657
5658static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5659 struct bpf_reg_state *src_reg)
5660{
5661 s64 smin_val = src_reg->smin_value;
5662 u64 umin_val = src_reg->umin_value;
5663 u64 umax_val = src_reg->umax_value;
5664
John Fastabend07cd2632020-03-24 10:38:15 -07005665 if (smin_val < 0 || dst_reg->smin_value < 0) {
5666 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07005667 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07005668 return;
5669 }
5670 /* Both values are positive, so we can work with unsigned and
5671 * copy the result to signed (unless it exceeds S64_MAX).
5672 */
5673 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5674 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07005675 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07005676 return;
5677 }
5678 dst_reg->umin_value *= umin_val;
5679 dst_reg->umax_value *= umax_val;
5680 if (dst_reg->umax_value > S64_MAX) {
5681 /* Overflow possible, we know nothing */
5682 dst_reg->smin_value = S64_MIN;
5683 dst_reg->smax_value = S64_MAX;
5684 } else {
5685 dst_reg->smin_value = dst_reg->umin_value;
5686 dst_reg->smax_value = dst_reg->umax_value;
5687 }
5688}
5689
John Fastabend3f50f132020-03-30 14:36:39 -07005690static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5691 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07005692{
John Fastabend3f50f132020-03-30 14:36:39 -07005693 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5694 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5695 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5696 s32 smin_val = src_reg->s32_min_value;
5697 u32 umax_val = src_reg->u32_max_value;
5698
5699 /* Assuming scalar64_min_max_and will be called so its safe
5700 * to skip updating register for known 32-bit case.
5701 */
5702 if (src_known && dst_known)
5703 return;
John Fastabend07cd2632020-03-24 10:38:15 -07005704
5705 /* We get our minimum from the var_off, since that's inherently
5706 * bitwise. Our maximum is the minimum of the operands' maxima.
5707 */
John Fastabend3f50f132020-03-30 14:36:39 -07005708 dst_reg->u32_min_value = var32_off.value;
5709 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5710 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5711 /* Lose signed bounds when ANDing negative numbers,
5712 * ain't nobody got time for that.
5713 */
5714 dst_reg->s32_min_value = S32_MIN;
5715 dst_reg->s32_max_value = S32_MAX;
5716 } else {
5717 /* ANDing two positives gives a positive, so safe to
5718 * cast result into s64.
5719 */
5720 dst_reg->s32_min_value = dst_reg->u32_min_value;
5721 dst_reg->s32_max_value = dst_reg->u32_max_value;
5722 }
5723
5724}
5725
5726static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5727 struct bpf_reg_state *src_reg)
5728{
5729 bool src_known = tnum_is_const(src_reg->var_off);
5730 bool dst_known = tnum_is_const(dst_reg->var_off);
5731 s64 smin_val = src_reg->smin_value;
5732 u64 umax_val = src_reg->umax_value;
5733
5734 if (src_known && dst_known) {
5735 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5736 src_reg->var_off.value);
5737 return;
5738 }
5739
5740 /* We get our minimum from the var_off, since that's inherently
5741 * bitwise. Our maximum is the minimum of the operands' maxima.
5742 */
John Fastabend07cd2632020-03-24 10:38:15 -07005743 dst_reg->umin_value = dst_reg->var_off.value;
5744 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5745 if (dst_reg->smin_value < 0 || smin_val < 0) {
5746 /* Lose signed bounds when ANDing negative numbers,
5747 * ain't nobody got time for that.
5748 */
5749 dst_reg->smin_value = S64_MIN;
5750 dst_reg->smax_value = S64_MAX;
5751 } else {
5752 /* ANDing two positives gives a positive, so safe to
5753 * cast result into s64.
5754 */
5755 dst_reg->smin_value = dst_reg->umin_value;
5756 dst_reg->smax_value = dst_reg->umax_value;
5757 }
5758 /* We may learn something more from the var_off */
5759 __update_reg_bounds(dst_reg);
5760}
5761
John Fastabend3f50f132020-03-30 14:36:39 -07005762static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5763 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07005764{
John Fastabend3f50f132020-03-30 14:36:39 -07005765 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5766 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5767 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5768 s32 smin_val = src_reg->smin_value;
5769 u32 umin_val = src_reg->umin_value;
5770
5771 /* Assuming scalar64_min_max_or will be called so it is safe
5772 * to skip updating register for known case.
5773 */
5774 if (src_known && dst_known)
5775 return;
John Fastabend07cd2632020-03-24 10:38:15 -07005776
5777 /* We get our maximum from the var_off, and our minimum is the
5778 * maximum of the operands' minima
5779 */
John Fastabend3f50f132020-03-30 14:36:39 -07005780 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5781 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5782 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5783 /* Lose signed bounds when ORing negative numbers,
5784 * ain't nobody got time for that.
5785 */
5786 dst_reg->s32_min_value = S32_MIN;
5787 dst_reg->s32_max_value = S32_MAX;
5788 } else {
5789 /* ORing two positives gives a positive, so safe to
5790 * cast result into s64.
5791 */
5792 dst_reg->s32_min_value = dst_reg->umin_value;
5793 dst_reg->s32_max_value = dst_reg->umax_value;
5794 }
5795}
5796
5797static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5798 struct bpf_reg_state *src_reg)
5799{
5800 bool src_known = tnum_is_const(src_reg->var_off);
5801 bool dst_known = tnum_is_const(dst_reg->var_off);
5802 s64 smin_val = src_reg->smin_value;
5803 u64 umin_val = src_reg->umin_value;
5804
5805 if (src_known && dst_known) {
5806 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5807 src_reg->var_off.value);
5808 return;
5809 }
5810
5811 /* We get our maximum from the var_off, and our minimum is the
5812 * maximum of the operands' minima
5813 */
John Fastabend07cd2632020-03-24 10:38:15 -07005814 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5815 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5816 if (dst_reg->smin_value < 0 || smin_val < 0) {
5817 /* Lose signed bounds when ORing negative numbers,
5818 * ain't nobody got time for that.
5819 */
5820 dst_reg->smin_value = S64_MIN;
5821 dst_reg->smax_value = S64_MAX;
5822 } else {
5823 /* ORing two positives gives a positive, so safe to
5824 * cast result into s64.
5825 */
5826 dst_reg->smin_value = dst_reg->umin_value;
5827 dst_reg->smax_value = dst_reg->umax_value;
5828 }
5829 /* We may learn something more from the var_off */
5830 __update_reg_bounds(dst_reg);
5831}
5832
Yonghong Song2921c902020-08-24 23:46:08 -07005833static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
5834 struct bpf_reg_state *src_reg)
5835{
5836 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5837 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5838 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5839 s32 smin_val = src_reg->s32_min_value;
5840
5841 /* Assuming scalar64_min_max_xor will be called so it is safe
5842 * to skip updating register for known case.
5843 */
5844 if (src_known && dst_known)
5845 return;
5846
5847 /* We get both minimum and maximum from the var32_off. */
5848 dst_reg->u32_min_value = var32_off.value;
5849 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5850
5851 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
5852 /* XORing two positive sign numbers gives a positive,
5853 * so safe to cast u32 result into s32.
5854 */
5855 dst_reg->s32_min_value = dst_reg->u32_min_value;
5856 dst_reg->s32_max_value = dst_reg->u32_max_value;
5857 } else {
5858 dst_reg->s32_min_value = S32_MIN;
5859 dst_reg->s32_max_value = S32_MAX;
5860 }
5861}
5862
5863static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
5864 struct bpf_reg_state *src_reg)
5865{
5866 bool src_known = tnum_is_const(src_reg->var_off);
5867 bool dst_known = tnum_is_const(dst_reg->var_off);
5868 s64 smin_val = src_reg->smin_value;
5869
5870 if (src_known && dst_known) {
5871 /* dst_reg->var_off.value has been updated earlier */
5872 __mark_reg_known(dst_reg, dst_reg->var_off.value);
5873 return;
5874 }
5875
5876 /* We get both minimum and maximum from the var_off. */
5877 dst_reg->umin_value = dst_reg->var_off.value;
5878 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5879
5880 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
5881 /* XORing two positive sign numbers gives a positive,
5882 * so safe to cast u64 result into s64.
5883 */
5884 dst_reg->smin_value = dst_reg->umin_value;
5885 dst_reg->smax_value = dst_reg->umax_value;
5886 } else {
5887 dst_reg->smin_value = S64_MIN;
5888 dst_reg->smax_value = S64_MAX;
5889 }
5890
5891 __update_reg_bounds(dst_reg);
5892}
5893
John Fastabend3f50f132020-03-30 14:36:39 -07005894static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5895 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07005896{
John Fastabend07cd2632020-03-24 10:38:15 -07005897 /* We lose all sign bit information (except what we can pick
5898 * up from var_off)
5899 */
John Fastabend3f50f132020-03-30 14:36:39 -07005900 dst_reg->s32_min_value = S32_MIN;
5901 dst_reg->s32_max_value = S32_MAX;
5902 /* If we might shift our top bit out, then we know nothing */
5903 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
5904 dst_reg->u32_min_value = 0;
5905 dst_reg->u32_max_value = U32_MAX;
5906 } else {
5907 dst_reg->u32_min_value <<= umin_val;
5908 dst_reg->u32_max_value <<= umax_val;
5909 }
5910}
5911
5912static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5913 struct bpf_reg_state *src_reg)
5914{
5915 u32 umax_val = src_reg->u32_max_value;
5916 u32 umin_val = src_reg->u32_min_value;
5917 /* u32 alu operation will zext upper bits */
5918 struct tnum subreg = tnum_subreg(dst_reg->var_off);
5919
5920 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5921 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
5922 /* Not required but being careful mark reg64 bounds as unknown so
5923 * that we are forced to pick them up from tnum and zext later and
5924 * if some path skips this step we are still safe.
5925 */
5926 __mark_reg64_unbounded(dst_reg);
5927 __update_reg32_bounds(dst_reg);
5928}
5929
5930static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
5931 u64 umin_val, u64 umax_val)
5932{
5933 /* Special case <<32 because it is a common compiler pattern to sign
5934 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
5935 * positive we know this shift will also be positive so we can track
5936 * bounds correctly. Otherwise we lose all sign bit information except
5937 * what we can pick up from var_off. Perhaps we can generalize this
5938 * later to shifts of any length.
5939 */
5940 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
5941 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
5942 else
5943 dst_reg->smax_value = S64_MAX;
5944
5945 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
5946 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
5947 else
5948 dst_reg->smin_value = S64_MIN;
5949
John Fastabend07cd2632020-03-24 10:38:15 -07005950 /* If we might shift our top bit out, then we know nothing */
5951 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
5952 dst_reg->umin_value = 0;
5953 dst_reg->umax_value = U64_MAX;
5954 } else {
5955 dst_reg->umin_value <<= umin_val;
5956 dst_reg->umax_value <<= umax_val;
5957 }
John Fastabend3f50f132020-03-30 14:36:39 -07005958}
5959
5960static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
5961 struct bpf_reg_state *src_reg)
5962{
5963 u64 umax_val = src_reg->umax_value;
5964 u64 umin_val = src_reg->umin_value;
5965
5966 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
5967 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
5968 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5969
John Fastabend07cd2632020-03-24 10:38:15 -07005970 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
5971 /* We may learn something more from the var_off */
5972 __update_reg_bounds(dst_reg);
5973}
5974
John Fastabend3f50f132020-03-30 14:36:39 -07005975static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
5976 struct bpf_reg_state *src_reg)
5977{
5978 struct tnum subreg = tnum_subreg(dst_reg->var_off);
5979 u32 umax_val = src_reg->u32_max_value;
5980 u32 umin_val = src_reg->u32_min_value;
5981
5982 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
5983 * be negative, then either:
5984 * 1) src_reg might be zero, so the sign bit of the result is
5985 * unknown, so we lose our signed bounds
5986 * 2) it's known negative, thus the unsigned bounds capture the
5987 * signed bounds
5988 * 3) the signed bounds cross zero, so they tell us nothing
5989 * about the result
5990 * If the value in dst_reg is known nonnegative, then again the
5991 * unsigned bounts capture the signed bounds.
5992 * Thus, in all cases it suffices to blow away our signed bounds
5993 * and rely on inferring new ones from the unsigned bounds and
5994 * var_off of the result.
5995 */
5996 dst_reg->s32_min_value = S32_MIN;
5997 dst_reg->s32_max_value = S32_MAX;
5998
5999 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6000 dst_reg->u32_min_value >>= umax_val;
6001 dst_reg->u32_max_value >>= umin_val;
6002
6003 __mark_reg64_unbounded(dst_reg);
6004 __update_reg32_bounds(dst_reg);
6005}
6006
John Fastabend07cd2632020-03-24 10:38:15 -07006007static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6008 struct bpf_reg_state *src_reg)
6009{
6010 u64 umax_val = src_reg->umax_value;
6011 u64 umin_val = src_reg->umin_value;
6012
6013 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6014 * be negative, then either:
6015 * 1) src_reg might be zero, so the sign bit of the result is
6016 * unknown, so we lose our signed bounds
6017 * 2) it's known negative, thus the unsigned bounds capture the
6018 * signed bounds
6019 * 3) the signed bounds cross zero, so they tell us nothing
6020 * about the result
6021 * If the value in dst_reg is known nonnegative, then again the
6022 * unsigned bounts capture the signed bounds.
6023 * Thus, in all cases it suffices to blow away our signed bounds
6024 * and rely on inferring new ones from the unsigned bounds and
6025 * var_off of the result.
6026 */
6027 dst_reg->smin_value = S64_MIN;
6028 dst_reg->smax_value = S64_MAX;
6029 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6030 dst_reg->umin_value >>= umax_val;
6031 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006032
6033 /* Its not easy to operate on alu32 bounds here because it depends
6034 * on bits being shifted in. Take easy way out and mark unbounded
6035 * so we can recalculate later from tnum.
6036 */
6037 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006038 __update_reg_bounds(dst_reg);
6039}
6040
John Fastabend3f50f132020-03-30 14:36:39 -07006041static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6042 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006043{
John Fastabend3f50f132020-03-30 14:36:39 -07006044 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07006045
6046 /* Upon reaching here, src_known is true and
6047 * umax_val is equal to umin_val.
6048 */
John Fastabend3f50f132020-03-30 14:36:39 -07006049 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6050 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07006051
John Fastabend3f50f132020-03-30 14:36:39 -07006052 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6053
6054 /* blow away the dst_reg umin_value/umax_value and rely on
6055 * dst_reg var_off to refine the result.
6056 */
6057 dst_reg->u32_min_value = 0;
6058 dst_reg->u32_max_value = U32_MAX;
6059
6060 __mark_reg64_unbounded(dst_reg);
6061 __update_reg32_bounds(dst_reg);
6062}
6063
6064static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6065 struct bpf_reg_state *src_reg)
6066{
6067 u64 umin_val = src_reg->umin_value;
6068
6069 /* Upon reaching here, src_known is true and umax_val is equal
6070 * to umin_val.
6071 */
6072 dst_reg->smin_value >>= umin_val;
6073 dst_reg->smax_value >>= umin_val;
6074
6075 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07006076
6077 /* blow away the dst_reg umin_value/umax_value and rely on
6078 * dst_reg var_off to refine the result.
6079 */
6080 dst_reg->umin_value = 0;
6081 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07006082
6083 /* Its not easy to operate on alu32 bounds here because it depends
6084 * on bits being shifted in from upper 32-bits. Take easy way out
6085 * and mark unbounded so we can recalculate later from tnum.
6086 */
6087 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006088 __update_reg_bounds(dst_reg);
6089}
6090
Jann Horn468f6ea2017-12-18 20:11:56 -08006091/* WARNING: This function does calculations on 64-bit values, but the actual
6092 * execution may occur on 32-bit values. Therefore, things like bitshifts
6093 * need extra checks in the 32-bit case.
6094 */
Edward Creef1174f72017-08-07 15:26:19 +01006095static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6096 struct bpf_insn *insn,
6097 struct bpf_reg_state *dst_reg,
6098 struct bpf_reg_state src_reg)
6099{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006100 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01006101 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08006102 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01006103 s64 smin_val, smax_val;
6104 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006105 s32 s32_min_val, s32_max_val;
6106 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08006107 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006108 u32 dst = insn->dst_reg;
6109 int ret;
John Fastabend3f50f132020-03-30 14:36:39 -07006110 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Jann Hornb7992072018-10-05 18:17:59 +02006111
Edward Creeb03c9f92017-08-07 15:26:36 +01006112 smin_val = src_reg.smin_value;
6113 smax_val = src_reg.smax_value;
6114 umin_val = src_reg.umin_value;
6115 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01006116
John Fastabend3f50f132020-03-30 14:36:39 -07006117 s32_min_val = src_reg.s32_min_value;
6118 s32_max_val = src_reg.s32_max_value;
6119 u32_min_val = src_reg.u32_min_value;
6120 u32_max_val = src_reg.u32_max_value;
6121
6122 if (alu32) {
6123 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006124 if ((src_known &&
6125 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6126 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6127 /* Taint dst register if offset had invalid bounds
6128 * derived from e.g. dead branches.
6129 */
6130 __mark_reg_unknown(env, dst_reg);
6131 return 0;
6132 }
6133 } else {
6134 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006135 if ((src_known &&
6136 (smin_val != smax_val || umin_val != umax_val)) ||
6137 smin_val > smax_val || umin_val > umax_val) {
6138 /* Taint dst register if offset had invalid bounds
6139 * derived from e.g. dead branches.
6140 */
6141 __mark_reg_unknown(env, dst_reg);
6142 return 0;
6143 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01006144 }
6145
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006146 if (!src_known &&
6147 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006148 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006149 return 0;
6150 }
6151
John Fastabend3f50f132020-03-30 14:36:39 -07006152 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6153 * There are two classes of instructions: The first class we track both
6154 * alu32 and alu64 sign/unsigned bounds independently this provides the
6155 * greatest amount of precision when alu operations are mixed with jmp32
6156 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6157 * and BPF_OR. This is possible because these ops have fairly easy to
6158 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6159 * See alu32 verifier tests for examples. The second class of
6160 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6161 * with regards to tracking sign/unsigned bounds because the bits may
6162 * cross subreg boundaries in the alu64 case. When this happens we mark
6163 * the reg unbounded in the subreg bound space and use the resulting
6164 * tnum to calculate an approximation of the sign/unsigned bounds.
6165 */
Edward Creef1174f72017-08-07 15:26:19 +01006166 switch (opcode) {
6167 case BPF_ADD:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006168 ret = sanitize_val_alu(env, insn);
6169 if (ret < 0) {
6170 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6171 return ret;
6172 }
John Fastabend3f50f132020-03-30 14:36:39 -07006173 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006174 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006175 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01006176 break;
6177 case BPF_SUB:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006178 ret = sanitize_val_alu(env, insn);
6179 if (ret < 0) {
6180 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6181 return ret;
6182 }
John Fastabend3f50f132020-03-30 14:36:39 -07006183 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006184 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006185 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04006186 break;
6187 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07006188 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6189 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006190 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006191 break;
6192 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07006193 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6194 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006195 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006196 break;
6197 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07006198 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6199 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006200 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006201 break;
Yonghong Song2921c902020-08-24 23:46:08 -07006202 case BPF_XOR:
6203 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6204 scalar32_min_max_xor(dst_reg, &src_reg);
6205 scalar_min_max_xor(dst_reg, &src_reg);
6206 break;
Josef Bacik48461132016-09-28 10:54:32 -04006207 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006208 if (umax_val >= insn_bitness) {
6209 /* Shifts greater than 31 or 63 are undefined.
6210 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006211 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006212 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006213 break;
6214 }
John Fastabend3f50f132020-03-30 14:36:39 -07006215 if (alu32)
6216 scalar32_min_max_lsh(dst_reg, &src_reg);
6217 else
6218 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006219 break;
6220 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006221 if (umax_val >= insn_bitness) {
6222 /* Shifts greater than 31 or 63 are undefined.
6223 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006224 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006225 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006226 break;
6227 }
John Fastabend3f50f132020-03-30 14:36:39 -07006228 if (alu32)
6229 scalar32_min_max_rsh(dst_reg, &src_reg);
6230 else
6231 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006232 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006233 case BPF_ARSH:
6234 if (umax_val >= insn_bitness) {
6235 /* Shifts greater than 31 or 63 are undefined.
6236 * This includes shifts by a negative number.
6237 */
6238 mark_reg_unknown(env, regs, insn->dst_reg);
6239 break;
6240 }
John Fastabend3f50f132020-03-30 14:36:39 -07006241 if (alu32)
6242 scalar32_min_max_arsh(dst_reg, &src_reg);
6243 else
6244 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006245 break;
Josef Bacik48461132016-09-28 10:54:32 -04006246 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006247 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006248 break;
6249 }
6250
John Fastabend3f50f132020-03-30 14:36:39 -07006251 /* ALU32 ops are zero extended into 64bit register */
6252 if (alu32)
6253 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08006254
John Fastabend294f2fc2020-03-24 10:38:37 -07006255 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01006256 __reg_deduce_bounds(dst_reg);
6257 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006258 return 0;
6259}
6260
6261/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6262 * and var_off.
6263 */
6264static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6265 struct bpf_insn *insn)
6266{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006267 struct bpf_verifier_state *vstate = env->cur_state;
6268 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6269 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01006270 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6271 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006272 int err;
Edward Creef1174f72017-08-07 15:26:19 +01006273
6274 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01006275 src_reg = NULL;
6276 if (dst_reg->type != SCALAR_VALUE)
6277 ptr_reg = dst_reg;
6278 if (BPF_SRC(insn->code) == BPF_X) {
6279 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01006280 if (src_reg->type != SCALAR_VALUE) {
6281 if (dst_reg->type != SCALAR_VALUE) {
6282 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006283 * an arbitrary scalar. Disallow all math except
6284 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01006285 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07006286 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006287 mark_reg_unknown(env, regs, insn->dst_reg);
6288 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01006289 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006290 verbose(env, "R%d pointer %s pointer prohibited\n",
6291 insn->dst_reg,
6292 bpf_alu_string[opcode >> 4]);
6293 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01006294 } else {
6295 /* scalar += pointer
6296 * This is legal, but we have to reverse our
6297 * src/dest handling in computing the range
6298 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006299 err = mark_chain_precision(env, insn->dst_reg);
6300 if (err)
6301 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006302 return adjust_ptr_min_max_vals(env, insn,
6303 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006304 }
6305 } else if (ptr_reg) {
6306 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006307 err = mark_chain_precision(env, insn->src_reg);
6308 if (err)
6309 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006310 return adjust_ptr_min_max_vals(env, insn,
6311 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006312 }
6313 } else {
6314 /* Pretend the src is a reg with a known value, since we only
6315 * need to be able to read from this state.
6316 */
6317 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01006318 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01006319 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006320 if (ptr_reg) /* pointer += K */
6321 return adjust_ptr_min_max_vals(env, insn,
6322 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006323 }
6324
6325 /* Got here implies adding two SCALAR_VALUEs */
6326 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006327 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006328 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01006329 return -EINVAL;
6330 }
6331 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006332 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006333 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01006334 return -EINVAL;
6335 }
6336 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006337}
6338
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006339/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006340static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006341{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006342 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006343 u8 opcode = BPF_OP(insn->code);
6344 int err;
6345
6346 if (opcode == BPF_END || opcode == BPF_NEG) {
6347 if (opcode == BPF_NEG) {
6348 if (BPF_SRC(insn->code) != 0 ||
6349 insn->src_reg != BPF_REG_0 ||
6350 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006351 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006352 return -EINVAL;
6353 }
6354 } else {
6355 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01006356 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6357 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006358 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006359 return -EINVAL;
6360 }
6361 }
6362
6363 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01006364 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006365 if (err)
6366 return err;
6367
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006368 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006369 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006370 insn->dst_reg);
6371 return -EACCES;
6372 }
6373
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006374 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01006375 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006376 if (err)
6377 return err;
6378
6379 } else if (opcode == BPF_MOV) {
6380
6381 if (BPF_SRC(insn->code) == BPF_X) {
6382 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006383 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006384 return -EINVAL;
6385 }
6386
6387 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01006388 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006389 if (err)
6390 return err;
6391 } else {
6392 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006393 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006394 return -EINVAL;
6395 }
6396 }
6397
Arthur Fabrefbeb1602018-07-31 18:17:22 +01006398 /* check dest operand, mark as required later */
6399 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006400 if (err)
6401 return err;
6402
6403 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05006404 struct bpf_reg_state *src_reg = regs + insn->src_reg;
6405 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6406
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006407 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6408 /* case: R1 = R2
6409 * copy register state to dest reg
6410 */
Jiong Wange434b8c2018-12-07 12:16:18 -05006411 *dst_reg = *src_reg;
6412 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01006413 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006414 } else {
Edward Creef1174f72017-08-07 15:26:19 +01006415 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006416 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006417 verbose(env,
6418 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006419 insn->src_reg);
6420 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05006421 } else if (src_reg->type == SCALAR_VALUE) {
6422 *dst_reg = *src_reg;
6423 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01006424 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05006425 } else {
6426 mark_reg_unknown(env, regs,
6427 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006428 }
John Fastabend3f50f132020-03-30 14:36:39 -07006429 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006430 }
6431 } else {
6432 /* case: R = imm
6433 * remember the value we stored into this reg
6434 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01006435 /* clear any state __mark_reg_known doesn't set */
6436 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006437 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08006438 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6439 __mark_reg_known(regs + insn->dst_reg,
6440 insn->imm);
6441 } else {
6442 __mark_reg_known(regs + insn->dst_reg,
6443 (u32)insn->imm);
6444 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006445 }
6446
6447 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006448 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006449 return -EINVAL;
6450
6451 } else { /* all other ALU ops: and, sub, xor, add, ... */
6452
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006453 if (BPF_SRC(insn->code) == BPF_X) {
6454 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006455 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006456 return -EINVAL;
6457 }
6458 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006459 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006460 if (err)
6461 return err;
6462 } else {
6463 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006464 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006465 return -EINVAL;
6466 }
6467 }
6468
6469 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006470 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006471 if (err)
6472 return err;
6473
6474 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6475 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006476 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006477 return -EINVAL;
6478 }
6479
Rabin Vincent229394e82016-01-12 20:17:08 +01006480 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6481 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6482 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6483
6484 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006485 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01006486 return -EINVAL;
6487 }
6488 }
6489
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006490 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01006491 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006492 if (err)
6493 return err;
6494
Edward Creef1174f72017-08-07 15:26:19 +01006495 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006496 }
6497
6498 return 0;
6499}
6500
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006501static void __find_good_pkt_pointers(struct bpf_func_state *state,
6502 struct bpf_reg_state *dst_reg,
6503 enum bpf_reg_type type, u16 new_range)
6504{
6505 struct bpf_reg_state *reg;
6506 int i;
6507
6508 for (i = 0; i < MAX_BPF_REG; i++) {
6509 reg = &state->regs[i];
6510 if (reg->type == type && reg->id == dst_reg->id)
6511 /* keep the maximum range already checked */
6512 reg->range = max(reg->range, new_range);
6513 }
6514
6515 bpf_for_each_spilled_reg(i, state, reg) {
6516 if (!reg)
6517 continue;
6518 if (reg->type == type && reg->id == dst_reg->id)
6519 reg->range = max(reg->range, new_range);
6520 }
6521}
6522
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006523static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006524 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01006525 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006526 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006527{
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006528 u16 new_range;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006529 int i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006530
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006531 if (dst_reg->off < 0 ||
6532 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01006533 /* This doesn't give us any range */
6534 return;
6535
Edward Creeb03c9f92017-08-07 15:26:36 +01006536 if (dst_reg->umax_value > MAX_PACKET_OFF ||
6537 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01006538 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6539 * than pkt_end, but that's because it's also less than pkt.
6540 */
6541 return;
6542
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006543 new_range = dst_reg->off;
6544 if (range_right_open)
6545 new_range--;
6546
6547 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006548 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006549 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006550 *
6551 * r2 = r3;
6552 * r2 += 8;
6553 * if (r2 > pkt_end) goto <handle exception>
6554 * <access okay>
6555 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006556 * r2 = r3;
6557 * r2 += 8;
6558 * if (r2 < pkt_end) goto <access okay>
6559 * <handle exception>
6560 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006561 * Where:
6562 * r2 == dst_reg, pkt_end == src_reg
6563 * r2=pkt(id=n,off=8,r=0)
6564 * r3=pkt(id=n,off=0,r=0)
6565 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006566 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006567 *
6568 * r2 = r3;
6569 * r2 += 8;
6570 * if (pkt_end >= r2) goto <access okay>
6571 * <handle exception>
6572 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006573 * r2 = r3;
6574 * r2 += 8;
6575 * if (pkt_end <= r2) goto <handle exception>
6576 * <access okay>
6577 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006578 * Where:
6579 * pkt_end == dst_reg, r2 == src_reg
6580 * r2=pkt(id=n,off=8,r=0)
6581 * r3=pkt(id=n,off=0,r=0)
6582 *
6583 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02006584 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6585 * and [r3, r3 + 8-1) respectively is safe to access depending on
6586 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006587 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02006588
Edward Creef1174f72017-08-07 15:26:19 +01006589 /* If our ids match, then we must have the same max_value. And we
6590 * don't care about the other reg's fixed offset, since if it's too big
6591 * the range won't allow anything.
6592 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6593 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006594 for (i = 0; i <= vstate->curframe; i++)
6595 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6596 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006597}
6598
John Fastabend3f50f132020-03-30 14:36:39 -07006599static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006600{
John Fastabend3f50f132020-03-30 14:36:39 -07006601 struct tnum subreg = tnum_subreg(reg->var_off);
6602 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006603
John Fastabend3f50f132020-03-30 14:36:39 -07006604 switch (opcode) {
6605 case BPF_JEQ:
6606 if (tnum_is_const(subreg))
6607 return !!tnum_equals_const(subreg, val);
6608 break;
6609 case BPF_JNE:
6610 if (tnum_is_const(subreg))
6611 return !tnum_equals_const(subreg, val);
6612 break;
6613 case BPF_JSET:
6614 if ((~subreg.mask & subreg.value) & val)
6615 return 1;
6616 if (!((subreg.mask | subreg.value) & val))
6617 return 0;
6618 break;
6619 case BPF_JGT:
6620 if (reg->u32_min_value > val)
6621 return 1;
6622 else if (reg->u32_max_value <= val)
6623 return 0;
6624 break;
6625 case BPF_JSGT:
6626 if (reg->s32_min_value > sval)
6627 return 1;
6628 else if (reg->s32_max_value < sval)
6629 return 0;
6630 break;
6631 case BPF_JLT:
6632 if (reg->u32_max_value < val)
6633 return 1;
6634 else if (reg->u32_min_value >= val)
6635 return 0;
6636 break;
6637 case BPF_JSLT:
6638 if (reg->s32_max_value < sval)
6639 return 1;
6640 else if (reg->s32_min_value >= sval)
6641 return 0;
6642 break;
6643 case BPF_JGE:
6644 if (reg->u32_min_value >= val)
6645 return 1;
6646 else if (reg->u32_max_value < val)
6647 return 0;
6648 break;
6649 case BPF_JSGE:
6650 if (reg->s32_min_value >= sval)
6651 return 1;
6652 else if (reg->s32_max_value < sval)
6653 return 0;
6654 break;
6655 case BPF_JLE:
6656 if (reg->u32_max_value <= val)
6657 return 1;
6658 else if (reg->u32_min_value > val)
6659 return 0;
6660 break;
6661 case BPF_JSLE:
6662 if (reg->s32_max_value <= sval)
6663 return 1;
6664 else if (reg->s32_min_value > sval)
6665 return 0;
6666 break;
Jiong Wang092ed092019-01-26 12:26:01 -05006667 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05006668
John Fastabend3f50f132020-03-30 14:36:39 -07006669 return -1;
6670}
6671
6672
6673static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6674{
6675 s64 sval = (s64)val;
6676
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006677 switch (opcode) {
6678 case BPF_JEQ:
6679 if (tnum_is_const(reg->var_off))
6680 return !!tnum_equals_const(reg->var_off, val);
6681 break;
6682 case BPF_JNE:
6683 if (tnum_is_const(reg->var_off))
6684 return !tnum_equals_const(reg->var_off, val);
6685 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08006686 case BPF_JSET:
6687 if ((~reg->var_off.mask & reg->var_off.value) & val)
6688 return 1;
6689 if (!((reg->var_off.mask | reg->var_off.value) & val))
6690 return 0;
6691 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006692 case BPF_JGT:
6693 if (reg->umin_value > val)
6694 return 1;
6695 else if (reg->umax_value <= val)
6696 return 0;
6697 break;
6698 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006699 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006700 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006701 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006702 return 0;
6703 break;
6704 case BPF_JLT:
6705 if (reg->umax_value < val)
6706 return 1;
6707 else if (reg->umin_value >= val)
6708 return 0;
6709 break;
6710 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006711 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006712 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006713 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006714 return 0;
6715 break;
6716 case BPF_JGE:
6717 if (reg->umin_value >= val)
6718 return 1;
6719 else if (reg->umax_value < val)
6720 return 0;
6721 break;
6722 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006723 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006724 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006725 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006726 return 0;
6727 break;
6728 case BPF_JLE:
6729 if (reg->umax_value <= val)
6730 return 1;
6731 else if (reg->umin_value > val)
6732 return 0;
6733 break;
6734 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006735 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006736 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006737 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08006738 return 0;
6739 break;
6740 }
6741
6742 return -1;
6743}
6744
John Fastabend3f50f132020-03-30 14:36:39 -07006745/* compute branch direction of the expression "if (reg opcode val) goto target;"
6746 * and return:
6747 * 1 - branch will be taken and "goto target" will be executed
6748 * 0 - branch will not be taken and fall-through to next insn
6749 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6750 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05006751 */
John Fastabend3f50f132020-03-30 14:36:39 -07006752static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6753 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05006754{
John Fastabendcac616d2020-05-21 13:07:26 -07006755 if (__is_pointer_value(false, reg)) {
6756 if (!reg_type_not_null(reg->type))
6757 return -1;
6758
6759 /* If pointer is valid tests against zero will fail so we can
6760 * use this to direct branch taken.
6761 */
6762 if (val != 0)
6763 return -1;
6764
6765 switch (opcode) {
6766 case BPF_JEQ:
6767 return 0;
6768 case BPF_JNE:
6769 return 1;
6770 default:
6771 return -1;
6772 }
6773 }
Jiong Wang092ed092019-01-26 12:26:01 -05006774
John Fastabend3f50f132020-03-30 14:36:39 -07006775 if (is_jmp32)
6776 return is_branch32_taken(reg, val, opcode);
6777 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02006778}
6779
Josef Bacik48461132016-09-28 10:54:32 -04006780/* Adjusts the register min/max values in the case that the dst_reg is the
6781 * variable register that we are working on, and src_reg is a constant or we're
6782 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01006783 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04006784 */
6785static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07006786 struct bpf_reg_state *false_reg,
6787 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05006788 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04006789{
John Fastabend3f50f132020-03-30 14:36:39 -07006790 struct tnum false_32off = tnum_subreg(false_reg->var_off);
6791 struct tnum false_64off = false_reg->var_off;
6792 struct tnum true_32off = tnum_subreg(true_reg->var_off);
6793 struct tnum true_64off = true_reg->var_off;
6794 s64 sval = (s64)val;
6795 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006796
Edward Creef1174f72017-08-07 15:26:19 +01006797 /* If the dst_reg is a pointer, we can't learn anything about its
6798 * variable offset from the compare (unless src_reg were a pointer into
6799 * the same object, but we don't bother with that.
6800 * Since false_reg and true_reg have the same type by construction, we
6801 * only need to check one of them for pointerness.
6802 */
6803 if (__is_pointer_value(false, false_reg))
6804 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02006805
Josef Bacik48461132016-09-28 10:54:32 -04006806 switch (opcode) {
6807 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04006808 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006809 {
6810 struct bpf_reg_state *reg =
6811 opcode == BPF_JEQ ? true_reg : false_reg;
6812
6813 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6814 * if it is true we know the value for sure. Likewise for
6815 * BPF_JNE.
Josef Bacik48461132016-09-28 10:54:32 -04006816 */
John Fastabend3f50f132020-03-30 14:36:39 -07006817 if (is_jmp32)
6818 __mark_reg32_known(reg, val32);
6819 else
Jiong Wang092ed092019-01-26 12:26:01 -05006820 __mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04006821 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006822 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08006823 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07006824 if (is_jmp32) {
6825 false_32off = tnum_and(false_32off, tnum_const(~val32));
6826 if (is_power_of_2(val32))
6827 true_32off = tnum_or(true_32off,
6828 tnum_const(val32));
6829 } else {
6830 false_64off = tnum_and(false_64off, tnum_const(~val));
6831 if (is_power_of_2(val))
6832 true_64off = tnum_or(true_64off,
6833 tnum_const(val));
6834 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08006835 break;
Josef Bacik48461132016-09-28 10:54:32 -04006836 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006837 case BPF_JGT:
6838 {
John Fastabend3f50f132020-03-30 14:36:39 -07006839 if (is_jmp32) {
6840 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
6841 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
6842
6843 false_reg->u32_max_value = min(false_reg->u32_max_value,
6844 false_umax);
6845 true_reg->u32_min_value = max(true_reg->u32_min_value,
6846 true_umin);
6847 } else {
6848 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
6849 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
6850
6851 false_reg->umax_value = min(false_reg->umax_value, false_umax);
6852 true_reg->umin_value = max(true_reg->umin_value, true_umin);
6853 }
Edward Creeb03c9f92017-08-07 15:26:36 +01006854 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006855 }
Josef Bacik48461132016-09-28 10:54:32 -04006856 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006857 case BPF_JSGT:
6858 {
John Fastabend3f50f132020-03-30 14:36:39 -07006859 if (is_jmp32) {
6860 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
6861 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006862
John Fastabend3f50f132020-03-30 14:36:39 -07006863 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
6864 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
6865 } else {
6866 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
6867 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
6868
6869 false_reg->smax_value = min(false_reg->smax_value, false_smax);
6870 true_reg->smin_value = max(true_reg->smin_value, true_smin);
6871 }
Josef Bacik48461132016-09-28 10:54:32 -04006872 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006873 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006874 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006875 case BPF_JLT:
6876 {
John Fastabend3f50f132020-03-30 14:36:39 -07006877 if (is_jmp32) {
6878 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
6879 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
6880
6881 false_reg->u32_min_value = max(false_reg->u32_min_value,
6882 false_umin);
6883 true_reg->u32_max_value = min(true_reg->u32_max_value,
6884 true_umax);
6885 } else {
6886 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
6887 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
6888
6889 false_reg->umin_value = max(false_reg->umin_value, false_umin);
6890 true_reg->umax_value = min(true_reg->umax_value, true_umax);
6891 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006892 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006893 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006894 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05006895 case BPF_JSLT:
6896 {
John Fastabend3f50f132020-03-30 14:36:39 -07006897 if (is_jmp32) {
6898 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
6899 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006900
John Fastabend3f50f132020-03-30 14:36:39 -07006901 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
6902 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
6903 } else {
6904 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
6905 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
6906
6907 false_reg->smin_value = max(false_reg->smin_value, false_smin);
6908 true_reg->smax_value = min(true_reg->smax_value, true_smax);
6909 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02006910 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05006911 }
Josef Bacik48461132016-09-28 10:54:32 -04006912 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02006913 return;
Josef Bacik48461132016-09-28 10:54:32 -04006914 }
6915
John Fastabend3f50f132020-03-30 14:36:39 -07006916 if (is_jmp32) {
6917 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
6918 tnum_subreg(false_32off));
6919 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
6920 tnum_subreg(true_32off));
6921 __reg_combine_32_into_64(false_reg);
6922 __reg_combine_32_into_64(true_reg);
6923 } else {
6924 false_reg->var_off = false_64off;
6925 true_reg->var_off = true_64off;
6926 __reg_combine_64_into_32(false_reg);
6927 __reg_combine_64_into_32(true_reg);
6928 }
Josef Bacik48461132016-09-28 10:54:32 -04006929}
6930
Edward Creef1174f72017-08-07 15:26:19 +01006931/* Same as above, but for the case that dst_reg holds a constant and src_reg is
6932 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04006933 */
6934static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07006935 struct bpf_reg_state *false_reg,
6936 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05006937 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04006938{
Jann Horn0fc31b12020-03-30 18:03:24 +02006939 /* How can we transform "a <op> b" into "b <op> a"? */
6940 static const u8 opcode_flip[16] = {
6941 /* these stay the same */
6942 [BPF_JEQ >> 4] = BPF_JEQ,
6943 [BPF_JNE >> 4] = BPF_JNE,
6944 [BPF_JSET >> 4] = BPF_JSET,
6945 /* these swap "lesser" and "greater" (L and G in the opcodes) */
6946 [BPF_JGE >> 4] = BPF_JLE,
6947 [BPF_JGT >> 4] = BPF_JLT,
6948 [BPF_JLE >> 4] = BPF_JGE,
6949 [BPF_JLT >> 4] = BPF_JGT,
6950 [BPF_JSGE >> 4] = BPF_JSLE,
6951 [BPF_JSGT >> 4] = BPF_JSLT,
6952 [BPF_JSLE >> 4] = BPF_JSGE,
6953 [BPF_JSLT >> 4] = BPF_JSGT
6954 };
6955 opcode = opcode_flip[opcode >> 4];
6956 /* This uses zero as "not present in table"; luckily the zero opcode,
6957 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01006958 */
Jann Horn0fc31b12020-03-30 18:03:24 +02006959 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07006960 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01006961}
6962
6963/* Regs are known to be equal, so intersect their min/max/var_off */
6964static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
6965 struct bpf_reg_state *dst_reg)
6966{
Edward Creeb03c9f92017-08-07 15:26:36 +01006967 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
6968 dst_reg->umin_value);
6969 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
6970 dst_reg->umax_value);
6971 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
6972 dst_reg->smin_value);
6973 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
6974 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01006975 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
6976 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01006977 /* We might have learned new bounds from the var_off. */
6978 __update_reg_bounds(src_reg);
6979 __update_reg_bounds(dst_reg);
6980 /* We might have learned something about the sign bit. */
6981 __reg_deduce_bounds(src_reg);
6982 __reg_deduce_bounds(dst_reg);
6983 /* We might have learned some bits from the bounds. */
6984 __reg_bound_offset(src_reg);
6985 __reg_bound_offset(dst_reg);
6986 /* Intersecting with the old var_off might have improved our bounds
6987 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
6988 * then new var_off is (0; 0x7f...fc) which improves our umax.
6989 */
6990 __update_reg_bounds(src_reg);
6991 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006992}
6993
6994static void reg_combine_min_max(struct bpf_reg_state *true_src,
6995 struct bpf_reg_state *true_dst,
6996 struct bpf_reg_state *false_src,
6997 struct bpf_reg_state *false_dst,
6998 u8 opcode)
6999{
7000 switch (opcode) {
7001 case BPF_JEQ:
7002 __reg_combine_min_max(true_src, true_dst);
7003 break;
7004 case BPF_JNE:
7005 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01007006 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007007 }
Josef Bacik48461132016-09-28 10:54:32 -04007008}
7009
Joe Stringerfd978bf72018-10-02 13:35:35 -07007010static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7011 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07007012 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007013{
Joe Stringer840b9612018-10-02 13:35:32 -07007014 if (reg_type_may_be_null(reg->type) && reg->id == id) {
Edward Creef1174f72017-08-07 15:26:19 +01007015 /* Old offset (both fixed and variable parts) should
7016 * have been known-zero, because we don't allow pointer
7017 * arithmetic on pointers that might be NULL.
7018 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007019 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7020 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01007021 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01007022 __mark_reg_known_zero(reg);
7023 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007024 }
7025 if (is_null) {
7026 reg->type = SCALAR_VALUE;
Joe Stringer840b9612018-10-02 13:35:32 -07007027 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007028 const struct bpf_map *map = reg->map_ptr;
7029
7030 if (map->inner_map_meta) {
Joe Stringer840b9612018-10-02 13:35:32 -07007031 reg->type = CONST_PTR_TO_MAP;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007032 reg->map_ptr = map->inner_map_meta;
7033 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07007034 reg->type = PTR_TO_XDP_SOCK;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02007035 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7036 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7037 reg->type = PTR_TO_SOCKET;
Joe Stringer840b9612018-10-02 13:35:32 -07007038 } else {
7039 reg->type = PTR_TO_MAP_VALUE;
7040 }
Joe Stringerc64b7982018-10-02 13:35:33 -07007041 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7042 reg->type = PTR_TO_SOCKET;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08007043 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7044 reg->type = PTR_TO_SOCK_COMMON;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08007045 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7046 reg->type = PTR_TO_TCP_SOCK;
Yonghong Songb121b342020-05-09 10:59:12 -07007047 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7048 reg->type = PTR_TO_BTF_ID;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07007049 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7050 reg->type = PTR_TO_MEM;
Yonghong Songafbf21d2020-07-23 11:41:11 -07007051 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7052 reg->type = PTR_TO_RDONLY_BUF;
7053 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7054 reg->type = PTR_TO_RDWR_BUF;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07007055 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007056 if (is_null) {
7057 /* We don't need id and ref_obj_id from this point
7058 * onwards anymore, thus we should better reset it,
7059 * so that state pruning has chances to take effect.
7060 */
7061 reg->id = 0;
7062 reg->ref_obj_id = 0;
7063 } else if (!reg_may_point_to_spin_lock(reg)) {
7064 /* For not-NULL ptr, reg->ref_obj_id will be reset
7065 * in release_reg_references().
7066 *
7067 * reg->id is still used by spin_lock ptr. Other
7068 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07007069 */
7070 reg->id = 0;
7071 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02007072 }
7073}
7074
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007075static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7076 bool is_null)
7077{
7078 struct bpf_reg_state *reg;
7079 int i;
7080
7081 for (i = 0; i < MAX_BPF_REG; i++)
7082 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7083
7084 bpf_for_each_spilled_reg(i, state, reg) {
7085 if (!reg)
7086 continue;
7087 mark_ptr_or_null_reg(state, reg, id, is_null);
7088 }
7089}
7090
Thomas Graf57a09bf2016-10-18 19:51:19 +02007091/* The logic is similar to find_good_pkt_pointers(), both could eventually
7092 * be folded together at some point.
7093 */
Joe Stringer840b9612018-10-02 13:35:32 -07007094static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7095 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007096{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007097 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007098 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007099 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01007100 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007101 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02007102
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007103 if (ref_obj_id && ref_obj_id == id && is_null)
7104 /* regs[regno] is in the " == NULL" branch.
7105 * No one could have freed the reference state before
7106 * doing the NULL check.
7107 */
7108 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07007109
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007110 for (i = 0; i <= vstate->curframe; i++)
7111 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02007112}
7113
Daniel Borkmann5beca082017-11-01 23:58:10 +01007114static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7115 struct bpf_reg_state *dst_reg,
7116 struct bpf_reg_state *src_reg,
7117 struct bpf_verifier_state *this_branch,
7118 struct bpf_verifier_state *other_branch)
7119{
7120 if (BPF_SRC(insn->code) != BPF_X)
7121 return false;
7122
Jiong Wang092ed092019-01-26 12:26:01 -05007123 /* Pointers are always 64-bit. */
7124 if (BPF_CLASS(insn->code) == BPF_JMP32)
7125 return false;
7126
Daniel Borkmann5beca082017-11-01 23:58:10 +01007127 switch (BPF_OP(insn->code)) {
7128 case BPF_JGT:
7129 if ((dst_reg->type == PTR_TO_PACKET &&
7130 src_reg->type == PTR_TO_PACKET_END) ||
7131 (dst_reg->type == PTR_TO_PACKET_META &&
7132 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7133 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7134 find_good_pkt_pointers(this_branch, dst_reg,
7135 dst_reg->type, false);
7136 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7137 src_reg->type == PTR_TO_PACKET) ||
7138 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7139 src_reg->type == PTR_TO_PACKET_META)) {
7140 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7141 find_good_pkt_pointers(other_branch, src_reg,
7142 src_reg->type, true);
7143 } else {
7144 return false;
7145 }
7146 break;
7147 case BPF_JLT:
7148 if ((dst_reg->type == PTR_TO_PACKET &&
7149 src_reg->type == PTR_TO_PACKET_END) ||
7150 (dst_reg->type == PTR_TO_PACKET_META &&
7151 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7152 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7153 find_good_pkt_pointers(other_branch, dst_reg,
7154 dst_reg->type, true);
7155 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7156 src_reg->type == PTR_TO_PACKET) ||
7157 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7158 src_reg->type == PTR_TO_PACKET_META)) {
7159 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7160 find_good_pkt_pointers(this_branch, src_reg,
7161 src_reg->type, false);
7162 } else {
7163 return false;
7164 }
7165 break;
7166 case BPF_JGE:
7167 if ((dst_reg->type == PTR_TO_PACKET &&
7168 src_reg->type == PTR_TO_PACKET_END) ||
7169 (dst_reg->type == PTR_TO_PACKET_META &&
7170 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7171 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7172 find_good_pkt_pointers(this_branch, dst_reg,
7173 dst_reg->type, true);
7174 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7175 src_reg->type == PTR_TO_PACKET) ||
7176 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7177 src_reg->type == PTR_TO_PACKET_META)) {
7178 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7179 find_good_pkt_pointers(other_branch, src_reg,
7180 src_reg->type, false);
7181 } else {
7182 return false;
7183 }
7184 break;
7185 case BPF_JLE:
7186 if ((dst_reg->type == PTR_TO_PACKET &&
7187 src_reg->type == PTR_TO_PACKET_END) ||
7188 (dst_reg->type == PTR_TO_PACKET_META &&
7189 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7190 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7191 find_good_pkt_pointers(other_branch, dst_reg,
7192 dst_reg->type, false);
7193 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7194 src_reg->type == PTR_TO_PACKET) ||
7195 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7196 src_reg->type == PTR_TO_PACKET_META)) {
7197 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7198 find_good_pkt_pointers(this_branch, src_reg,
7199 src_reg->type, true);
7200 } else {
7201 return false;
7202 }
7203 break;
7204 default:
7205 return false;
7206 }
7207
7208 return true;
7209}
7210
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007211static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007212 struct bpf_insn *insn, int *insn_idx)
7213{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007214 struct bpf_verifier_state *this_branch = env->cur_state;
7215 struct bpf_verifier_state *other_branch;
7216 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007217 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007218 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05007219 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007220 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007221 int err;
7222
Jiong Wang092ed092019-01-26 12:26:01 -05007223 /* Only conditional jumps are expected to reach here. */
7224 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7225 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007226 return -EINVAL;
7227 }
7228
7229 if (BPF_SRC(insn->code) == BPF_X) {
7230 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05007231 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007232 return -EINVAL;
7233 }
7234
7235 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007236 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007237 if (err)
7238 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007239
7240 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007241 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007242 insn->src_reg);
7243 return -EACCES;
7244 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007245 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007246 } else {
7247 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05007248 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007249 return -EINVAL;
7250 }
7251 }
7252
7253 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007254 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007255 if (err)
7256 return err;
7257
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007258 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05007259 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007260
John Fastabend3f50f132020-03-30 14:36:39 -07007261 if (BPF_SRC(insn->code) == BPF_K) {
7262 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7263 } else if (src_reg->type == SCALAR_VALUE &&
7264 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7265 pred = is_branch_taken(dst_reg,
7266 tnum_subreg(src_reg->var_off).value,
7267 opcode,
7268 is_jmp32);
7269 } else if (src_reg->type == SCALAR_VALUE &&
7270 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7271 pred = is_branch_taken(dst_reg,
7272 src_reg->var_off.value,
7273 opcode,
7274 is_jmp32);
7275 }
7276
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007277 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07007278 /* If we get here with a dst_reg pointer type it is because
7279 * above is_branch_taken() special cased the 0 comparison.
7280 */
7281 if (!__is_pointer_value(false, dst_reg))
7282 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007283 if (BPF_SRC(insn->code) == BPF_X && !err)
7284 err = mark_chain_precision(env, insn->src_reg);
7285 if (err)
7286 return err;
7287 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07007288 if (pred == 1) {
7289 /* only follow the goto, ignore fall-through */
7290 *insn_idx += insn->off;
7291 return 0;
7292 } else if (pred == 0) {
7293 /* only follow fall-through branch, since
7294 * that's where the program will go
7295 */
7296 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007297 }
7298
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007299 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
7300 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007301 if (!other_branch)
7302 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007303 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007304
Josef Bacik48461132016-09-28 10:54:32 -04007305 /* detect if we are comparing against a constant value so we can adjust
7306 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01007307 * this is only legit if both are scalars (or pointers to the same
7308 * object, I suppose, but we don't support that right now), because
7309 * otherwise the different base pointers mean the offsets aren't
7310 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04007311 */
7312 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05007313 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05007314
Edward Creef1174f72017-08-07 15:26:19 +01007315 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05007316 src_reg->type == SCALAR_VALUE) {
7317 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07007318 (is_jmp32 &&
7319 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007320 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007321 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007322 src_reg->var_off.value,
7323 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05007324 opcode, is_jmp32);
7325 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07007326 (is_jmp32 &&
7327 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007328 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007329 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007330 dst_reg->var_off.value,
7331 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05007332 opcode, is_jmp32);
7333 else if (!is_jmp32 &&
7334 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01007335 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007336 reg_combine_min_max(&other_branch_regs[insn->src_reg],
7337 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05007338 src_reg, dst_reg, opcode);
Edward Creef1174f72017-08-07 15:26:19 +01007339 }
7340 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007341 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07007342 dst_reg, insn->imm, (u32)insn->imm,
7343 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04007344 }
7345
Jiong Wang092ed092019-01-26 12:26:01 -05007346 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7347 * NOTE: these optimizations below are related with pointer comparison
7348 * which will never be JMP32.
7349 */
7350 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007351 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07007352 reg_type_may_be_null(dst_reg->type)) {
7353 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02007354 * safe or unknown depending R == 0 or R != 0 conditional.
7355 */
Joe Stringer840b9612018-10-02 13:35:32 -07007356 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7357 opcode == BPF_JNE);
7358 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7359 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007360 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7361 this_branch, other_branch) &&
7362 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007363 verbose(env, "R%d pointer comparison prohibited\n",
7364 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007365 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007366 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007367 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007368 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007369 return 0;
7370}
7371
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007372/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007373static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007374{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007375 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007376 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007377 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007378 int err;
7379
7380 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007381 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007382 return -EINVAL;
7383 }
7384 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007385 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007386 return -EINVAL;
7387 }
7388
Edward Creedc503a82017-08-15 20:34:35 +01007389 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007390 if (err)
7391 return err;
7392
Jakub Kicinski6b173872016-09-21 11:43:59 +01007393 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01007394 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7395
Edward Creef1174f72017-08-07 15:26:19 +01007396 regs[insn->dst_reg].type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01007397 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007398 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01007399 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007400
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007401 map = env->used_maps[aux->map_index];
7402 mark_reg_known_zero(env, regs, insn->dst_reg);
7403 regs[insn->dst_reg].map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007404
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02007405 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
7406 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
7407 regs[insn->dst_reg].off = aux->map_off;
7408 if (map_value_has_spin_lock(map))
7409 regs[insn->dst_reg].id = ++env->id_gen;
7410 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7411 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
7412 } else {
7413 verbose(env, "bpf verifier is misconfigured\n");
7414 return -EINVAL;
7415 }
7416
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007417 return 0;
7418}
7419
Daniel Borkmann96be4322015-03-01 12:31:46 +01007420static bool may_access_skb(enum bpf_prog_type type)
7421{
7422 switch (type) {
7423 case BPF_PROG_TYPE_SOCKET_FILTER:
7424 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01007425 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01007426 return true;
7427 default:
7428 return false;
7429 }
7430}
7431
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007432/* verify safety of LD_ABS|LD_IND instructions:
7433 * - they can only appear in the programs where ctx == skb
7434 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7435 * preserve R6-R9, and store return value into R0
7436 *
7437 * Implicit input:
7438 * ctx == skb == R6 == CTX
7439 *
7440 * Explicit input:
7441 * SRC == any register
7442 * IMM == 32-bit immediate
7443 *
7444 * Output:
7445 * R0 - 8/16/32-bit skb data converted to cpu endianness
7446 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007447static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007448{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007449 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007450 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007451 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007452 int i, err;
7453
Udip Pant7e407812020-08-25 16:20:00 -07007454 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007455 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007456 return -EINVAL;
7457 }
7458
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02007459 if (!env->ops->gen_ld_abs) {
7460 verbose(env, "bpf verifier is misconfigured\n");
7461 return -EINVAL;
7462 }
7463
Jiong Wangf910cef2018-05-02 16:17:17 -04007464 if (env->subprog_cnt > 1) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007465 /* when program has LD_ABS insn JITs and interpreter assume
7466 * that r1 == ctx == skb which is not the case for callees
7467 * that can have arbitrary arguments. It's problematic
7468 * for main prog as well since JITs would need to analyze
7469 * all functions in order to make proper register save/restore
7470 * decisions in the main prog. Hence disallow LD_ABS with calls
7471 */
7472 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
7473 return -EINVAL;
7474 }
7475
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007476 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07007477 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007478 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007479 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007480 return -EINVAL;
7481 }
7482
7483 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007484 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007485 if (err)
7486 return err;
7487
Joe Stringerfd978bf72018-10-02 13:35:35 -07007488 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7489 * gen_ld_abs() may terminate the program at runtime, leading to
7490 * reference leak.
7491 */
7492 err = check_reference_leak(env);
7493 if (err) {
7494 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7495 return err;
7496 }
7497
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08007498 if (env->cur_state->active_spin_lock) {
7499 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7500 return -EINVAL;
7501 }
7502
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007503 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007504 verbose(env,
7505 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007506 return -EINVAL;
7507 }
7508
7509 if (mode == BPF_IND) {
7510 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01007511 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007512 if (err)
7513 return err;
7514 }
7515
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01007516 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7517 if (err < 0)
7518 return err;
7519
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007520 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01007521 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007522 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01007523 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7524 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007525
7526 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01007527 * the value fetched from the packet.
7528 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007529 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007530 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01007531 /* ld_abs load up to 32-bit skb data. */
7532 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08007533 return 0;
7534}
7535
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007536static int check_return_code(struct bpf_verifier_env *env)
7537{
brakmo5cf1e912019-05-28 16:59:36 -07007538 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007539 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007540 struct bpf_reg_state *reg;
7541 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07007542 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007543 int err;
7544
KP Singh9e4e01d2020-03-29 01:43:52 +01007545 /* LSM and struct_ops func-ptr's return type could be "void" */
Udip Pant7e407812020-08-25 16:20:00 -07007546 if ((prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7547 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08007548 !prog->aux->attach_func_proto->type)
7549 return 0;
7550
7551 /* eBPF calling convetion is such that R0 is used
7552 * to return the value from eBPF program.
7553 * Make sure that it's readable at this time
7554 * of bpf_exit, which means that program wrote
7555 * something into it earlier
7556 */
7557 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7558 if (err)
7559 return err;
7560
7561 if (is_pointer_value(env, BPF_REG_0)) {
7562 verbose(env, "R0 leaks addr as return value\n");
7563 return -EACCES;
7564 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007565
Udip Pant7e407812020-08-25 16:20:00 -07007566 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02007567 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7568 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02007569 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7570 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7571 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7572 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7573 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02007574 range = tnum_range(1, 1);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05007575 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007576 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07007577 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7578 range = tnum_range(0, 3);
7579 enforce_attach_type_range = tnum_range(2, 3);
7580 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05007581 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007582 case BPF_PROG_TYPE_CGROUP_SOCK:
7583 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05007584 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08007585 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07007586 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007587 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07007588 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7589 if (!env->prog->aux->attach_btf_id)
7590 return 0;
7591 range = tnum_const(0);
7592 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07007593 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07007594 switch (env->prog->expected_attach_type) {
7595 case BPF_TRACE_FENTRY:
7596 case BPF_TRACE_FEXIT:
7597 range = tnum_const(0);
7598 break;
7599 case BPF_TRACE_RAW_TP:
7600 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07007601 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02007602 case BPF_TRACE_ITER:
7603 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07007604 default:
7605 return -ENOTSUPP;
7606 }
Yonghong Song15d83c42020-05-09 10:59:00 -07007607 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02007608 case BPF_PROG_TYPE_SK_LOOKUP:
7609 range = tnum_range(SK_DROP, SK_PASS);
7610 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07007611 case BPF_PROG_TYPE_EXT:
7612 /* freplace program can return anything as its return value
7613 * depends on the to-be-replaced kernel func or bpf program.
7614 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007615 default:
7616 return 0;
7617 }
7618
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007619 reg = cur_regs(env) + BPF_REG_0;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007620 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007621 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007622 reg_type_str[reg->type]);
7623 return -EINVAL;
7624 }
7625
7626 if (!tnum_in(range, reg->var_off)) {
brakmo5cf1e912019-05-28 16:59:36 -07007627 char tn_buf[48];
7628
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007629 verbose(env, "At program exit the register R0 ");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007630 if (!tnum_is_unknown(reg->var_off)) {
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007631 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007632 verbose(env, "has value %s", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007633 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007634 verbose(env, "has unknown scalar value");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007635 }
brakmo5cf1e912019-05-28 16:59:36 -07007636 tnum_strn(tn_buf, sizeof(tn_buf), range);
Daniel Borkmann983695f2019-06-07 01:48:57 +02007637 verbose(env, " should have been in %s\n", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007638 return -EINVAL;
7639 }
brakmo5cf1e912019-05-28 16:59:36 -07007640
7641 if (!tnum_is_unknown(enforce_attach_type_range) &&
7642 tnum_in(enforce_attach_type_range, reg->var_off))
7643 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07007644 return 0;
7645}
7646
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007647/* non-recursive DFS pseudo code
7648 * 1 procedure DFS-iterative(G,v):
7649 * 2 label v as discovered
7650 * 3 let S be a stack
7651 * 4 S.push(v)
7652 * 5 while S is not empty
7653 * 6 t <- S.pop()
7654 * 7 if t is what we're looking for:
7655 * 8 return t
7656 * 9 for all edges e in G.adjacentEdges(t) do
7657 * 10 if edge e is already labelled
7658 * 11 continue with the next edge
7659 * 12 w <- G.adjacentVertex(t,e)
7660 * 13 if vertex w is not discovered and not explored
7661 * 14 label e as tree-edge
7662 * 15 label w as discovered
7663 * 16 S.push(w)
7664 * 17 continue at 5
7665 * 18 else if vertex w is discovered
7666 * 19 label e as back-edge
7667 * 20 else
7668 * 21 // vertex w is explored
7669 * 22 label e as forward- or cross-edge
7670 * 23 label t as explored
7671 * 24 S.pop()
7672 *
7673 * convention:
7674 * 0x10 - discovered
7675 * 0x11 - discovered and fall-through edge labelled
7676 * 0x12 - discovered and fall-through and branch edges labelled
7677 * 0x20 - explored
7678 */
7679
7680enum {
7681 DISCOVERED = 0x10,
7682 EXPLORED = 0x20,
7683 FALLTHROUGH = 1,
7684 BRANCH = 2,
7685};
7686
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007687static u32 state_htab_size(struct bpf_verifier_env *env)
7688{
7689 return env->prog->len;
7690}
7691
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007692static struct bpf_verifier_state_list **explored_state(
7693 struct bpf_verifier_env *env,
7694 int idx)
7695{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007696 struct bpf_verifier_state *cur = env->cur_state;
7697 struct bpf_func_state *state = cur->frame[cur->curframe];
7698
7699 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007700}
7701
7702static void init_explored_state(struct bpf_verifier_env *env, int idx)
7703{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007704 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007705}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007706
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007707/* t, w, e - match pseudo-code above:
7708 * t - index of current instruction
7709 * w - next instruction
7710 * e - edge
7711 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07007712static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7713 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007714{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007715 int *insn_stack = env->cfg.insn_stack;
7716 int *insn_state = env->cfg.insn_state;
7717
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007718 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7719 return 0;
7720
7721 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7722 return 0;
7723
7724 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08007725 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007726 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007727 return -EINVAL;
7728 }
7729
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007730 if (e == BRANCH)
7731 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007732 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007733
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007734 if (insn_state[w] == 0) {
7735 /* tree-edge */
7736 insn_state[t] = DISCOVERED | e;
7737 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007738 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007739 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007740 insn_stack[env->cfg.cur_stack++] = w;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007741 return 1;
7742 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07007743 if (loop_ok && env->bpf_capable)
Alexei Starovoitov25897262019-06-15 12:12:20 -07007744 return 0;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08007745 verbose_linfo(env, t, "%d: ", t);
7746 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007747 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007748 return -EINVAL;
7749 } else if (insn_state[w] == EXPLORED) {
7750 /* forward- or cross-edge */
7751 insn_state[t] = DISCOVERED | e;
7752 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007753 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007754 return -EFAULT;
7755 }
7756 return 0;
7757}
7758
7759/* non-recursive depth-first-search to detect loops in BPF program
7760 * loop == back-edge in directed graph
7761 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007762static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007763{
7764 struct bpf_insn *insns = env->prog->insnsi;
7765 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007766 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007767 int ret = 0;
7768 int i, t;
7769
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007770 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007771 if (!insn_state)
7772 return -ENOMEM;
7773
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007774 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007775 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07007776 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007777 return -ENOMEM;
7778 }
7779
7780 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
7781 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007782 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007783
7784peek_stack:
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007785 if (env->cfg.cur_stack == 0)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007786 goto check_state;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007787 t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007788
Jiong Wang092ed092019-01-26 12:26:01 -05007789 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
7790 BPF_CLASS(insns[t].code) == BPF_JMP32) {
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007791 u8 opcode = BPF_OP(insns[t].code);
7792
7793 if (opcode == BPF_EXIT) {
7794 goto mark_explored;
7795 } else if (opcode == BPF_CALL) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07007796 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007797 if (ret == 1)
7798 goto peek_stack;
7799 else if (ret < 0)
7800 goto err_free;
Daniel Borkmann07016152016-04-05 22:33:17 +02007801 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007802 init_explored_state(env, t + 1);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08007803 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007804 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07007805 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
7806 env, false);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08007807 if (ret == 1)
7808 goto peek_stack;
7809 else if (ret < 0)
7810 goto err_free;
7811 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007812 } else if (opcode == BPF_JA) {
7813 if (BPF_SRC(insns[t].code) != BPF_K) {
7814 ret = -EINVAL;
7815 goto err_free;
7816 }
7817 /* unconditional jump with single edge */
7818 ret = push_insn(t, t + insns[t].off + 1,
Alexei Starovoitov25897262019-06-15 12:12:20 -07007819 FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007820 if (ret == 1)
7821 goto peek_stack;
7822 else if (ret < 0)
7823 goto err_free;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007824 /* unconditional jmp is not a good pruning point,
7825 * but it's marked, since backtracking needs
7826 * to record jmp history in is_state_visited().
7827 */
7828 init_explored_state(env, t + insns[t].off + 1);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007829 /* tell verifier to check for equivalent states
7830 * after every call and jump
7831 */
Alexei Starovoitovc3de6312015-04-14 15:57:13 -07007832 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007833 init_explored_state(env, t + 1);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007834 } else {
7835 /* conditional jump with two edges */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007836 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07007837 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007838 if (ret == 1)
7839 goto peek_stack;
7840 else if (ret < 0)
7841 goto err_free;
7842
Alexei Starovoitov25897262019-06-15 12:12:20 -07007843 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007844 if (ret == 1)
7845 goto peek_stack;
7846 else if (ret < 0)
7847 goto err_free;
7848 }
7849 } else {
7850 /* all other non-branch instructions with single
7851 * fall-through edge
7852 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07007853 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007854 if (ret == 1)
7855 goto peek_stack;
7856 else if (ret < 0)
7857 goto err_free;
7858 }
7859
7860mark_explored:
7861 insn_state[t] = EXPLORED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007862 if (env->cfg.cur_stack-- <= 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007863 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007864 ret = -EFAULT;
7865 goto err_free;
7866 }
7867 goto peek_stack;
7868
7869check_state:
7870 for (i = 0; i < insn_cnt; i++) {
7871 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007872 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007873 ret = -EINVAL;
7874 goto err_free;
7875 }
7876 }
7877 ret = 0; /* cfg looks good */
7878
7879err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07007880 kvfree(insn_state);
7881 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07007882 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07007883 return ret;
7884}
7885
Yonghong Song838e9692018-11-19 15:29:11 -08007886/* The minimum supported BTF func info size */
7887#define MIN_BPF_FUNCINFO_SIZE 8
7888#define MAX_FUNCINFO_REC_SIZE 252
7889
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007890static int check_btf_func(struct bpf_verifier_env *env,
7891 const union bpf_attr *attr,
7892 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08007893{
Peter Oskolkovd0b28182019-01-16 10:43:01 -08007894 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08007895 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007896 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08007897 struct bpf_func_info_aux *info_aux = NULL;
Yonghong Song838e9692018-11-19 15:29:11 -08007898 const struct btf_type *type;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007899 struct bpf_prog *prog;
7900 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08007901 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08007902 u32 prev_offset = 0;
Dan Carpentere7ed83d2020-06-04 11:54:36 +03007903 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -08007904
7905 nfuncs = attr->func_info_cnt;
7906 if (!nfuncs)
7907 return 0;
7908
7909 if (nfuncs != env->subprog_cnt) {
7910 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
7911 return -EINVAL;
7912 }
7913
7914 urec_size = attr->func_info_rec_size;
7915 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
7916 urec_size > MAX_FUNCINFO_REC_SIZE ||
7917 urec_size % sizeof(u32)) {
7918 verbose(env, "invalid func info rec size %u\n", urec_size);
7919 return -EINVAL;
7920 }
7921
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007922 prog = env->prog;
7923 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08007924
7925 urecord = u64_to_user_ptr(attr->func_info);
7926 min_size = min_t(u32, krec_size, urec_size);
7927
Yonghong Songba64e7d2018-11-24 23:20:44 -08007928 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007929 if (!krecord)
7930 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08007931 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
7932 if (!info_aux)
7933 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08007934
Yonghong Song838e9692018-11-19 15:29:11 -08007935 for (i = 0; i < nfuncs; i++) {
7936 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
7937 if (ret) {
7938 if (ret == -E2BIG) {
7939 verbose(env, "nonzero tailing record in func info");
7940 /* set the size kernel expects so loader can zero
7941 * out the rest of the record.
7942 */
7943 if (put_user(min_size, &uattr->func_info_rec_size))
7944 ret = -EFAULT;
7945 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007946 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08007947 }
7948
Yonghong Songba64e7d2018-11-24 23:20:44 -08007949 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08007950 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007951 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08007952 }
7953
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08007954 /* check insn_off */
Yonghong Song838e9692018-11-19 15:29:11 -08007955 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08007956 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08007957 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08007958 "nonzero insn_off %u for the first func info record",
7959 krecord[i].insn_off);
Yonghong Song838e9692018-11-19 15:29:11 -08007960 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007961 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08007962 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08007963 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08007964 verbose(env,
7965 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08007966 krecord[i].insn_off, prev_offset);
Yonghong Song838e9692018-11-19 15:29:11 -08007967 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007968 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08007969 }
7970
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08007971 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08007972 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
7973 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007974 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08007975 }
7976
7977 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08007978 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08007979 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08007980 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08007981 krecord[i].type_id);
Yonghong Song838e9692018-11-19 15:29:11 -08007982 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007983 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08007984 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08007985 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08007986 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08007987 urecord += urec_size;
7988 }
7989
Yonghong Songba64e7d2018-11-24 23:20:44 -08007990 prog->aux->func_info = krecord;
7991 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08007992 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08007993 return 0;
7994
Martin KaFai Lauc454a462018-12-07 16:42:25 -08007995err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08007996 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08007997 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08007998 return ret;
7999}
8000
Yonghong Songba64e7d2018-11-24 23:20:44 -08008001static void adjust_btf_func(struct bpf_verifier_env *env)
8002{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008003 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008004 int i;
8005
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008006 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08008007 return;
8008
8009 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008010 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008011}
8012
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008013#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8014 sizeof(((struct bpf_line_info *)(0))->line_col))
8015#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8016
8017static int check_btf_line(struct bpf_verifier_env *env,
8018 const union bpf_attr *attr,
8019 union bpf_attr __user *uattr)
8020{
8021 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8022 struct bpf_subprog_info *sub;
8023 struct bpf_line_info *linfo;
8024 struct bpf_prog *prog;
8025 const struct btf *btf;
8026 void __user *ulinfo;
8027 int err;
8028
8029 nr_linfo = attr->line_info_cnt;
8030 if (!nr_linfo)
8031 return 0;
8032
8033 rec_size = attr->line_info_rec_size;
8034 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8035 rec_size > MAX_LINEINFO_REC_SIZE ||
8036 rec_size & (sizeof(u32) - 1))
8037 return -EINVAL;
8038
8039 /* Need to zero it in case the userspace may
8040 * pass in a smaller bpf_line_info object.
8041 */
8042 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8043 GFP_KERNEL | __GFP_NOWARN);
8044 if (!linfo)
8045 return -ENOMEM;
8046
8047 prog = env->prog;
8048 btf = prog->aux->btf;
8049
8050 s = 0;
8051 sub = env->subprog_info;
8052 ulinfo = u64_to_user_ptr(attr->line_info);
8053 expected_size = sizeof(struct bpf_line_info);
8054 ncopy = min_t(u32, expected_size, rec_size);
8055 for (i = 0; i < nr_linfo; i++) {
8056 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8057 if (err) {
8058 if (err == -E2BIG) {
8059 verbose(env, "nonzero tailing record in line_info");
8060 if (put_user(expected_size,
8061 &uattr->line_info_rec_size))
8062 err = -EFAULT;
8063 }
8064 goto err_free;
8065 }
8066
8067 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8068 err = -EFAULT;
8069 goto err_free;
8070 }
8071
8072 /*
8073 * Check insn_off to ensure
8074 * 1) strictly increasing AND
8075 * 2) bounded by prog->len
8076 *
8077 * The linfo[0].insn_off == 0 check logically falls into
8078 * the later "missing bpf_line_info for func..." case
8079 * because the first linfo[0].insn_off must be the
8080 * first sub also and the first sub must have
8081 * subprog_info[0].start == 0.
8082 */
8083 if ((i && linfo[i].insn_off <= prev_offset) ||
8084 linfo[i].insn_off >= prog->len) {
8085 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8086 i, linfo[i].insn_off, prev_offset,
8087 prog->len);
8088 err = -EINVAL;
8089 goto err_free;
8090 }
8091
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08008092 if (!prog->insnsi[linfo[i].insn_off].code) {
8093 verbose(env,
8094 "Invalid insn code at line_info[%u].insn_off\n",
8095 i);
8096 err = -EINVAL;
8097 goto err_free;
8098 }
8099
Martin KaFai Lau23127b32018-12-13 10:41:46 -08008100 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8101 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008102 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8103 err = -EINVAL;
8104 goto err_free;
8105 }
8106
8107 if (s != env->subprog_cnt) {
8108 if (linfo[i].insn_off == sub[s].start) {
8109 sub[s].linfo_idx = i;
8110 s++;
8111 } else if (sub[s].start < linfo[i].insn_off) {
8112 verbose(env, "missing bpf_line_info for func#%u\n", s);
8113 err = -EINVAL;
8114 goto err_free;
8115 }
8116 }
8117
8118 prev_offset = linfo[i].insn_off;
8119 ulinfo += rec_size;
8120 }
8121
8122 if (s != env->subprog_cnt) {
8123 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8124 env->subprog_cnt - s, s);
8125 err = -EINVAL;
8126 goto err_free;
8127 }
8128
8129 prog->aux->linfo = linfo;
8130 prog->aux->nr_linfo = nr_linfo;
8131
8132 return 0;
8133
8134err_free:
8135 kvfree(linfo);
8136 return err;
8137}
8138
8139static int check_btf_info(struct bpf_verifier_env *env,
8140 const union bpf_attr *attr,
8141 union bpf_attr __user *uattr)
8142{
8143 struct btf *btf;
8144 int err;
8145
8146 if (!attr->func_info_cnt && !attr->line_info_cnt)
8147 return 0;
8148
8149 btf = btf_get_by_fd(attr->prog_btf_fd);
8150 if (IS_ERR(btf))
8151 return PTR_ERR(btf);
8152 env->prog->aux->btf = btf;
8153
8154 err = check_btf_func(env, attr, uattr);
8155 if (err)
8156 return err;
8157
8158 err = check_btf_line(env, attr, uattr);
8159 if (err)
8160 return err;
8161
8162 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008163}
8164
Edward Creef1174f72017-08-07 15:26:19 +01008165/* check %cur's range satisfies %old's */
8166static bool range_within(struct bpf_reg_state *old,
8167 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008168{
Edward Creeb03c9f92017-08-07 15:26:36 +01008169 return old->umin_value <= cur->umin_value &&
8170 old->umax_value >= cur->umax_value &&
8171 old->smin_value <= cur->smin_value &&
8172 old->smax_value >= cur->smax_value;
Edward Creef1174f72017-08-07 15:26:19 +01008173}
8174
8175/* Maximum number of register states that can exist at once */
8176#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8177struct idpair {
8178 u32 old;
8179 u32 cur;
8180};
8181
8182/* If in the old state two registers had the same id, then they need to have
8183 * the same id in the new state as well. But that id could be different from
8184 * the old state, so we need to track the mapping from old to new ids.
8185 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8186 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8187 * regs with a different old id could still have new id 9, we don't care about
8188 * that.
8189 * So we look through our idmap to see if this old id has been seen before. If
8190 * so, we require the new id to match; otherwise, we add the id pair to the map.
8191 */
8192static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
8193{
8194 unsigned int i;
8195
8196 for (i = 0; i < ID_MAP_SIZE; i++) {
8197 if (!idmap[i].old) {
8198 /* Reached an empty slot; haven't seen this id before */
8199 idmap[i].old = old_id;
8200 idmap[i].cur = cur_id;
8201 return true;
8202 }
8203 if (idmap[i].old == old_id)
8204 return idmap[i].cur == cur_id;
8205 }
8206 /* We ran out of idmap slots, which should be impossible */
8207 WARN_ON_ONCE(1);
8208 return false;
8209}
8210
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008211static void clean_func_state(struct bpf_verifier_env *env,
8212 struct bpf_func_state *st)
8213{
8214 enum bpf_reg_liveness live;
8215 int i, j;
8216
8217 for (i = 0; i < BPF_REG_FP; i++) {
8218 live = st->regs[i].live;
8219 /* liveness must not touch this register anymore */
8220 st->regs[i].live |= REG_LIVE_DONE;
8221 if (!(live & REG_LIVE_READ))
8222 /* since the register is unused, clear its state
8223 * to make further comparison simpler
8224 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01008225 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008226 }
8227
8228 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
8229 live = st->stack[i].spilled_ptr.live;
8230 /* liveness must not touch this stack slot anymore */
8231 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
8232 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01008233 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008234 for (j = 0; j < BPF_REG_SIZE; j++)
8235 st->stack[i].slot_type[j] = STACK_INVALID;
8236 }
8237 }
8238}
8239
8240static void clean_verifier_state(struct bpf_verifier_env *env,
8241 struct bpf_verifier_state *st)
8242{
8243 int i;
8244
8245 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
8246 /* all regs in this state in all frames were already marked */
8247 return;
8248
8249 for (i = 0; i <= st->curframe; i++)
8250 clean_func_state(env, st->frame[i]);
8251}
8252
8253/* the parentage chains form a tree.
8254 * the verifier states are added to state lists at given insn and
8255 * pushed into state stack for future exploration.
8256 * when the verifier reaches bpf_exit insn some of the verifer states
8257 * stored in the state lists have their final liveness state already,
8258 * but a lot of states will get revised from liveness point of view when
8259 * the verifier explores other branches.
8260 * Example:
8261 * 1: r0 = 1
8262 * 2: if r1 == 100 goto pc+1
8263 * 3: r0 = 2
8264 * 4: exit
8265 * when the verifier reaches exit insn the register r0 in the state list of
8266 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8267 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8268 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8269 *
8270 * Since the verifier pushes the branch states as it sees them while exploring
8271 * the program the condition of walking the branch instruction for the second
8272 * time means that all states below this branch were already explored and
8273 * their final liveness markes are already propagated.
8274 * Hence when the verifier completes the search of state list in is_state_visited()
8275 * we can call this clean_live_states() function to mark all liveness states
8276 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8277 * will not be used.
8278 * This function also clears the registers and stack for states that !READ
8279 * to simplify state merging.
8280 *
8281 * Important note here that walking the same branch instruction in the callee
8282 * doesn't meant that the states are DONE. The verifier has to compare
8283 * the callsites
8284 */
8285static void clean_live_states(struct bpf_verifier_env *env, int insn,
8286 struct bpf_verifier_state *cur)
8287{
8288 struct bpf_verifier_state_list *sl;
8289 int i;
8290
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008291 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008292 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07008293 if (sl->state.branches)
8294 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008295 if (sl->state.insn_idx != insn ||
8296 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008297 goto next;
8298 for (i = 0; i <= cur->curframe; i++)
8299 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
8300 goto next;
8301 clean_verifier_state(env, &sl->state);
8302next:
8303 sl = sl->next;
8304 }
8305}
8306
Edward Creef1174f72017-08-07 15:26:19 +01008307/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01008308static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8309 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01008310{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008311 bool equal;
8312
Edward Creedc503a82017-08-15 20:34:35 +01008313 if (!(rold->live & REG_LIVE_READ))
8314 /* explored state didn't use this */
8315 return true;
8316
Edward Cree679c7822018-08-22 20:02:19 +01008317 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008318
8319 if (rold->type == PTR_TO_STACK)
8320 /* two stack pointers are equal only if they're pointing to
8321 * the same stack frame, since fp-8 in foo != fp-8 in bar
8322 */
8323 return equal && rold->frameno == rcur->frameno;
8324
8325 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01008326 return true;
8327
8328 if (rold->type == NOT_INIT)
8329 /* explored state can't have used this */
8330 return true;
8331 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008332 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008333 switch (rold->type) {
8334 case SCALAR_VALUE:
8335 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008336 if (!rold->precise && !rcur->precise)
8337 return true;
Edward Creef1174f72017-08-07 15:26:19 +01008338 /* new val must satisfy old val knowledge */
8339 return range_within(rold, rcur) &&
8340 tnum_in(rold->var_off, rcur->var_off);
8341 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08008342 /* We're trying to use a pointer in place of a scalar.
8343 * Even if the scalar was unbounded, this could lead to
8344 * pointer leaks because scalars are allowed to leak
8345 * while pointers are not. We could make this safe in
8346 * special cases if root is calling us, but it's
8347 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01008348 */
Jann Horn179d1c52017-12-18 20:11:59 -08008349 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008350 }
8351 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01008352 /* If the new min/max/var_off satisfy the old ones and
8353 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008354 * 'id' is not compared, since it's only used for maps with
8355 * bpf_spin_lock inside map element and in such cases if
8356 * the rest of the prog is valid for one map element then
8357 * it's valid for all map elements regardless of the key
8358 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01008359 */
8360 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8361 range_within(rold, rcur) &&
8362 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01008363 case PTR_TO_MAP_VALUE_OR_NULL:
8364 /* a PTR_TO_MAP_VALUE could be safe to use as a
8365 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8366 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8367 * checked, doing so could have affected others with the same
8368 * id, and we can't check for that because we lost the id when
8369 * we converted to a PTR_TO_MAP_VALUE.
8370 */
8371 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8372 return false;
8373 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8374 return false;
8375 /* Check our ids match any regs they're supposed to */
8376 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02008377 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01008378 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02008379 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01008380 return false;
8381 /* We must have at least as much range as the old ptr
8382 * did, so that any accesses which were safe before are
8383 * still safe. This is true even if old range < old off,
8384 * since someone could have accessed through (ptr - k), or
8385 * even done ptr -= k in a register, to get a safe access.
8386 */
8387 if (rold->range > rcur->range)
8388 return false;
8389 /* If the offsets don't match, we can't trust our alignment;
8390 * nor can we be sure that we won't fall out of range.
8391 */
8392 if (rold->off != rcur->off)
8393 return false;
8394 /* id relations must be preserved */
8395 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8396 return false;
8397 /* new val must satisfy old val knowledge */
8398 return range_within(rold, rcur) &&
8399 tnum_in(rold->var_off, rcur->var_off);
8400 case PTR_TO_CTX:
8401 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01008402 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07008403 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07008404 case PTR_TO_SOCKET:
8405 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08008406 case PTR_TO_SOCK_COMMON:
8407 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08008408 case PTR_TO_TCP_SOCK:
8409 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07008410 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01008411 /* Only valid matches are exact, which memcmp() above
8412 * would have accepted
8413 */
8414 default:
8415 /* Don't know what's going on, just say it's not safe */
8416 return false;
8417 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008418
Edward Creef1174f72017-08-07 15:26:19 +01008419 /* Shouldn't get here; if we do, say it's not safe */
8420 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008421 return false;
8422}
8423
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008424static bool stacksafe(struct bpf_func_state *old,
8425 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008426 struct idpair *idmap)
8427{
8428 int i, spi;
8429
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008430 /* walk slots of the explored stack and ignore any additional
8431 * slots in the current stack, since explored(safe) state
8432 * didn't use them
8433 */
8434 for (i = 0; i < old->allocated_stack; i++) {
8435 spi = i / BPF_REG_SIZE;
8436
Alexei Starovoitovb2339202018-12-13 11:42:31 -08008437 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8438 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008439 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +00008440 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -08008441 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008442
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008443 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8444 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -08008445
8446 /* explored stack has more populated slots than current stack
8447 * and these slots were used
8448 */
8449 if (i >= cur->allocated_stack)
8450 return false;
8451
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008452 /* if old state was safe with misc data in the stack
8453 * it will be safe with zero-initialized stack.
8454 * The opposite is not true
8455 */
8456 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8457 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8458 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008459 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8460 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8461 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -07008462 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008463 * this verifier states are not equivalent,
8464 * return false to continue verification of this path
8465 */
8466 return false;
8467 if (i % BPF_REG_SIZE)
8468 continue;
8469 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8470 continue;
8471 if (!regsafe(&old->stack[spi].spilled_ptr,
8472 &cur->stack[spi].spilled_ptr,
8473 idmap))
8474 /* when explored and current stack slot are both storing
8475 * spilled registers, check that stored pointers types
8476 * are the same as well.
8477 * Ex: explored safe path could have stored
8478 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8479 * but current path has stored:
8480 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8481 * such verifier states are not equivalent.
8482 * return false to continue verification of this path
8483 */
8484 return false;
8485 }
8486 return true;
8487}
8488
Joe Stringerfd978bf72018-10-02 13:35:35 -07008489static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8490{
8491 if (old->acquired_refs != cur->acquired_refs)
8492 return false;
8493 return !memcmp(old->refs, cur->refs,
8494 sizeof(*old->refs) * old->acquired_refs);
8495}
8496
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008497/* compare two verifier states
8498 *
8499 * all states stored in state_list are known to be valid, since
8500 * verifier reached 'bpf_exit' instruction through them
8501 *
8502 * this function is called when verifier exploring different branches of
8503 * execution popped from the state stack. If it sees an old state that has
8504 * more strict register state and more strict stack state then this execution
8505 * branch doesn't need to be explored further, since verifier already
8506 * concluded that more strict state leads to valid finish.
8507 *
8508 * Therefore two states are equivalent if register state is more conservative
8509 * and explored stack state is more conservative than the current one.
8510 * Example:
8511 * explored current
8512 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8513 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8514 *
8515 * In other words if current stack state (one being explored) has more
8516 * valid slots than old one that already passed validation, it means
8517 * the verifier can stop exploring and conclude that current state is valid too
8518 *
8519 * Similarly with registers. If explored state has register type as invalid
8520 * whereas register type in current state is meaningful, it means that
8521 * the current state will reach 'bpf_exit' instruction safely
8522 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008523static bool func_states_equal(struct bpf_func_state *old,
8524 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008525{
Edward Creef1174f72017-08-07 15:26:19 +01008526 struct idpair *idmap;
8527 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008528 int i;
8529
Edward Creef1174f72017-08-07 15:26:19 +01008530 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8531 /* If we failed to allocate the idmap, just say it's not safe */
8532 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008533 return false;
Edward Creef1174f72017-08-07 15:26:19 +01008534
8535 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +01008536 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +01008537 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008538 }
8539
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008540 if (!stacksafe(old, cur, idmap))
8541 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -07008542
8543 if (!refsafe(old, cur))
8544 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +01008545 ret = true;
8546out_free:
8547 kfree(idmap);
8548 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008549}
8550
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008551static bool states_equal(struct bpf_verifier_env *env,
8552 struct bpf_verifier_state *old,
8553 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +01008554{
Edward Creedc503a82017-08-15 20:34:35 +01008555 int i;
8556
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008557 if (old->curframe != cur->curframe)
8558 return false;
8559
Daniel Borkmann979d63d2019-01-03 00:58:34 +01008560 /* Verification state from speculative execution simulation
8561 * must never prune a non-speculative execution one.
8562 */
8563 if (old->speculative && !cur->speculative)
8564 return false;
8565
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008566 if (old->active_spin_lock != cur->active_spin_lock)
8567 return false;
8568
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008569 /* for states to be equal callsites have to be the same
8570 * and all frame states need to be equivalent
8571 */
8572 for (i = 0; i <= old->curframe; i++) {
8573 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8574 return false;
8575 if (!func_states_equal(old->frame[i], cur->frame[i]))
8576 return false;
8577 }
8578 return true;
8579}
8580
Jiong Wang5327ed32019-05-24 23:25:12 +01008581/* Return 0 if no propagation happened. Return negative error code if error
8582 * happened. Otherwise, return the propagated bit.
8583 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008584static int propagate_liveness_reg(struct bpf_verifier_env *env,
8585 struct bpf_reg_state *reg,
8586 struct bpf_reg_state *parent_reg)
8587{
Jiong Wang5327ed32019-05-24 23:25:12 +01008588 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8589 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008590 int err;
8591
Jiong Wang5327ed32019-05-24 23:25:12 +01008592 /* When comes here, read flags of PARENT_REG or REG could be any of
8593 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8594 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8595 */
8596 if (parent_flag == REG_LIVE_READ64 ||
8597 /* Or if there is no read flag from REG. */
8598 !flag ||
8599 /* Or if the read flag from REG is the same as PARENT_REG. */
8600 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008601 return 0;
8602
Jiong Wang5327ed32019-05-24 23:25:12 +01008603 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008604 if (err)
8605 return err;
8606
Jiong Wang5327ed32019-05-24 23:25:12 +01008607 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008608}
8609
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008610/* A write screens off any subsequent reads; but write marks come from the
8611 * straight-line code between a state and its parent. When we arrive at an
8612 * equivalent state (jump target or such) we didn't arrive by the straight-line
8613 * code, so read marks in the state must propagate to the parent regardless
8614 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +01008615 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008616 */
8617static int propagate_liveness(struct bpf_verifier_env *env,
8618 const struct bpf_verifier_state *vstate,
8619 struct bpf_verifier_state *vparent)
8620{
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008621 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008622 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008623 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008624
8625 if (vparent->curframe != vstate->curframe) {
8626 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8627 vparent->curframe, vstate->curframe);
8628 return -EFAULT;
8629 }
Edward Creedc503a82017-08-15 20:34:35 +01008630 /* Propagate read liveness of registers... */
8631 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -07008632 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008633 parent = vparent->frame[frame];
8634 state = vstate->frame[frame];
8635 parent_reg = parent->regs;
8636 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -07008637 /* We don't need to worry about FP liveness, it's read-only */
8638 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008639 err = propagate_liveness_reg(env, &state_reg[i],
8640 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +01008641 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008642 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +01008643 if (err == REG_LIVE_READ64)
8644 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +01008645 }
Edward Creedc503a82017-08-15 20:34:35 +01008646
Jiong Wang1b04aee2019-04-12 22:59:34 +01008647 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008648 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8649 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008650 parent_reg = &parent->stack[i].spilled_ptr;
8651 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01008652 err = propagate_liveness_reg(env, state_reg,
8653 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +01008654 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01008655 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008656 }
Edward Creedc503a82017-08-15 20:34:35 +01008657 }
Jiong Wang5327ed32019-05-24 23:25:12 +01008658 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01008659}
8660
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07008661/* find precise scalars in the previous equivalent state and
8662 * propagate them into the current state
8663 */
8664static int propagate_precision(struct bpf_verifier_env *env,
8665 const struct bpf_verifier_state *old)
8666{
8667 struct bpf_reg_state *state_reg;
8668 struct bpf_func_state *state;
8669 int i, err = 0;
8670
8671 state = old->frame[old->curframe];
8672 state_reg = state->regs;
8673 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8674 if (state_reg->type != SCALAR_VALUE ||
8675 !state_reg->precise)
8676 continue;
8677 if (env->log.level & BPF_LOG_LEVEL2)
8678 verbose(env, "propagating r%d\n", i);
8679 err = mark_chain_precision(env, i);
8680 if (err < 0)
8681 return err;
8682 }
8683
8684 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8685 if (state->stack[i].slot_type[0] != STACK_SPILL)
8686 continue;
8687 state_reg = &state->stack[i].spilled_ptr;
8688 if (state_reg->type != SCALAR_VALUE ||
8689 !state_reg->precise)
8690 continue;
8691 if (env->log.level & BPF_LOG_LEVEL2)
8692 verbose(env, "propagating fp%d\n",
8693 (-i - 1) * BPF_REG_SIZE);
8694 err = mark_chain_precision_stack(env, i);
8695 if (err < 0)
8696 return err;
8697 }
8698 return 0;
8699}
8700
Alexei Starovoitov25897262019-06-15 12:12:20 -07008701static bool states_maybe_looping(struct bpf_verifier_state *old,
8702 struct bpf_verifier_state *cur)
8703{
8704 struct bpf_func_state *fold, *fcur;
8705 int i, fr = cur->curframe;
8706
8707 if (old->curframe != fr)
8708 return false;
8709
8710 fold = old->frame[fr];
8711 fcur = cur->frame[fr];
8712 for (i = 0; i < MAX_BPF_REG; i++)
8713 if (memcmp(&fold->regs[i], &fcur->regs[i],
8714 offsetof(struct bpf_reg_state, parent)))
8715 return false;
8716 return true;
8717}
8718
8719
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008720static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008721{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008722 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008723 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +01008724 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08008725 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -07008726 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008727
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008728 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008729 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008730 /* this 'insn_idx' instruction wasn't marked, so we will not
8731 * be doing state search here
8732 */
8733 return 0;
8734
Alexei Starovoitov25897262019-06-15 12:12:20 -07008735 /* bpf progs typically have pruning point every 4 instructions
8736 * http://vger.kernel.org/bpfconf2019.html#session-1
8737 * Do not add new state for future pruning if the verifier hasn't seen
8738 * at least 2 jumps and at least 8 instructions.
8739 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8740 * In tests that amounts to up to 50% reduction into total verifier
8741 * memory consumption and 20% verifier time speedup.
8742 */
8743 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
8744 env->insn_processed - env->prev_insn_processed >= 8)
8745 add_new_state = true;
8746
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008747 pprev = explored_state(env, insn_idx);
8748 sl = *pprev;
8749
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08008750 clean_live_states(env, insn_idx, cur);
8751
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008752 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008753 states_cnt++;
8754 if (sl->state.insn_idx != insn_idx)
8755 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -07008756 if (sl->state.branches) {
8757 if (states_maybe_looping(&sl->state, cur) &&
8758 states_equal(env, &sl->state, cur)) {
8759 verbose_linfo(env, insn_idx, "; ");
8760 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
8761 return -EINVAL;
8762 }
8763 /* if the verifier is processing a loop, avoid adding new state
8764 * too often, since different loop iterations have distinct
8765 * states and may not help future pruning.
8766 * This threshold shouldn't be too low to make sure that
8767 * a loop with large bound will be rejected quickly.
8768 * The most abusive loop will be:
8769 * r1 += 1
8770 * if r1 < 1000000 goto pc-2
8771 * 1M insn_procssed limit / 100 == 10k peak states.
8772 * This threshold shouldn't be too high either, since states
8773 * at the end of the loop are likely to be useful in pruning.
8774 */
8775 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
8776 env->insn_processed - env->prev_insn_processed < 100)
8777 add_new_state = false;
8778 goto miss;
8779 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008780 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008781 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008782 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +01008783 * prune the search.
8784 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +01008785 * If we have any write marks in env->cur_state, they
8786 * will prevent corresponding reads in the continuation
8787 * from reaching our parent (an explored_state). Our
8788 * own state will get the read marks recorded, but
8789 * they'll be immediately forgotten as we're pruning
8790 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008791 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008792 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07008793
8794 /* if previous state reached the exit with precision and
8795 * current state is equivalent to it (except precsion marks)
8796 * the precision needs to be propagated back in
8797 * the current state.
8798 */
8799 err = err ? : push_jmp_history(env, cur);
8800 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008801 if (err)
8802 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008803 return 1;
Edward Creedc503a82017-08-15 20:34:35 +01008804 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07008805miss:
8806 /* when new state is not going to be added do not increase miss count.
8807 * Otherwise several loop iterations will remove the state
8808 * recorded earlier. The goal of these heuristics is to have
8809 * states from some iterations of the loop (some in the beginning
8810 * and some at the end) to help pruning.
8811 */
8812 if (add_new_state)
8813 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008814 /* heuristic to determine whether this state is beneficial
8815 * to keep checking from state equivalence point of view.
8816 * Higher numbers increase max_states_per_insn and verification time,
8817 * but do not meaningfully decrease insn_processed.
8818 */
8819 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
8820 /* the state is unlikely to be useful. Remove it to
8821 * speed up verification
8822 */
8823 *pprev = sl->next;
8824 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07008825 u32 br = sl->state.branches;
8826
8827 WARN_ONCE(br,
8828 "BUG live_done but branches_to_explore %d\n",
8829 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008830 free_verifier_state(&sl->state, false);
8831 kfree(sl);
8832 env->peak_states--;
8833 } else {
8834 /* cannot free this state, since parentage chain may
8835 * walk it later. Add it for free_list instead to
8836 * be freed at the end of verification
8837 */
8838 sl->next = env->free_list;
8839 env->free_list = sl;
8840 }
8841 sl = *pprev;
8842 continue;
8843 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008844next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07008845 pprev = &sl->next;
8846 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008847 }
8848
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008849 if (env->max_states_per_insn < states_cnt)
8850 env->max_states_per_insn = states_cnt;
8851
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07008852 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008853 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08008854
Alexei Starovoitov25897262019-06-15 12:12:20 -07008855 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008856 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -07008857
8858 /* There were no equivalent states, remember the current one.
8859 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008860 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -07008861 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008862 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -07008863 * again on the way to bpf_exit.
8864 * When looping the sl->state.branches will be > 0 and this state
8865 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008866 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008867 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008868 if (!new_sl)
8869 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008870 env->total_states++;
8871 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -07008872 env->prev_jmps_processed = env->jmps_processed;
8873 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008874
8875 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +01008876 new = &new_sl->state;
8877 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07008878 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +01008879 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07008880 kfree(new_sl);
8881 return err;
8882 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008883 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -07008884 WARN_ONCE(new->branches != 1,
8885 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008886
Alexei Starovoitov25897262019-06-15 12:12:20 -07008887 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008888 cur->first_insn_idx = insn_idx;
8889 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008890 new_sl->next = *explored_state(env, insn_idx);
8891 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -08008892 /* connect new state to parentage chain. Current frame needs all
8893 * registers connected. Only r6 - r9 of the callers are alive (pushed
8894 * to the stack implicitly by JITs) so in callers' frames connect just
8895 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
8896 * the state of the call instruction (with WRITTEN set), and r0 comes
8897 * from callee with its full parentage chain, anyway.
8898 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +01008899 /* clear write marks in current state: the writes we did are not writes
8900 * our child did, so they don't screen off its reads from us.
8901 * (There are no read marks in current state, because reads always mark
8902 * their parent and current state never has children yet. Only
8903 * explored_states can get read marks.)
8904 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -07008905 for (j = 0; j <= cur->curframe; j++) {
8906 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
8907 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
8908 for (i = 0; i < BPF_REG_FP; i++)
8909 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
8910 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008911
8912 /* all stack frames are accessible from callee, clear them all */
8913 for (j = 0; j <= cur->curframe; j++) {
8914 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +01008915 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008916
Edward Cree679c7822018-08-22 20:02:19 +01008917 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08008918 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01008919 frame->stack[i].spilled_ptr.parent =
8920 &newframe->stack[i].spilled_ptr;
8921 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008922 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008923 return 0;
8924}
8925
Joe Stringerc64b7982018-10-02 13:35:33 -07008926/* Return true if it's OK to have the same insn return a different type. */
8927static bool reg_type_mismatch_ok(enum bpf_reg_type type)
8928{
8929 switch (type) {
8930 case PTR_TO_CTX:
8931 case PTR_TO_SOCKET:
8932 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08008933 case PTR_TO_SOCK_COMMON:
8934 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08008935 case PTR_TO_TCP_SOCK:
8936 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07008937 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -07008938 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07008939 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -07008940 return false;
8941 default:
8942 return true;
8943 }
8944}
8945
8946/* If an instruction was previously used with particular pointer types, then we
8947 * need to be careful to avoid cases such as the below, where it may be ok
8948 * for one branch accessing the pointer, but not ok for the other branch:
8949 *
8950 * R1 = sock_ptr
8951 * goto X;
8952 * ...
8953 * R1 = some_other_valid_ptr;
8954 * goto X;
8955 * ...
8956 * R2 = *(u32 *)(R1 + 0);
8957 */
8958static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
8959{
8960 return src != prev && (!reg_type_mismatch_ok(src) ||
8961 !reg_type_mismatch_ok(prev));
8962}
8963
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008964static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008965{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07008966 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008967 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008968 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008969 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008970 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008971 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008972 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008973
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008974 for (;;) {
8975 struct bpf_insn *insn;
8976 u8 class;
8977 int err;
8978
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008979 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008980 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008981 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008982 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008983 return -EFAULT;
8984 }
8985
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008986 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008987 class = BPF_CLASS(insn->code);
8988
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008989 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008990 verbose(env,
8991 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008992 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008993 return -E2BIG;
8994 }
8995
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008996 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008997 if (err < 0)
8998 return err;
8999 if (err == 1) {
9000 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009001 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009002 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009003 verbose(env, "\nfrom %d to %d%s: safe\n",
9004 env->prev_insn_idx, env->insn_idx,
9005 env->cur_state->speculative ?
9006 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009007 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009008 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009009 }
9010 goto process_bpf_exit;
9011 }
9012
Alexei Starovoitovc3494802018-12-03 22:46:04 -08009013 if (signal_pending(current))
9014 return -EAGAIN;
9015
Daniel Borkmann3c2ce602017-05-18 03:00:06 +02009016 if (need_resched())
9017 cond_resched();
9018
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009019 if (env->log.level & BPF_LOG_LEVEL2 ||
9020 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9021 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009022 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -07009023 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009024 verbose(env, "\nfrom %d to %d%s:",
9025 env->prev_insn_idx, env->insn_idx,
9026 env->cur_state->speculative ?
9027 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009028 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009029 do_print_state = false;
9030 }
9031
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009032 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01009033 const struct bpf_insn_cbs cbs = {
9034 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +01009035 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +01009036 };
9037
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009038 verbose_linfo(env, env->insn_idx, "; ");
9039 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +01009040 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009041 }
9042
Jakub Kicinskicae19272017-12-27 18:39:05 -08009043 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009044 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9045 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -08009046 if (err)
9047 return err;
9048 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +01009049
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009050 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009051 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009052 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -07009053
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009054 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07009055 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009056 if (err)
9057 return err;
9058
9059 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009060 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009061
9062 /* check for reserved fields is already done */
9063
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009064 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01009065 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009066 if (err)
9067 return err;
9068
Edward Creedc503a82017-08-15 20:34:35 +01009069 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009070 if (err)
9071 return err;
9072
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -07009073 src_reg_type = regs[insn->src_reg].type;
9074
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009075 /* check that memory (src_reg + off) is readable,
9076 * the state of dst_reg will be updated by this func
9077 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009078 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9079 insn->off, BPF_SIZE(insn->code),
9080 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009081 if (err)
9082 return err;
9083
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009084 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009085
9086 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009087 /* saw a valid insn
9088 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009089 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009090 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009091 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009092
Joe Stringerc64b7982018-10-02 13:35:33 -07009093 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009094 /* ABuser program is trying to use the same insn
9095 * dst_reg = *(u32*) (src_reg + off)
9096 * with different pointer types:
9097 * src_reg == ctx in one branch and
9098 * src_reg == stack|map in some other branch.
9099 * Reject it.
9100 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009101 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009102 return -EINVAL;
9103 }
9104
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009105 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009106 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009107
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009108 if (BPF_MODE(insn->code) == BPF_XADD) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009109 err = check_xadd(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009110 if (err)
9111 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009112 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009113 continue;
9114 }
9115
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009116 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01009117 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009118 if (err)
9119 return err;
9120 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01009121 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009122 if (err)
9123 return err;
9124
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009125 dst_reg_type = regs[insn->dst_reg].type;
9126
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009127 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009128 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9129 insn->off, BPF_SIZE(insn->code),
9130 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009131 if (err)
9132 return err;
9133
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009134 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009135
9136 if (*prev_dst_type == NOT_INIT) {
9137 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -07009138 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009139 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009140 return -EINVAL;
9141 }
9142
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009143 } else if (class == BPF_ST) {
9144 if (BPF_MODE(insn->code) != BPF_MEM ||
9145 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009146 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009147 return -EINVAL;
9148 }
9149 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01009150 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009151 if (err)
9152 return err;
9153
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01009154 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -07009155 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02009156 insn->dst_reg,
9157 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01009158 return -EACCES;
9159 }
9160
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009161 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009162 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9163 insn->off, BPF_SIZE(insn->code),
9164 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009165 if (err)
9166 return err;
9167
Jiong Wang092ed092019-01-26 12:26:01 -05009168 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009169 u8 opcode = BPF_OP(insn->code);
9170
Alexei Starovoitov25897262019-06-15 12:12:20 -07009171 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009172 if (opcode == BPF_CALL) {
9173 if (BPF_SRC(insn->code) != BPF_K ||
9174 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009175 (insn->src_reg != BPF_REG_0 &&
9176 insn->src_reg != BPF_PSEUDO_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -05009177 insn->dst_reg != BPF_REG_0 ||
9178 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009179 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009180 return -EINVAL;
9181 }
9182
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009183 if (env->cur_state->active_spin_lock &&
9184 (insn->src_reg == BPF_PSEUDO_CALL ||
9185 insn->imm != BPF_FUNC_spin_unlock)) {
9186 verbose(env, "function calls are not allowed while holding a lock\n");
9187 return -EINVAL;
9188 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009189 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009190 err = check_func_call(env, insn, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009191 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009192 err = check_helper_call(env, insn->imm, env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009193 if (err)
9194 return err;
9195
9196 } else if (opcode == BPF_JA) {
9197 if (BPF_SRC(insn->code) != BPF_K ||
9198 insn->imm != 0 ||
9199 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05009200 insn->dst_reg != BPF_REG_0 ||
9201 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009202 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009203 return -EINVAL;
9204 }
9205
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009206 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009207 continue;
9208
9209 } else if (opcode == BPF_EXIT) {
9210 if (BPF_SRC(insn->code) != BPF_K ||
9211 insn->imm != 0 ||
9212 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05009213 insn->dst_reg != BPF_REG_0 ||
9214 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009215 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009216 return -EINVAL;
9217 }
9218
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009219 if (env->cur_state->active_spin_lock) {
9220 verbose(env, "bpf_spin_unlock is missing\n");
9221 return -EINVAL;
9222 }
9223
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009224 if (state->curframe) {
9225 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009226 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009227 if (err)
9228 return err;
9229 do_print_state = true;
9230 continue;
9231 }
9232
Joe Stringerfd978bf72018-10-02 13:35:35 -07009233 err = check_reference_leak(env);
9234 if (err)
9235 return err;
9236
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009237 err = check_return_code(env);
9238 if (err)
9239 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009240process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -07009241 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009242 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07009243 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009244 if (err < 0) {
9245 if (err != -ENOENT)
9246 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009247 break;
9248 } else {
9249 do_print_state = true;
9250 continue;
9251 }
9252 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009253 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009254 if (err)
9255 return err;
9256 }
9257 } else if (class == BPF_LD) {
9258 u8 mode = BPF_MODE(insn->code);
9259
9260 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009261 err = check_ld_abs(env, insn);
9262 if (err)
9263 return err;
9264
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009265 } else if (mode == BPF_IMM) {
9266 err = check_ld_imm(env, insn);
9267 if (err)
9268 return err;
9269
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009270 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009271 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009272 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009273 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009274 return -EINVAL;
9275 }
9276 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009277 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009278 return -EINVAL;
9279 }
9280
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009281 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009282 }
9283
9284 return 0;
9285}
9286
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009287static int check_map_prealloc(struct bpf_map *map)
9288{
9289 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07009290 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9291 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009292 !(map->map_flags & BPF_F_NO_PREALLOC);
9293}
9294
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009295static bool is_tracing_prog_type(enum bpf_prog_type type)
9296{
9297 switch (type) {
9298 case BPF_PROG_TYPE_KPROBE:
9299 case BPF_PROG_TYPE_TRACEPOINT:
9300 case BPF_PROG_TYPE_PERF_EVENT:
9301 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9302 return true;
9303 default:
9304 return false;
9305 }
9306}
9307
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009308static bool is_preallocated_map(struct bpf_map *map)
9309{
9310 if (!check_map_prealloc(map))
9311 return false;
9312 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
9313 return false;
9314 return true;
9315}
9316
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009317static int check_map_prog_compatibility(struct bpf_verifier_env *env,
9318 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009319 struct bpf_prog *prog)
9320
9321{
Udip Pant7e407812020-08-25 16:20:00 -07009322 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009323 /*
9324 * Validate that trace type programs use preallocated hash maps.
9325 *
9326 * For programs attached to PERF events this is mandatory as the
9327 * perf NMI can hit any arbitrary code sequence.
9328 *
9329 * All other trace types using preallocated hash maps are unsafe as
9330 * well because tracepoint or kprobes can be inside locked regions
9331 * of the memory allocator or at a place where a recursion into the
9332 * memory allocator would see inconsistent state.
9333 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01009334 * On RT enabled kernels run-time allocation of all trace type
9335 * programs is strictly prohibited due to lock type constraints. On
9336 * !RT kernels it is allowed for backwards compatibility reasons for
9337 * now, but warnings are emitted so developers are made aware of
9338 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009339 */
Udip Pant7e407812020-08-25 16:20:00 -07009340 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
9341 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009342 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07009343 return -EINVAL;
9344 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01009345 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
9346 verbose(env, "trace type programs can only use preallocated hash map\n");
9347 return -EINVAL;
9348 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01009349 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9350 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 -07009351 }
Jakub Kicinskia3884572018-01-11 20:29:09 -08009352
Udip Pant7e407812020-08-25 16:20:00 -07009353 if ((is_tracing_prog_type(prog_type) ||
9354 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009355 map_value_has_spin_lock(map)) {
9356 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9357 return -EINVAL;
9358 }
9359
Jakub Kicinskia3884572018-01-11 20:29:09 -08009360 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -07009361 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -08009362 verbose(env, "offload device mismatch between prog and map\n");
9363 return -EINVAL;
9364 }
9365
Martin KaFai Lau85d33df2020-01-08 16:35:05 -08009366 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9367 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9368 return -EINVAL;
9369 }
9370
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -07009371 if (prog->aux->sleepable)
9372 switch (map->map_type) {
9373 case BPF_MAP_TYPE_HASH:
9374 case BPF_MAP_TYPE_LRU_HASH:
9375 case BPF_MAP_TYPE_ARRAY:
9376 if (!is_preallocated_map(map)) {
9377 verbose(env,
9378 "Sleepable programs can only use preallocated hash maps\n");
9379 return -EINVAL;
9380 }
9381 break;
9382 default:
9383 verbose(env,
9384 "Sleepable programs can only use array and hash maps\n");
9385 return -EINVAL;
9386 }
9387
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009388 return 0;
9389}
9390
Roman Gushchinb741f162018-09-28 14:45:43 +00009391static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9392{
9393 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9394 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9395}
9396
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009397/* look for pseudo eBPF instructions that access map FDs and
9398 * replace them with actual map pointers
9399 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009400static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009401{
9402 struct bpf_insn *insn = env->prog->insnsi;
9403 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009404 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009405
Daniel Borkmannf1f77142017-01-13 23:38:15 +01009406 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +01009407 if (err)
9408 return err;
9409
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009410 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009411 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009412 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009413 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009414 return -EINVAL;
9415 }
9416
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009417 if (BPF_CLASS(insn->code) == BPF_STX &&
9418 ((BPF_MODE(insn->code) != BPF_MEM &&
9419 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009420 verbose(env, "BPF_STX uses reserved fields\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009421 return -EINVAL;
9422 }
9423
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009424 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009425 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009426 struct bpf_map *map;
9427 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009428 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009429
9430 if (i == insn_cnt - 1 || insn[1].code != 0 ||
9431 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9432 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009433 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009434 return -EINVAL;
9435 }
9436
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009437 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009438 /* valid generic load 64-bit imm */
9439 goto next_insn;
9440
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009441 /* In final convert_pseudo_ld_imm64() step, this is
9442 * converted into regular 64-bit imm load insn.
9443 */
9444 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9445 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9446 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9447 insn[1].imm != 0)) {
9448 verbose(env,
9449 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009450 return -EINVAL;
9451 }
9452
Daniel Borkmann20182392019-03-04 21:08:53 +01009453 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +01009454 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009455 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009456 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +01009457 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009458 return PTR_ERR(map);
9459 }
9460
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009461 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07009462 if (err) {
9463 fdput(f);
9464 return err;
9465 }
9466
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009467 aux = &env->insn_aux_data[i];
9468 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9469 addr = (unsigned long)map;
9470 } else {
9471 u32 off = insn[1].imm;
9472
9473 if (off >= BPF_MAX_VAR_OFF) {
9474 verbose(env, "direct value offset of %u is not allowed\n", off);
9475 fdput(f);
9476 return -EINVAL;
9477 }
9478
9479 if (!map->ops->map_direct_value_addr) {
9480 verbose(env, "no direct value access support for this map type\n");
9481 fdput(f);
9482 return -EINVAL;
9483 }
9484
9485 err = map->ops->map_direct_value_addr(map, &addr, off);
9486 if (err) {
9487 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9488 map->value_size, off);
9489 fdput(f);
9490 return err;
9491 }
9492
9493 aux->map_off = off;
9494 addr += off;
9495 }
9496
9497 insn[0].imm = (u32)addr;
9498 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009499
9500 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009501 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009502 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009503 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009504 fdput(f);
9505 goto next_insn;
9506 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009507 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009508
9509 if (env->used_map_cnt >= MAX_USED_MAPS) {
9510 fdput(f);
9511 return -E2BIG;
9512 }
9513
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009514 /* hold the map. If the program is rejected by verifier,
9515 * the map will be released by release_maps() or it
9516 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -07009517 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009518 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -08009519 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009520
9521 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -07009522 env->used_maps[env->used_map_cnt++] = map;
9523
Roman Gushchinb741f162018-09-28 14:45:43 +00009524 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +01009525 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +00009526 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -07009527 fdput(f);
9528 return -EBUSY;
9529 }
9530
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009531 fdput(f);
9532next_insn:
9533 insn++;
9534 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +01009535 continue;
9536 }
9537
9538 /* Basic sanity check before we invest more work here. */
9539 if (!bpf_opcode_in_insntable(insn->code)) {
9540 verbose(env, "unknown opcode %02x\n", insn->code);
9541 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009542 }
9543 }
9544
9545 /* now all pseudo BPF_LD_IMM64 instructions load valid
9546 * 'struct bpf_map *' into a register instead of user map_fd.
9547 * These pointers will be used later by verifier to validate map access.
9548 */
9549 return 0;
9550}
9551
9552/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009553static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009554{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +01009555 __bpf_free_used_maps(env->prog->aux, env->used_maps,
9556 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009557}
9558
9559/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009560static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009561{
9562 struct bpf_insn *insn = env->prog->insnsi;
9563 int insn_cnt = env->prog->len;
9564 int i;
9565
9566 for (i = 0; i < insn_cnt; i++, insn++)
9567 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9568 insn->src_reg = 0;
9569}
9570
Alexei Starovoitov80419022017-03-15 18:26:41 -07009571/* single env->prog->insni[off] instruction was replaced with the range
9572 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9573 * [0, off) and [off, end) to new locations, so the patched range stays zero
9574 */
Jiong Wangb325fbc2019-05-24 23:25:13 +01009575static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9576 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -07009577{
9578 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009579 struct bpf_insn *insn = new_prog->insnsi;
9580 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009581 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -07009582
Jiong Wangb325fbc2019-05-24 23:25:13 +01009583 /* aux info at OFF always needs adjustment, no matter fast path
9584 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9585 * original insn at old prog.
9586 */
9587 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9588
Alexei Starovoitov80419022017-03-15 18:26:41 -07009589 if (cnt == 1)
9590 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009591 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -07009592 new_data = vzalloc(array_size(prog_len,
9593 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -07009594 if (!new_data)
9595 return -ENOMEM;
9596 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9597 memcpy(new_data + off + cnt - 1, old_data + off,
9598 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +01009599 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009600 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +01009601 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9602 }
Alexei Starovoitov80419022017-03-15 18:26:41 -07009603 env->insn_aux_data = new_data;
9604 vfree(old_data);
9605 return 0;
9606}
9607
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009608static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9609{
9610 int i;
9611
9612 if (len == 1)
9613 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -04009614 /* NOTE: fake 'exit' subprog should be updated as well. */
9615 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +00009616 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009617 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -04009618 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009619 }
9620}
9621
Alexei Starovoitov80419022017-03-15 18:26:41 -07009622static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
9623 const struct bpf_insn *patch, u32 len)
9624{
9625 struct bpf_prog *new_prog;
9626
9627 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -07009628 if (IS_ERR(new_prog)) {
9629 if (PTR_ERR(new_prog) == -ERANGE)
9630 verbose(env,
9631 "insn %d cannot be patched due to 16-bit range\n",
9632 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -07009633 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -07009634 }
Jiong Wangb325fbc2019-05-24 23:25:13 +01009635 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -07009636 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009637 adjust_subprog_starts(env, off, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -07009638 return new_prog;
9639}
9640
Jakub Kicinski52875a02019-01-22 22:45:20 -08009641static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
9642 u32 off, u32 cnt)
9643{
9644 int i, j;
9645
9646 /* find first prog starting at or after off (first to remove) */
9647 for (i = 0; i < env->subprog_cnt; i++)
9648 if (env->subprog_info[i].start >= off)
9649 break;
9650 /* find first prog starting at or after off + cnt (first to stay) */
9651 for (j = i; j < env->subprog_cnt; j++)
9652 if (env->subprog_info[j].start >= off + cnt)
9653 break;
9654 /* if j doesn't start exactly at off + cnt, we are just removing
9655 * the front of previous prog
9656 */
9657 if (env->subprog_info[j].start != off + cnt)
9658 j--;
9659
9660 if (j > i) {
9661 struct bpf_prog_aux *aux = env->prog->aux;
9662 int move;
9663
9664 /* move fake 'exit' subprog as well */
9665 move = env->subprog_cnt + 1 - j;
9666
9667 memmove(env->subprog_info + i,
9668 env->subprog_info + j,
9669 sizeof(*env->subprog_info) * move);
9670 env->subprog_cnt -= j - i;
9671
9672 /* remove func_info */
9673 if (aux->func_info) {
9674 move = aux->func_info_cnt - j;
9675
9676 memmove(aux->func_info + i,
9677 aux->func_info + j,
9678 sizeof(*aux->func_info) * move);
9679 aux->func_info_cnt -= j - i;
9680 /* func_info->insn_off is set after all code rewrites,
9681 * in adjust_btf_func() - no need to adjust
9682 */
9683 }
9684 } else {
9685 /* convert i from "first prog to remove" to "first to adjust" */
9686 if (env->subprog_info[i].start == off)
9687 i++;
9688 }
9689
9690 /* update fake 'exit' subprog as well */
9691 for (; i <= env->subprog_cnt; i++)
9692 env->subprog_info[i].start -= cnt;
9693
9694 return 0;
9695}
9696
9697static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
9698 u32 cnt)
9699{
9700 struct bpf_prog *prog = env->prog;
9701 u32 i, l_off, l_cnt, nr_linfo;
9702 struct bpf_line_info *linfo;
9703
9704 nr_linfo = prog->aux->nr_linfo;
9705 if (!nr_linfo)
9706 return 0;
9707
9708 linfo = prog->aux->linfo;
9709
9710 /* find first line info to remove, count lines to be removed */
9711 for (i = 0; i < nr_linfo; i++)
9712 if (linfo[i].insn_off >= off)
9713 break;
9714
9715 l_off = i;
9716 l_cnt = 0;
9717 for (; i < nr_linfo; i++)
9718 if (linfo[i].insn_off < off + cnt)
9719 l_cnt++;
9720 else
9721 break;
9722
9723 /* First live insn doesn't match first live linfo, it needs to "inherit"
9724 * last removed linfo. prog is already modified, so prog->len == off
9725 * means no live instructions after (tail of the program was removed).
9726 */
9727 if (prog->len != off && l_cnt &&
9728 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
9729 l_cnt--;
9730 linfo[--i].insn_off = off + cnt;
9731 }
9732
9733 /* remove the line info which refer to the removed instructions */
9734 if (l_cnt) {
9735 memmove(linfo + l_off, linfo + i,
9736 sizeof(*linfo) * (nr_linfo - i));
9737
9738 prog->aux->nr_linfo -= l_cnt;
9739 nr_linfo = prog->aux->nr_linfo;
9740 }
9741
9742 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9743 for (i = l_off; i < nr_linfo; i++)
9744 linfo[i].insn_off -= cnt;
9745
9746 /* fix up all subprogs (incl. 'exit') which start >= off */
9747 for (i = 0; i <= env->subprog_cnt; i++)
9748 if (env->subprog_info[i].linfo_idx > l_off) {
9749 /* program may have started in the removed region but
9750 * may not be fully removed
9751 */
9752 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
9753 env->subprog_info[i].linfo_idx -= l_cnt;
9754 else
9755 env->subprog_info[i].linfo_idx = l_off;
9756 }
9757
9758 return 0;
9759}
9760
9761static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
9762{
9763 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9764 unsigned int orig_prog_len = env->prog->len;
9765 int err;
9766
Jakub Kicinski08ca90a2019-01-22 22:45:24 -08009767 if (bpf_prog_is_dev_bound(env->prog->aux))
9768 bpf_prog_offload_remove_insns(env, off, cnt);
9769
Jakub Kicinski52875a02019-01-22 22:45:20 -08009770 err = bpf_remove_insns(env->prog, off, cnt);
9771 if (err)
9772 return err;
9773
9774 err = adjust_subprog_starts_after_remove(env, off, cnt);
9775 if (err)
9776 return err;
9777
9778 err = bpf_adj_linfo_after_remove(env, off, cnt);
9779 if (err)
9780 return err;
9781
9782 memmove(aux_data + off, aux_data + off + cnt,
9783 sizeof(*aux_data) * (orig_prog_len - off - cnt));
9784
9785 return 0;
9786}
9787
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01009788/* The verifier does more data flow analysis than llvm and will not
9789 * explore branches that are dead at run time. Malicious programs can
9790 * have dead code too. Therefore replace all dead at-run-time code
9791 * with 'ja -1'.
9792 *
9793 * Just nops are not optimal, e.g. if they would sit at the end of the
9794 * program and through another bug we would manage to jump there, then
9795 * we'd execute beyond program memory otherwise. Returning exception
9796 * code also wouldn't work since we can have subprogs where the dead
9797 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009798 */
9799static void sanitize_dead_code(struct bpf_verifier_env *env)
9800{
9801 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01009802 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009803 struct bpf_insn *insn = env->prog->insnsi;
9804 const int insn_cnt = env->prog->len;
9805 int i;
9806
9807 for (i = 0; i < insn_cnt; i++) {
9808 if (aux_data[i].seen)
9809 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01009810 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -08009811 }
9812}
9813
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08009814static bool insn_is_cond_jump(u8 code)
9815{
9816 u8 op;
9817
Jiong Wang092ed092019-01-26 12:26:01 -05009818 if (BPF_CLASS(code) == BPF_JMP32)
9819 return true;
9820
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08009821 if (BPF_CLASS(code) != BPF_JMP)
9822 return false;
9823
9824 op = BPF_OP(code);
9825 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
9826}
9827
9828static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
9829{
9830 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9831 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9832 struct bpf_insn *insn = env->prog->insnsi;
9833 const int insn_cnt = env->prog->len;
9834 int i;
9835
9836 for (i = 0; i < insn_cnt; i++, insn++) {
9837 if (!insn_is_cond_jump(insn->code))
9838 continue;
9839
9840 if (!aux_data[i + 1].seen)
9841 ja.off = insn->off;
9842 else if (!aux_data[i + 1 + insn->off].seen)
9843 ja.off = 0;
9844 else
9845 continue;
9846
Jakub Kicinski08ca90a2019-01-22 22:45:24 -08009847 if (bpf_prog_is_dev_bound(env->prog->aux))
9848 bpf_prog_offload_replace_insn(env, i, &ja);
9849
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08009850 memcpy(insn, &ja, sizeof(ja));
9851 }
9852}
9853
Jakub Kicinski52875a02019-01-22 22:45:20 -08009854static int opt_remove_dead_code(struct bpf_verifier_env *env)
9855{
9856 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9857 int insn_cnt = env->prog->len;
9858 int i, err;
9859
9860 for (i = 0; i < insn_cnt; i++) {
9861 int j;
9862
9863 j = 0;
9864 while (i + j < insn_cnt && !aux_data[i + j].seen)
9865 j++;
9866 if (!j)
9867 continue;
9868
9869 err = verifier_remove_insns(env, i, j);
9870 if (err)
9871 return err;
9872 insn_cnt = env->prog->len;
9873 }
9874
9875 return 0;
9876}
9877
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -08009878static int opt_remove_nops(struct bpf_verifier_env *env)
9879{
9880 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9881 struct bpf_insn *insn = env->prog->insnsi;
9882 int insn_cnt = env->prog->len;
9883 int i, err;
9884
9885 for (i = 0; i < insn_cnt; i++) {
9886 if (memcmp(&insn[i], &ja, sizeof(ja)))
9887 continue;
9888
9889 err = verifier_remove_insns(env, i, 1);
9890 if (err)
9891 return err;
9892 insn_cnt--;
9893 i--;
9894 }
9895
9896 return 0;
9897}
9898
Jiong Wangd6c23082019-05-24 23:25:18 +01009899static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
9900 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009901{
Jiong Wangd6c23082019-05-24 23:25:18 +01009902 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009903 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +01009904 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009905 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009906 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +01009907 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009908
Jiong Wangd6c23082019-05-24 23:25:18 +01009909 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009910 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +01009911 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
9912 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
9913 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009914 for (i = 0; i < len; i++) {
9915 int adj_idx = i + delta;
9916 struct bpf_insn insn;
9917
Jiong Wangd6c23082019-05-24 23:25:18 +01009918 insn = insns[adj_idx];
9919 if (!aux[adj_idx].zext_dst) {
9920 u8 code, class;
9921 u32 imm_rnd;
9922
9923 if (!rnd_hi32)
9924 continue;
9925
9926 code = insn.code;
9927 class = BPF_CLASS(code);
9928 if (insn_no_def(&insn))
9929 continue;
9930
9931 /* NOTE: arg "reg" (the fourth one) is only used for
9932 * BPF_STX which has been ruled out in above
9933 * check, it is safe to pass NULL here.
9934 */
9935 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
9936 if (class == BPF_LD &&
9937 BPF_MODE(code) == BPF_IMM)
9938 i++;
9939 continue;
9940 }
9941
9942 /* ctx load could be transformed into wider load. */
9943 if (class == BPF_LDX &&
9944 aux[adj_idx].ptr_type == PTR_TO_CTX)
9945 continue;
9946
9947 imm_rnd = get_random_int();
9948 rnd_hi32_patch[0] = insn;
9949 rnd_hi32_patch[1].imm = imm_rnd;
9950 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
9951 patch = rnd_hi32_patch;
9952 patch_len = 4;
9953 goto apply_patch_buffer;
9954 }
9955
9956 if (!bpf_jit_needs_zext())
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009957 continue;
9958
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009959 zext_patch[0] = insn;
9960 zext_patch[1].dst_reg = insn.dst_reg;
9961 zext_patch[1].src_reg = insn.dst_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +01009962 patch = zext_patch;
9963 patch_len = 2;
9964apply_patch_buffer:
9965 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009966 if (!new_prog)
9967 return -ENOMEM;
9968 env->prog = new_prog;
9969 insns = new_prog->insnsi;
9970 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +01009971 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01009972 }
9973
9974 return 0;
9975}
9976
Joe Stringerc64b7982018-10-02 13:35:33 -07009977/* convert load instructions that access fields of a context type into a
9978 * sequence of instructions that access fields of the underlying structure:
9979 * struct __sk_buff -> struct sk_buff
9980 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009981 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009982static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009983{
Jakub Kicinski00176a32017-10-16 16:40:54 -07009984 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +02009985 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009986 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +02009987 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -08009988 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009989 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009990 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +02009991 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009992
Daniel Borkmannb09928b2018-10-24 22:05:49 +02009993 if (ops->gen_prologue || env->seen_direct_write) {
9994 if (!ops->gen_prologue) {
9995 verbose(env, "bpf verifier is misconfigured\n");
9996 return -EINVAL;
9997 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +02009998 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
9999 env->prog);
10000 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010001 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010002 return -EINVAL;
10003 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070010004 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010005 if (!new_prog)
10006 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070010007
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010008 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010009 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010010 }
10011 }
10012
Joe Stringerc64b7982018-10-02 13:35:33 -070010013 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010014 return 0;
10015
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010016 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020010017
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010018 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070010019 bpf_convert_ctx_access_t convert_ctx_access;
10020
Daniel Borkmann62c79892017-01-12 11:51:33 +010010021 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10022 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10023 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070010024 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010025 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +010010026 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10027 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10028 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070010029 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010030 type = BPF_WRITE;
10031 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010032 continue;
10033
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070010034 if (type == BPF_WRITE &&
10035 env->insn_aux_data[i + delta].sanitize_stack_off) {
10036 struct bpf_insn patch[] = {
10037 /* Sanitize suspicious stack slot with zero.
10038 * There are no memory dependencies for this store,
10039 * since it's only using frame pointer and immediate
10040 * constant of zero
10041 */
10042 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
10043 env->insn_aux_data[i + delta].sanitize_stack_off,
10044 0),
10045 /* the original STX instruction will immediately
10046 * overwrite the same stack slot with appropriate value
10047 */
10048 *insn,
10049 };
10050
10051 cnt = ARRAY_SIZE(patch);
10052 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10053 if (!new_prog)
10054 return -ENOMEM;
10055
10056 delta += cnt - 1;
10057 env->prog = new_prog;
10058 insn = new_prog->insnsi + i + delta;
10059 continue;
10060 }
10061
Joe Stringerc64b7982018-10-02 13:35:33 -070010062 switch (env->insn_aux_data[i + delta].ptr_type) {
10063 case PTR_TO_CTX:
10064 if (!ops->convert_ctx_access)
10065 continue;
10066 convert_ctx_access = ops->convert_ctx_access;
10067 break;
10068 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080010069 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070010070 convert_ctx_access = bpf_sock_convert_ctx_access;
10071 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080010072 case PTR_TO_TCP_SOCK:
10073 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
10074 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070010075 case PTR_TO_XDP_SOCK:
10076 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
10077 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010078 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080010079 if (type == BPF_READ) {
10080 insn->code = BPF_LDX | BPF_PROBE_MEM |
10081 BPF_SIZE((insn)->code);
10082 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070010083 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010084 verbose(env, "Writes through BTF pointers are not allowed\n");
10085 return -EINVAL;
10086 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010087 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070010088 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010089 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070010090 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010091
Yonghong Song31fd8582017-06-13 15:52:13 -070010092 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010093 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070010094
10095 /* If the read access is a narrower load of the field,
10096 * convert to a 4/8-byte load, to minimum program type specific
10097 * convert_ctx_access changes. If conversion is successful,
10098 * we will apply proper mask to the result.
10099 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020010100 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010101 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
10102 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070010103 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020010104 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070010105
Daniel Borkmannf96da092017-07-02 02:13:27 +020010106 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010107 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020010108 return -EINVAL;
10109 }
10110
10111 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070010112 if (ctx_field_size == 4)
10113 size_code = BPF_W;
10114 else if (ctx_field_size == 8)
10115 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020010116
Daniel Borkmannbc231052018-06-02 23:06:39 +020010117 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070010118 insn->code = BPF_LDX | BPF_MEM | size_code;
10119 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020010120
10121 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070010122 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
10123 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020010124 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
10125 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010126 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010127 return -EINVAL;
10128 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020010129
10130 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020010131 u8 shift = bpf_ctx_narrow_access_offset(
10132 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010133 if (ctx_field_size <= 4) {
10134 if (shift)
10135 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
10136 insn->dst_reg,
10137 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070010138 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020010139 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010140 } else {
10141 if (shift)
10142 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
10143 insn->dst_reg,
10144 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070010145 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020010146 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080010147 }
Yonghong Song31fd8582017-06-13 15:52:13 -070010148 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010149
Alexei Starovoitov80419022017-03-15 18:26:41 -070010150 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010151 if (!new_prog)
10152 return -ENOMEM;
10153
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010154 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010155
10156 /* keep walking new program and skip insns we just inserted */
10157 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010158 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010159 }
10160
10161 return 0;
10162}
10163
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010164static int jit_subprogs(struct bpf_verifier_env *env)
10165{
10166 struct bpf_prog *prog = env->prog, **func, *tmp;
10167 int i, j, subprog_start, subprog_end = 0, len, subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010010168 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010169 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070010170 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010171
Jiong Wangf910cef2018-05-02 16:17:17 -040010172 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010173 return 0;
10174
Daniel Borkmann7105e822017-12-20 13:42:57 +010010175 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010176 if (insn->code != (BPF_JMP | BPF_CALL) ||
10177 insn->src_reg != BPF_PSEUDO_CALL)
10178 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010179 /* Upon error here we cannot fall back to interpreter but
10180 * need a hard reject of the program. Thus -EFAULT is
10181 * propagated in any case.
10182 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010183 subprog = find_subprog(env, i + insn->imm + 1);
10184 if (subprog < 0) {
10185 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10186 i + insn->imm + 1);
10187 return -EFAULT;
10188 }
10189 /* temporarily remember subprog id inside insn instead of
10190 * aux_data, since next loop will split up all insns into funcs
10191 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010192 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010193 /* remember original imm in case JIT fails and fallback
10194 * to interpreter will be needed
10195 */
10196 env->insn_aux_data[i].call_imm = insn->imm;
10197 /* point imm to __bpf_call_base+1 from JITs point of view */
10198 insn->imm = 1;
10199 }
10200
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010201 err = bpf_prog_alloc_jited_linfo(prog);
10202 if (err)
10203 goto out_undo_insn;
10204
10205 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070010206 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010207 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010208 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010209
Jiong Wangf910cef2018-05-02 16:17:17 -040010210 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010211 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040010212 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010213
10214 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080010215 /* BPF_PROG_RUN doesn't call subprogs directly,
10216 * hence main prog stats include the runtime of subprogs.
10217 * subprogs don't have IDs and not reachable via prog_get_next_id
10218 * func[i]->aux->stats will never be accessed and stays NULL
10219 */
10220 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010221 if (!func[i])
10222 goto out_free;
10223 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
10224 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010010225 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010226 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010010227 if (bpf_prog_calc_tag(func[i]))
10228 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010229 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080010230 func[i]->aux->func_idx = i;
10231 /* the btf and func_info will be freed only at prog->aux */
10232 func[i]->aux->btf = prog->aux->btf;
10233 func[i]->aux->func_info = prog->aux->func_info;
10234
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010235 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10236 * Long term would need debug info to populate names
10237 */
10238 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040010239 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010240 func[i]->jit_requested = 1;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010241 func[i]->aux->linfo = prog->aux->linfo;
10242 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
10243 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
10244 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070010245 num_exentries = 0;
10246 insn = func[i]->insnsi;
10247 for (j = 0; j < func[i]->len; j++, insn++) {
10248 if (BPF_CLASS(insn->code) == BPF_LDX &&
10249 BPF_MODE(insn->code) == BPF_PROBE_MEM)
10250 num_exentries++;
10251 }
10252 func[i]->aux->num_exentries = num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010253 func[i] = bpf_int_jit_compile(func[i]);
10254 if (!func[i]->jited) {
10255 err = -ENOTSUPP;
10256 goto out_free;
10257 }
10258 cond_resched();
10259 }
10260 /* at this point all bpf functions were successfully JITed
10261 * now populate all bpf_calls with correct addresses and
10262 * run last pass of JIT
10263 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010264 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010265 insn = func[i]->insnsi;
10266 for (j = 0; j < func[i]->len; j++, insn++) {
10267 if (insn->code != (BPF_JMP | BPF_CALL) ||
10268 insn->src_reg != BPF_PSEUDO_CALL)
10269 continue;
10270 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +090010271 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
10272 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010273 }
Sandipan Das2162fed2018-05-24 12:26:45 +053010274
10275 /* we use the aux data to keep a list of the start addresses
10276 * of the JITed images for each function in the program
10277 *
10278 * for some architectures, such as powerpc64, the imm field
10279 * might not be large enough to hold the offset of the start
10280 * address of the callee's JITed image from __bpf_call_base
10281 *
10282 * in such cases, we can lookup the start address of a callee
10283 * by using its subprog id, available from the off field of
10284 * the call instruction, as an index for this list
10285 */
10286 func[i]->aux->func = func;
10287 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010288 }
Jiong Wangf910cef2018-05-02 16:17:17 -040010289 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010290 old_bpf_func = func[i]->bpf_func;
10291 tmp = bpf_int_jit_compile(func[i]);
10292 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
10293 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010294 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010295 goto out_free;
10296 }
10297 cond_resched();
10298 }
10299
10300 /* finally lock prog and jit images for all functions and
10301 * populate kallsysm
10302 */
Jiong Wangf910cef2018-05-02 16:17:17 -040010303 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010304 bpf_prog_lock_ro(func[i]);
10305 bpf_prog_kallsyms_add(func[i]);
10306 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010010307
10308 /* Last step: make now unused interpreter insns from main
10309 * prog consistent for later dump requests, so they can
10310 * later look the same as if they were interpreted only.
10311 */
10312 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Daniel Borkmann7105e822017-12-20 13:42:57 +010010313 if (insn->code != (BPF_JMP | BPF_CALL) ||
10314 insn->src_reg != BPF_PSEUDO_CALL)
10315 continue;
10316 insn->off = env->insn_aux_data[i].call_imm;
10317 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053010318 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010010319 }
10320
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010321 prog->jited = 1;
10322 prog->bpf_func = func[0]->bpf_func;
10323 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040010324 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010325 bpf_prog_free_unused_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010326 return 0;
10327out_free:
Jiong Wangf910cef2018-05-02 16:17:17 -040010328 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010329 if (func[i])
10330 bpf_jit_free(func[i]);
10331 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010332out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010333 /* cleanup main prog to be interpreted */
10334 prog->jit_requested = 0;
10335 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10336 if (insn->code != (BPF_JMP | BPF_CALL) ||
10337 insn->src_reg != BPF_PSEUDO_CALL)
10338 continue;
10339 insn->off = 0;
10340 insn->imm = env->insn_aux_data[i].call_imm;
10341 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010342 bpf_prog_free_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010343 return err;
10344}
10345
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010346static int fixup_call_args(struct bpf_verifier_env *env)
10347{
David S. Miller19d28fb2018-01-11 21:27:54 -050010348#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010349 struct bpf_prog *prog = env->prog;
10350 struct bpf_insn *insn = prog->insnsi;
10351 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050010352#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010010353 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010354
Quentin Monnete4052d02018-10-07 12:56:58 +010010355 if (env->prog->jit_requested &&
10356 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050010357 err = jit_subprogs(env);
10358 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080010359 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020010360 if (err == -EFAULT)
10361 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050010362 }
10363#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010364 for (i = 0; i < prog->len; i++, insn++) {
10365 if (insn->code != (BPF_JMP | BPF_CALL) ||
10366 insn->src_reg != BPF_PSEUDO_CALL)
10367 continue;
10368 depth = get_callee_stack_depth(env, insn, i);
10369 if (depth < 0)
10370 return depth;
10371 bpf_patch_call_args(insn, depth);
10372 }
David S. Miller19d28fb2018-01-11 21:27:54 -050010373 err = 0;
10374#endif
10375 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010376}
10377
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010378/* fixup insn->imm field of bpf_call instructions
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010379 * and inline eligible helpers as explicit sequence of BPF instructions
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010380 *
10381 * this function is called after eBPF program passed verification
10382 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010383static int fixup_bpf_calls(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010384{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010385 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010386 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010387 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010388 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010389 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020010390 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010391 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010392 struct bpf_insn insn_buf[16];
10393 struct bpf_prog *new_prog;
10394 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010395 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010396
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010397 for (i = 0; i < insn_cnt; i++, insn++) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010010398 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10399 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10400 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080010401 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010010402 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10403 struct bpf_insn mask_and_div[] = {
10404 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10405 /* Rx div 0 -> 0 */
10406 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10407 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10408 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10409 *insn,
10410 };
10411 struct bpf_insn mask_and_mod[] = {
10412 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10413 /* Rx mod 0 -> Rx */
10414 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10415 *insn,
10416 };
10417 struct bpf_insn *patchlet;
10418
10419 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10420 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10421 patchlet = mask_and_div + (is64 ? 1 : 0);
10422 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10423 } else {
10424 patchlet = mask_and_mod + (is64 ? 1 : 0);
10425 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10426 }
10427
10428 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080010429 if (!new_prog)
10430 return -ENOMEM;
10431
10432 delta += cnt - 1;
10433 env->prog = prog = new_prog;
10434 insn = new_prog->insnsi + i + delta;
10435 continue;
10436 }
10437
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020010438 if (BPF_CLASS(insn->code) == BPF_LD &&
10439 (BPF_MODE(insn->code) == BPF_ABS ||
10440 BPF_MODE(insn->code) == BPF_IND)) {
10441 cnt = env->ops->gen_ld_abs(insn, insn_buf);
10442 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10443 verbose(env, "bpf verifier is misconfigured\n");
10444 return -EINVAL;
10445 }
10446
10447 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10448 if (!new_prog)
10449 return -ENOMEM;
10450
10451 delta += cnt - 1;
10452 env->prog = prog = new_prog;
10453 insn = new_prog->insnsi + i + delta;
10454 continue;
10455 }
10456
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010457 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10458 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10459 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10460 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10461 struct bpf_insn insn_buf[16];
10462 struct bpf_insn *patch = &insn_buf[0];
10463 bool issrc, isneg;
10464 u32 off_reg;
10465
10466 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010010467 if (!aux->alu_state ||
10468 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010469 continue;
10470
10471 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10472 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10473 BPF_ALU_SANITIZE_SRC;
10474
10475 off_reg = issrc ? insn->src_reg : insn->dst_reg;
10476 if (isneg)
10477 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10478 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10479 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10480 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10481 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10482 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10483 if (issrc) {
10484 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10485 off_reg);
10486 insn->src_reg = BPF_REG_AX;
10487 } else {
10488 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10489 BPF_REG_AX);
10490 }
10491 if (isneg)
10492 insn->code = insn->code == code_add ?
10493 code_sub : code_add;
10494 *patch++ = *insn;
10495 if (issrc && isneg)
10496 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10497 cnt = patch - insn_buf;
10498
10499 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10500 if (!new_prog)
10501 return -ENOMEM;
10502
10503 delta += cnt - 1;
10504 env->prog = prog = new_prog;
10505 insn = new_prog->insnsi + i + delta;
10506 continue;
10507 }
10508
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010509 if (insn->code != (BPF_JMP | BPF_CALL))
10510 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010511 if (insn->src_reg == BPF_PSEUDO_CALL)
10512 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010513
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010514 if (insn->imm == BPF_FUNC_get_route_realm)
10515 prog->dst_needed = 1;
10516 if (insn->imm == BPF_FUNC_get_prandom_u32)
10517 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050010518 if (insn->imm == BPF_FUNC_override_return)
10519 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010520 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040010521 /* If we tail call into other programs, we
10522 * cannot make any assumptions since they can
10523 * be replaced dynamically during runtime in
10524 * the program array.
10525 */
10526 prog->cb_access = 1;
Alexei Starovoitov80a58d02017-05-30 13:31:30 -070010527 env->prog->aux->stack_depth = MAX_BPF_STACK;
Jiong Wange6478152018-11-08 04:08:42 -050010528 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040010529
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010530 /* mark bpf_tail_call as different opcode to avoid
10531 * conditional branch in the interpeter for every normal
10532 * call and to prevent accidental JITing by JIT compiler
10533 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010534 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010535 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070010536 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010537
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010538 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070010539 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010010540 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010541 !bpf_map_key_poisoned(aux) &&
10542 !bpf_map_ptr_poisoned(aux) &&
10543 !bpf_map_ptr_unpriv(aux)) {
10544 struct bpf_jit_poke_descriptor desc = {
10545 .reason = BPF_POKE_REASON_TAIL_CALL,
10546 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10547 .tail_call.key = bpf_map_key_immediate(aux),
10548 };
10549
10550 ret = bpf_jit_add_poke_descriptor(prog, &desc);
10551 if (ret < 0) {
10552 verbose(env, "adding tail call poke descriptor failed\n");
10553 return ret;
10554 }
10555
10556 insn->imm = ret + 1;
10557 continue;
10558 }
10559
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010560 if (!bpf_map_ptr_unpriv(aux))
10561 continue;
10562
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010563 /* instead of changing every JIT dealing with tail_call
10564 * emit two extra insns:
10565 * if (index >= max_entries) goto out;
10566 * index &= array->index_mask;
10567 * to avoid out-of-bounds cpu speculation
10568 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010569 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000010570 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010571 return -EINVAL;
10572 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010573
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010574 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080010575 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
10576 map_ptr->max_entries, 2);
10577 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
10578 container_of(map_ptr,
10579 struct bpf_array,
10580 map)->index_mask);
10581 insn_buf[2] = *insn;
10582 cnt = 3;
10583 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10584 if (!new_prog)
10585 return -ENOMEM;
10586
10587 delta += cnt - 1;
10588 env->prog = prog = new_prog;
10589 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010590 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010591 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010592
Daniel Borkmann89c63072017-08-19 03:12:45 +020010593 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020010594 * and other inlining handlers are currently limited to 64 bit
10595 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020010596 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080010597 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020010598 (insn->imm == BPF_FUNC_map_lookup_elem ||
10599 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020010600 insn->imm == BPF_FUNC_map_delete_elem ||
10601 insn->imm == BPF_FUNC_map_push_elem ||
10602 insn->imm == BPF_FUNC_map_pop_elem ||
10603 insn->imm == BPF_FUNC_map_peek_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020010604 aux = &env->insn_aux_data[i + delta];
10605 if (bpf_map_ptr_poisoned(aux))
10606 goto patch_call_imm;
10607
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010608 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020010609 ops = map_ptr->ops;
10610 if (insn->imm == BPF_FUNC_map_lookup_elem &&
10611 ops->map_gen_lookup) {
10612 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
10613 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10614 verbose(env, "bpf verifier is misconfigured\n");
10615 return -EINVAL;
10616 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010617
Daniel Borkmann09772d92018-06-02 23:06:35 +020010618 new_prog = bpf_patch_insn_data(env, i + delta,
10619 insn_buf, cnt);
10620 if (!new_prog)
10621 return -ENOMEM;
10622
10623 delta += cnt - 1;
10624 env->prog = prog = new_prog;
10625 insn = new_prog->insnsi + i + delta;
10626 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010627 }
10628
Daniel Borkmann09772d92018-06-02 23:06:35 +020010629 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
10630 (void *(*)(struct bpf_map *map, void *key))NULL));
10631 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
10632 (int (*)(struct bpf_map *map, void *key))NULL));
10633 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
10634 (int (*)(struct bpf_map *map, void *key, void *value,
10635 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020010636 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
10637 (int (*)(struct bpf_map *map, void *value,
10638 u64 flags))NULL));
10639 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
10640 (int (*)(struct bpf_map *map, void *value))NULL));
10641 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
10642 (int (*)(struct bpf_map *map, void *value))NULL));
10643
Daniel Borkmann09772d92018-06-02 23:06:35 +020010644 switch (insn->imm) {
10645 case BPF_FUNC_map_lookup_elem:
10646 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
10647 __bpf_call_base;
10648 continue;
10649 case BPF_FUNC_map_update_elem:
10650 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
10651 __bpf_call_base;
10652 continue;
10653 case BPF_FUNC_map_delete_elem:
10654 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
10655 __bpf_call_base;
10656 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020010657 case BPF_FUNC_map_push_elem:
10658 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
10659 __bpf_call_base;
10660 continue;
10661 case BPF_FUNC_map_pop_elem:
10662 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
10663 __bpf_call_base;
10664 continue;
10665 case BPF_FUNC_map_peek_elem:
10666 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
10667 __bpf_call_base;
10668 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +020010669 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010670
Daniel Borkmann09772d92018-06-02 23:06:35 +020010671 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010672 }
10673
Martin KaFai Lau5576b992020-01-22 15:36:46 -080010674 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10675 insn->imm == BPF_FUNC_jiffies64) {
10676 struct bpf_insn ld_jiffies_addr[2] = {
10677 BPF_LD_IMM64(BPF_REG_0,
10678 (unsigned long)&jiffies),
10679 };
10680
10681 insn_buf[0] = ld_jiffies_addr[0];
10682 insn_buf[1] = ld_jiffies_addr[1];
10683 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
10684 BPF_REG_0, 0);
10685 cnt = 3;
10686
10687 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
10688 cnt);
10689 if (!new_prog)
10690 return -ENOMEM;
10691
10692 delta += cnt - 1;
10693 env->prog = prog = new_prog;
10694 insn = new_prog->insnsi + i + delta;
10695 continue;
10696 }
10697
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070010698patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -070010699 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010700 /* all functions that have prototype and verifier allowed
10701 * programs to call them, must be real in-kernel functions
10702 */
10703 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010704 verbose(env,
10705 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010706 func_id_name(insn->imm), insn->imm);
10707 return -EFAULT;
10708 }
10709 insn->imm = fn->func - __bpf_call_base;
10710 }
10711
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010010712 /* Since poke tab is now finalized, publish aux to tracker. */
10713 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10714 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10715 if (!map_ptr->ops->map_poke_track ||
10716 !map_ptr->ops->map_poke_untrack ||
10717 !map_ptr->ops->map_poke_run) {
10718 verbose(env, "bpf verifier is misconfigured\n");
10719 return -EINVAL;
10720 }
10721
10722 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
10723 if (ret < 0) {
10724 verbose(env, "tracking tail call prog failed\n");
10725 return ret;
10726 }
10727 }
10728
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010729 return 0;
10730}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010731
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010732static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010733{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010734 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010735 int i;
10736
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010737 sl = env->free_list;
10738 while (sl) {
10739 sln = sl->next;
10740 free_verifier_state(&sl->state, false);
10741 kfree(sl);
10742 sl = sln;
10743 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010744 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010745
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010746 if (!env->explored_states)
10747 return;
10748
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010749 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010750 sl = env->explored_states[i];
10751
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010752 while (sl) {
10753 sln = sl->next;
10754 free_verifier_state(&sl->state, false);
10755 kfree(sl);
10756 sl = sln;
10757 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010758 env->explored_states[i] = NULL;
10759 }
10760}
10761
10762/* The verifier is using insn_aux_data[] to store temporary data during
10763 * verification and to store information for passes that run after the
10764 * verification like dead code sanitization. do_check_common() for subprogram N
10765 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10766 * temporary data after do_check_common() finds that subprogram N cannot be
10767 * verified independently. pass_cnt counts the number of times
10768 * do_check_common() was run and insn->aux->seen tells the pass number
10769 * insn_aux_data was touched. These variables are compared to clear temporary
10770 * data from failed pass. For testing and experiments do_check_common() can be
10771 * run multiple times even when prior attempt to verify is unsuccessful.
10772 */
10773static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
10774{
10775 struct bpf_insn *insn = env->prog->insnsi;
10776 struct bpf_insn_aux_data *aux;
10777 int i, class;
10778
10779 for (i = 0; i < env->prog->len; i++) {
10780 class = BPF_CLASS(insn[i].code);
10781 if (class != BPF_LDX && class != BPF_STX)
10782 continue;
10783 aux = &env->insn_aux_data[i];
10784 if (aux->seen != env->pass_cnt)
10785 continue;
10786 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
10787 }
10788}
10789
10790static int do_check_common(struct bpf_verifier_env *env, int subprog)
10791{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010792 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010793 struct bpf_verifier_state *state;
10794 struct bpf_reg_state *regs;
10795 int ret, i;
10796
10797 env->prev_linfo = NULL;
10798 env->pass_cnt++;
10799
10800 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
10801 if (!state)
10802 return -ENOMEM;
10803 state->curframe = 0;
10804 state->speculative = false;
10805 state->branches = 1;
10806 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
10807 if (!state->frame[0]) {
10808 kfree(state);
10809 return -ENOMEM;
10810 }
10811 env->cur_state = state;
10812 init_func_state(env, state->frame[0],
10813 BPF_MAIN_FUNC /* callsite */,
10814 0 /* frameno */,
10815 subprog);
10816
10817 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080010818 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010819 ret = btf_prepare_func_args(env, subprog, regs);
10820 if (ret)
10821 goto out;
10822 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
10823 if (regs[i].type == PTR_TO_CTX)
10824 mark_reg_known_zero(env, regs, i);
10825 else if (regs[i].type == SCALAR_VALUE)
10826 mark_reg_unknown(env, regs, i);
10827 }
10828 } else {
10829 /* 1st arg to a function */
10830 regs[BPF_REG_1].type = PTR_TO_CTX;
10831 mark_reg_known_zero(env, regs, BPF_REG_1);
10832 ret = btf_check_func_arg_match(env, subprog, regs);
10833 if (ret == -EFAULT)
10834 /* unlikely verifier bug. abort.
10835 * ret == 0 and ret < 0 are sadly acceptable for
10836 * main() function due to backward compatibility.
10837 * Like socket filter program may be written as:
10838 * int bpf_prog(struct pt_regs *ctx)
10839 * and never dereference that ctx in the program.
10840 * 'struct pt_regs' is a type mismatch for socket
10841 * filter that should be using 'struct __sk_buff'.
10842 */
10843 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010844 }
10845
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010846 ret = do_check(env);
10847out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080010848 /* check for NULL is necessary, since cur_state can be freed inside
10849 * do_check() under memory pressure.
10850 */
10851 if (env->cur_state) {
10852 free_verifier_state(env->cur_state, true);
10853 env->cur_state = NULL;
10854 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010855 while (!pop_stack(env, NULL, NULL, false));
10856 if (!ret && pop_log)
10857 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010858 free_states(env);
10859 if (ret)
10860 /* clean aux data in case subprog was rejected */
10861 sanitize_insn_aux_data(env);
10862 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010863}
10864
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010865/* Verify all global functions in a BPF program one by one based on their BTF.
10866 * All global functions must pass verification. Otherwise the whole program is rejected.
10867 * Consider:
10868 * int bar(int);
10869 * int foo(int f)
10870 * {
10871 * return bar(f);
10872 * }
10873 * int bar(int b)
10874 * {
10875 * ...
10876 * }
10877 * foo() will be verified first for R1=any_scalar_value. During verification it
10878 * will be assumed that bar() already verified successfully and call to bar()
10879 * from foo() will be checked for type match only. Later bar() will be verified
10880 * independently to check that it's safe for R1=any_scalar_value.
10881 */
10882static int do_check_subprogs(struct bpf_verifier_env *env)
10883{
10884 struct bpf_prog_aux *aux = env->prog->aux;
10885 int i, ret;
10886
10887 if (!aux->func_info)
10888 return 0;
10889
10890 for (i = 1; i < env->subprog_cnt; i++) {
10891 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
10892 continue;
10893 env->insn_idx = env->subprog_info[i].start;
10894 WARN_ON_ONCE(env->insn_idx == 0);
10895 ret = do_check_common(env, i);
10896 if (ret) {
10897 return ret;
10898 } else if (env->log.level & BPF_LOG_LEVEL) {
10899 verbose(env,
10900 "Func#%d is safe for any args that match its prototype\n",
10901 i);
10902 }
10903 }
10904 return 0;
10905}
10906
10907static int do_check_main(struct bpf_verifier_env *env)
10908{
10909 int ret;
10910
10911 env->insn_idx = 0;
10912 ret = do_check_common(env, 0);
10913 if (!ret)
10914 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
10915 return ret;
10916}
10917
10918
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010919static void print_verification_stats(struct bpf_verifier_env *env)
10920{
10921 int i;
10922
10923 if (env->log.level & BPF_LOG_STATS) {
10924 verbose(env, "verification time %lld usec\n",
10925 div_u64(env->verification_time, 1000));
10926 verbose(env, "stack depth ");
10927 for (i = 0; i < env->subprog_cnt; i++) {
10928 u32 depth = env->subprog_info[i].stack_depth;
10929
10930 verbose(env, "%d", depth);
10931 if (i + 1 < env->subprog_cnt)
10932 verbose(env, "+");
10933 }
10934 verbose(env, "\n");
10935 }
10936 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
10937 "total_states %d peak_states %d mark_read %d\n",
10938 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
10939 env->max_states_per_insn, env->total_states,
10940 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010941}
10942
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080010943static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
10944{
10945 const struct btf_type *t, *func_proto;
10946 const struct bpf_struct_ops *st_ops;
10947 const struct btf_member *member;
10948 struct bpf_prog *prog = env->prog;
10949 u32 btf_id, member_idx;
10950 const char *mname;
10951
10952 btf_id = prog->aux->attach_btf_id;
10953 st_ops = bpf_struct_ops_find(btf_id);
10954 if (!st_ops) {
10955 verbose(env, "attach_btf_id %u is not a supported struct\n",
10956 btf_id);
10957 return -ENOTSUPP;
10958 }
10959
10960 t = st_ops->type;
10961 member_idx = prog->expected_attach_type;
10962 if (member_idx >= btf_type_vlen(t)) {
10963 verbose(env, "attach to invalid member idx %u of struct %s\n",
10964 member_idx, st_ops->name);
10965 return -EINVAL;
10966 }
10967
10968 member = &btf_type_member(t)[member_idx];
10969 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
10970 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
10971 NULL);
10972 if (!func_proto) {
10973 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
10974 mname, member_idx, st_ops->name);
10975 return -EINVAL;
10976 }
10977
10978 if (st_ops->check_member) {
10979 int err = st_ops->check_member(t, member);
10980
10981 if (err) {
10982 verbose(env, "attach to unsupported member %s of struct %s\n",
10983 mname, st_ops->name);
10984 return err;
10985 }
10986 }
10987
10988 prog->aux->attach_func_proto = func_proto;
10989 prog->aux->attach_func_name = mname;
10990 env->ops = st_ops->verifier_ops;
10991
10992 return 0;
10993}
KP Singh6ba43b72020-03-04 20:18:50 +010010994#define SECURITY_PREFIX "security_"
10995
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070010996static int check_attach_modify_return(struct bpf_prog *prog, unsigned long addr)
KP Singh6ba43b72020-03-04 20:18:50 +010010997{
KP Singh69191752020-03-05 21:49:55 +010010998 if (within_error_injection_list(addr) ||
10999 !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
11000 sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010011001 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010011002
KP Singh6ba43b72020-03-04 20:18:50 +010011003 return -EINVAL;
11004}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011005
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011006/* non exhaustive list of sleepable bpf_lsm_*() functions */
11007BTF_SET_START(btf_sleepable_lsm_hooks)
11008#ifdef CONFIG_BPF_LSM
11009BTF_ID(func, bpf_lsm_file_mprotect)
11010BTF_ID(func, bpf_lsm_bprm_committed_creds)
Alexei Starovoitov29523c52020-08-31 09:31:32 -070011011#else
11012BTF_ID_UNUSED
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011013#endif
11014BTF_SET_END(btf_sleepable_lsm_hooks)
11015
11016static int check_sleepable_lsm_hook(u32 btf_id)
11017{
11018 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
11019}
11020
11021/* list of non-sleepable functions that are otherwise on
11022 * ALLOW_ERROR_INJECTION list
11023 */
11024BTF_SET_START(btf_non_sleepable_error_inject)
11025/* Three functions below can be called from sleepable and non-sleepable context.
11026 * Assume non-sleepable from bpf safety point of view.
11027 */
11028BTF_ID(func, __add_to_page_cache_locked)
11029BTF_ID(func, should_fail_alloc_page)
11030BTF_ID(func, should_failslab)
11031BTF_SET_END(btf_non_sleepable_error_inject)
11032
11033static int check_non_sleepable_error_inject(u32 btf_id)
11034{
11035 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11036}
11037
Martin KaFai Lau38207292019-10-24 17:18:11 -070011038static int check_attach_btf_id(struct bpf_verifier_env *env)
11039{
11040 struct bpf_prog *prog = env->prog;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011041 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011042 struct bpf_prog *tgt_prog = prog->aux->linked_prog;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011043 u32 btf_id = prog->aux->attach_btf_id;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011044 const char prefix[] = "btf_trace_";
Yonghong Song15d83c42020-05-09 10:59:00 -070011045 struct btf_func_model fmodel;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011046 int ret = 0, subprog = -1, i;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011047 struct bpf_trampoline *tr;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011048 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011049 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011050 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011051 struct btf *btf;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011052 long addr;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011053 u64 key;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011054
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011055 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
11056 prog->type != BPF_PROG_TYPE_LSM) {
11057 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11058 return -EINVAL;
11059 }
11060
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011061 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
11062 return check_struct_ops_btf_id(env);
11063
KP Singh9e4e01d2020-03-29 01:43:52 +010011064 if (prog->type != BPF_PROG_TYPE_TRACING &&
11065 prog->type != BPF_PROG_TYPE_LSM &&
11066 !prog_extension)
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011067 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011068
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011069 if (!btf_id) {
11070 verbose(env, "Tracing programs must provide btf_id\n");
11071 return -EINVAL;
11072 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011073 btf = bpf_prog_get_target_btf(prog);
11074 if (!btf) {
11075 verbose(env,
11076 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11077 return -EINVAL;
11078 }
11079 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011080 if (!t) {
11081 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
11082 return -EINVAL;
11083 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011084 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011085 if (!tname) {
11086 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
11087 return -EINVAL;
11088 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011089 if (tgt_prog) {
11090 struct bpf_prog_aux *aux = tgt_prog->aux;
11091
11092 for (i = 0; i < aux->func_info_cnt; i++)
11093 if (aux->func_info[i].type_id == btf_id) {
11094 subprog = i;
11095 break;
11096 }
11097 if (subprog == -1) {
11098 verbose(env, "Subprog %s doesn't exist\n", tname);
11099 return -EINVAL;
11100 }
11101 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011102 if (prog_extension) {
11103 if (conservative) {
11104 verbose(env,
11105 "Cannot replace static functions\n");
11106 return -EINVAL;
11107 }
11108 if (!prog->jit_requested) {
11109 verbose(env,
11110 "Extension programs should be JITed\n");
11111 return -EINVAL;
11112 }
11113 env->ops = bpf_verifier_ops[tgt_prog->type];
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020011114 prog->expected_attach_type = tgt_prog->expected_attach_type;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011115 }
11116 if (!tgt_prog->jited) {
11117 verbose(env, "Can attach to only JITed progs\n");
11118 return -EINVAL;
11119 }
11120 if (tgt_prog->type == prog->type) {
11121 /* Cannot fentry/fexit another fentry/fexit program.
11122 * Cannot attach program extension to another extension.
11123 * It's ok to attach fentry/fexit to extension program.
11124 */
11125 verbose(env, "Cannot recursively attach\n");
11126 return -EINVAL;
11127 }
11128 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
11129 prog_extension &&
11130 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
11131 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
11132 /* Program extensions can extend all program types
11133 * except fentry/fexit. The reason is the following.
11134 * The fentry/fexit programs are used for performance
11135 * analysis, stats and can be attached to any program
11136 * type except themselves. When extension program is
11137 * replacing XDP function it is necessary to allow
11138 * performance analysis of all functions. Both original
11139 * XDP program and its program extension. Hence
11140 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11141 * allowed. If extending of fentry/fexit was allowed it
11142 * would be possible to create long call chain
11143 * fentry->extension->fentry->extension beyond
11144 * reasonable stack size. Hence extending fentry is not
11145 * allowed.
11146 */
11147 verbose(env, "Cannot extend fentry/fexit\n");
11148 return -EINVAL;
11149 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011150 key = ((u64)aux->id) << 32 | btf_id;
11151 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011152 if (prog_extension) {
11153 verbose(env, "Cannot replace kernel functions\n");
11154 return -EINVAL;
11155 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011156 key = btf_id;
11157 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011158
11159 switch (prog->expected_attach_type) {
11160 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011161 if (tgt_prog) {
11162 verbose(env,
11163 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11164 return -EINVAL;
11165 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070011166 if (!btf_type_is_typedef(t)) {
11167 verbose(env, "attach_btf_id %u is not a typedef\n",
11168 btf_id);
11169 return -EINVAL;
11170 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011171 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Martin KaFai Lau38207292019-10-24 17:18:11 -070011172 verbose(env, "attach_btf_id %u points to wrong type name %s\n",
11173 btf_id, tname);
11174 return -EINVAL;
11175 }
11176 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011177 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011178 if (!btf_type_is_ptr(t))
11179 /* should never happen in valid vmlinux build */
11180 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011181 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011182 if (!btf_type_is_func_proto(t))
11183 /* should never happen in valid vmlinux build */
11184 return -EINVAL;
11185
11186 /* remember two read only pointers that are valid for
11187 * the life time of the kernel
11188 */
11189 prog->aux->attach_func_name = tname;
11190 prog->aux->attach_func_proto = t;
11191 prog->aux->attach_btf_trace = true;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070011192 return 0;
Yonghong Song15d83c42020-05-09 10:59:00 -070011193 case BPF_TRACE_ITER:
11194 if (!btf_type_is_func(t)) {
11195 verbose(env, "attach_btf_id %u is not a function\n",
11196 btf_id);
11197 return -EINVAL;
11198 }
11199 t = btf_type_by_id(btf, t->type);
11200 if (!btf_type_is_func_proto(t))
11201 return -EINVAL;
11202 prog->aux->attach_func_name = tname;
11203 prog->aux->attach_func_proto = t;
11204 if (!bpf_iter_prog_supported(prog))
11205 return -EINVAL;
11206 ret = btf_distill_func_proto(&env->log, btf, t,
11207 tname, &fmodel);
11208 return ret;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011209 default:
11210 if (!prog_extension)
11211 return -EINVAL;
11212 /* fallthrough */
KP Singhae240822020-03-04 20:18:49 +010011213 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010011214 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011215 case BPF_TRACE_FENTRY:
11216 case BPF_TRACE_FEXIT:
KP Singh9e4e01d2020-03-29 01:43:52 +010011217 prog->aux->attach_func_name = tname;
11218 if (prog->type == BPF_PROG_TYPE_LSM) {
11219 ret = bpf_lsm_verify_prog(&env->log, prog);
11220 if (ret < 0)
11221 return ret;
11222 }
11223
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011224 if (!btf_type_is_func(t)) {
11225 verbose(env, "attach_btf_id %u is not a function\n",
11226 btf_id);
11227 return -EINVAL;
11228 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011229 if (prog_extension &&
11230 btf_check_type_match(env, prog, btf, t))
11231 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011232 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011233 if (!btf_type_is_func_proto(t))
11234 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011235 tr = bpf_trampoline_lookup(key);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011236 if (!tr)
11237 return -ENOMEM;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011238 /* t is either vmlinux type or another program's type */
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011239 prog->aux->attach_func_proto = t;
11240 mutex_lock(&tr->mutex);
11241 if (tr->func.addr) {
11242 prog->aux->trampoline = tr;
11243 goto out;
11244 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011245 if (tgt_prog && conservative) {
11246 prog->aux->attach_func_proto = NULL;
11247 t = NULL;
11248 }
11249 ret = btf_distill_func_proto(&env->log, btf, t,
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011250 tname, &tr->func.model);
11251 if (ret < 0)
11252 goto out;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011253 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080011254 if (subprog == 0)
11255 addr = (long) tgt_prog->bpf_func;
11256 else
11257 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080011258 } else {
11259 addr = kallsyms_lookup_name(tname);
11260 if (!addr) {
11261 verbose(env,
11262 "The address of function %s cannot be found\n",
11263 tname);
11264 ret = -ENOENT;
11265 goto out;
11266 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011267 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011268
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011269 if (prog->aux->sleepable) {
11270 ret = -EINVAL;
11271 switch (prog->type) {
11272 case BPF_PROG_TYPE_TRACING:
11273 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11274 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11275 */
11276 if (!check_non_sleepable_error_inject(btf_id) &&
11277 within_error_injection_list(addr))
11278 ret = 0;
11279 break;
11280 case BPF_PROG_TYPE_LSM:
11281 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11282 * Only some of them are sleepable.
11283 */
11284 if (check_sleepable_lsm_hook(btf_id))
11285 ret = 0;
11286 break;
11287 default:
11288 break;
11289 }
11290 if (ret)
11291 verbose(env, "%s is not sleepable\n",
11292 prog->aux->attach_func_name);
11293 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011294 ret = check_attach_modify_return(prog, addr);
11295 if (ret)
11296 verbose(env, "%s() is not modifiable\n",
11297 prog->aux->attach_func_name);
11298 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070011299 if (ret)
11300 goto out;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080011301 tr->func.addr = (void *)addr;
11302 prog->aux->trampoline = tr;
11303out:
11304 mutex_unlock(&tr->mutex);
11305 if (ret)
11306 bpf_trampoline_put(tr);
11307 return ret;
Martin KaFai Lau38207292019-10-24 17:18:11 -070011308 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070011309}
11310
Yonghong Song838e9692018-11-19 15:29:11 -080011311int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
11312 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011313{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011314 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011315 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070011316 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011317 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011318 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011319
Arnd Bergmanneba0c922017-11-02 12:05:52 +010011320 /* no program is valid */
11321 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
11322 return -EINVAL;
11323
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011324 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011325 * allocate/free it every time bpf_check() is called
11326 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011327 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011328 if (!env)
11329 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011330 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011331
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011332 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070011333 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011334 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011335 ret = -ENOMEM;
11336 if (!env->insn_aux_data)
11337 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080011338 for (i = 0; i < len; i++)
11339 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011340 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070011341 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011342 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011343
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011344 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
11345 mutex_lock(&bpf_verifier_lock);
11346 if (!btf_vmlinux)
11347 btf_vmlinux = btf_parse_vmlinux();
11348 mutex_unlock(&bpf_verifier_lock);
11349 }
11350
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011351 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070011352 if (!is_priv)
11353 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011354
11355 if (attr->log_level || attr->log_buf || attr->log_size) {
11356 /* user requested verbose verifier output
11357 * and supplied buffer to store the verification trace
11358 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070011359 log->level = attr->log_level;
11360 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
11361 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011362
11363 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070011364 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070011365 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011366 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011367 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011368 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020011369
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011370 if (IS_ERR(btf_vmlinux)) {
11371 /* Either gcc or pahole or kernel are broken. */
11372 verbose(env, "in-kernel BTF is malformed\n");
11373 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070011374 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070011375 }
11376
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020011377 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
11378 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070011379 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080011380 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
11381 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011382
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011383 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070011384 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011385 env->bypass_spec_v1 = bpf_bypass_spec_v1();
11386 env->bypass_spec_v4 = bpf_bypass_spec_v4();
11387 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011388
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070011389 if (is_priv)
11390 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
11391
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011392 ret = replace_map_fd_with_map_ptr(env);
11393 if (ret < 0)
11394 goto skip_full_check;
11395
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070011396 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Quentin Monneta40a2632018-11-09 13:03:31 +000011397 ret = bpf_prog_offload_verifier_prep(env->prog);
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070011398 if (ret)
11399 goto skip_full_check;
11400 }
11401
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011402 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011403 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011404 GFP_USER);
11405 ret = -ENOMEM;
11406 if (!env->explored_states)
11407 goto skip_full_check;
11408
Martin KaFai Laud9762e82018-12-13 10:41:48 -080011409 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070011410 if (ret < 0)
11411 goto skip_full_check;
11412
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011413 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080011414 if (ret < 0)
11415 goto skip_full_check;
11416
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011417 ret = check_attach_btf_id(env);
11418 if (ret)
11419 goto skip_full_check;
11420
Martin KaFai Laud9762e82018-12-13 10:41:48 -080011421 ret = check_cfg(env);
11422 if (ret < 0)
11423 goto skip_full_check;
11424
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011425 ret = do_check_subprogs(env);
11426 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011427
Quentin Monnetc941ce92018-10-07 12:56:47 +010011428 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11429 ret = bpf_prog_offload_finalize(env);
11430
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011431skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011432 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011433
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011434 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080011435 ret = check_max_stack_depth(env);
11436
Jakub Kicinski9b38c402018-12-19 22:13:06 -080011437 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011438 if (is_priv) {
11439 if (ret == 0)
11440 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080011441 if (ret == 0)
11442 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080011443 if (ret == 0)
11444 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080011445 } else {
11446 if (ret == 0)
11447 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011448 }
11449
Jakub Kicinski9b38c402018-12-19 22:13:06 -080011450 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011451 /* program is valid, convert *(u32*)(ctx + off) accesses */
11452 ret = convert_ctx_accesses(env);
11453
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011454 if (ret == 0)
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011455 ret = fixup_bpf_calls(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011456
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011457 /* do 32-bit optimization after insn patching has done so those patched
11458 * insns could be handled correctly.
11459 */
Jiong Wangd6c23082019-05-24 23:25:18 +010011460 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11461 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11462 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11463 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011464 }
11465
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011466 if (ret == 0)
11467 ret = fixup_call_args(env);
11468
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011469 env->verification_time = ktime_get_ns() - start_time;
11470 print_verification_stats(env);
11471
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011472 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011473 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011474 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011475 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011476 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011477 }
11478
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011479 if (ret == 0 && env->used_map_cnt) {
11480 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011481 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11482 sizeof(env->used_maps[0]),
11483 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011484
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011485 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011486 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011487 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011488 }
11489
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011490 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011491 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011492 env->prog->aux->used_map_cnt = env->used_map_cnt;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011493
11494 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11495 * bpf_ld_imm64 instructions
11496 */
11497 convert_pseudo_ld_imm64(env);
11498 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070011499
Yonghong Songba64e7d2018-11-24 23:20:44 -080011500 if (ret == 0)
11501 adjust_btf_func(env);
11502
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070011503err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011504 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011505 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070011506 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011507 */
11508 release_maps(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020011509
11510 /* extension progs temporarily inherit the attach_type of their targets
11511 for verification purposes, so set it back to zero before returning
11512 */
11513 if (env->prog->type == BPF_PROG_TYPE_EXT)
11514 env->prog->expected_attach_type = 0;
11515
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011516 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011517err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070011518 if (!is_priv)
11519 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011520 vfree(env->insn_aux_data);
11521err_free_env:
11522 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070011523 return ret;
11524}