blob: dda3b94d9661935da79de648d90e9f52eefff852 [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 Starovoitov51580e72014-09-26 00:17:02 -070024
Jakub Kicinskif4ac7e02017-10-09 10:30:12 -070025#include "disasm.h"
26
Jakub Kicinski00176a32017-10-16 16:40:54 -070027static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
Alexei Starovoitov91cc1a92019-11-14 10:57:15 -080028#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
Jakub Kicinski00176a32017-10-16 16:40:54 -070029 [_id] = & _name ## _verifier_ops,
30#define BPF_MAP_TYPE(_id, _ops)
31#include <linux/bpf_types.h>
32#undef BPF_PROG_TYPE
33#undef BPF_MAP_TYPE
34};
35
Alexei Starovoitov51580e72014-09-26 00:17:02 -070036/* bpf_check() is a static code analyzer that walks eBPF program
37 * instruction by instruction and updates register/stack state.
38 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
39 *
40 * The first pass is depth-first-search to check that the program is a DAG.
41 * It rejects the following programs:
42 * - larger than BPF_MAXINSNS insns
43 * - if loop is present (detected via back-edge)
44 * - unreachable insns exist (shouldn't be a forest. program = one function)
45 * - out of bounds or malformed jumps
46 * The second pass is all possible path descent from the 1st insn.
47 * Since it's analyzing all pathes through the program, the length of the
Gary Lineba38a92017-03-01 16:25:51 +080048 * analysis is limited to 64k insn, which may be hit even if total number of
Alexei Starovoitov51580e72014-09-26 00:17:02 -070049 * insn is less then 4K, but there are too many branches that change stack/regs.
50 * Number of 'branches to be analyzed' is limited to 1k
51 *
52 * On entry to each instruction, each register has a type, and the instruction
53 * changes the types of the registers depending on instruction semantics.
54 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
55 * copied to R1.
56 *
57 * All registers are 64-bit.
58 * R0 - return register
59 * R1-R5 argument passing registers
60 * R6-R9 callee saved registers
61 * R10 - frame pointer read-only
62 *
63 * At the start of BPF program the register R1 contains a pointer to bpf_context
64 * and has type PTR_TO_CTX.
65 *
66 * Verifier tracks arithmetic operations on pointers in case:
67 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
68 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
69 * 1st insn copies R10 (which has FRAME_PTR) type into R1
70 * and 2nd arithmetic instruction is pattern matched to recognize
71 * that it wants to construct a pointer to some element within stack.
72 * So after 2nd insn, the register R1 has type PTR_TO_STACK
73 * (and -20 constant is saved for further stack bounds checking).
74 * Meaning that this reg is a pointer to stack plus known immediate constant.
75 *
Edward Creef1174f72017-08-07 15:26:19 +010076 * Most of the time the registers have SCALAR_VALUE type, which
Alexei Starovoitov51580e72014-09-26 00:17:02 -070077 * means the register has some value, but it's not a valid pointer.
Edward Creef1174f72017-08-07 15:26:19 +010078 * (like pointer plus pointer becomes SCALAR_VALUE type)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070079 *
80 * When verifier sees load or store instructions the type of base register
Joe Stringerc64b7982018-10-02 13:35:33 -070081 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
82 * four pointer types recognized by check_mem_access() function.
Alexei Starovoitov51580e72014-09-26 00:17:02 -070083 *
84 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
85 * and the range of [ptr, ptr + map's value_size) is accessible.
86 *
87 * registers used to pass values to function calls are checked against
88 * function argument constraints.
89 *
90 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
91 * It means that the register type passed to this function must be
92 * PTR_TO_STACK and it will be used inside the function as
93 * 'pointer to map element key'
94 *
95 * For example the argument constraints for bpf_map_lookup_elem():
96 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
97 * .arg1_type = ARG_CONST_MAP_PTR,
98 * .arg2_type = ARG_PTR_TO_MAP_KEY,
99 *
100 * ret_type says that this function returns 'pointer to map elem value or null'
101 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
102 * 2nd argument should be a pointer to stack, which will be used inside
103 * the helper function as a pointer to map element key.
104 *
105 * On the kernel side the helper function looks like:
106 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
107 * {
108 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
109 * void *key = (void *) (unsigned long) r2;
110 * void *value;
111 *
112 * here kernel can access 'key' and 'map' pointers safely, knowing that
113 * [key, key + map->key_size) bytes are valid and were initialized on
114 * the stack of eBPF program.
115 * }
116 *
117 * Corresponding eBPF program may look like:
118 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
119 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
120 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
121 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
122 * here verifier looks at prototype of map_lookup_elem() and sees:
123 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
124 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
125 *
126 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
127 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
128 * and were initialized prior to this call.
129 * If it's ok, then verifier allows this BPF_CALL insn and looks at
130 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
131 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
132 * returns ether pointer to map value or NULL.
133 *
134 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
135 * insn, the register holding that pointer in the true branch changes state to
136 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
137 * branch. See check_cond_jmp_op().
138 *
139 * After the call R0 is set to return type of the function and registers R1-R5
140 * are set to NOT_INIT to indicate that they are no longer readable.
Joe Stringerfd978bf72018-10-02 13:35:35 -0700141 *
142 * The following reference types represent a potential reference to a kernel
143 * resource which, after first being allocated, must be checked and freed by
144 * the BPF program:
145 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
146 *
147 * When the verifier sees a helper call return a reference type, it allocates a
148 * pointer id for the reference and stores it in the current function state.
149 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
150 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
151 * passes through a NULL-check conditional. For the branch wherein the state is
152 * changed to CONST_IMM, the verifier releases the reference.
Joe Stringer6acc9b42018-10-02 13:35:36 -0700153 *
154 * For each helper function that allocates a reference, such as
155 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
156 * bpf_sk_release(). When a reference type passes into the release function,
157 * the verifier also releases the reference. If any unchecked or unreleased
158 * reference remains at the end of the program, the verifier rejects it.
Alexei Starovoitov51580e72014-09-26 00:17:02 -0700159 */
160
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700161/* verifier_state + insn_idx are pushed to stack when branch is encountered */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100162struct bpf_verifier_stack_elem {
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700163 /* verifer state is 'st'
164 * before processing instruction 'insn_idx'
165 * and after processing instruction 'prev_insn_idx'
166 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100167 struct bpf_verifier_state st;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700168 int insn_idx;
169 int prev_insn_idx;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100170 struct bpf_verifier_stack_elem *next;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700171};
172
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700173#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
Alexei Starovoitovceefbc92018-12-03 22:46:06 -0800174#define BPF_COMPLEXITY_LIMIT_STATES 64
Daniel Borkmann07016152016-04-05 22:33:17 +0200175
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100176#define BPF_MAP_KEY_POISON (1ULL << 63)
177#define BPF_MAP_KEY_SEEN (1ULL << 62)
178
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200179#define BPF_MAP_PTR_UNPRIV 1UL
180#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
181 POISON_POINTER_DELTA))
182#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
183
184static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
185{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100186 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200187}
188
189static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
190{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100191 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200192}
193
194static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
195 const struct bpf_map *map, bool unpriv)
196{
197 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
198 unpriv |= bpf_map_ptr_unpriv(aux);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100199 aux->map_ptr_state = (unsigned long)map |
200 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
201}
202
203static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
204{
205 return aux->map_key_state & BPF_MAP_KEY_POISON;
206}
207
208static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
209{
210 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
211}
212
213static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
214{
215 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
216}
217
218static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
219{
220 bool poisoned = bpf_map_key_poisoned(aux);
221
222 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
223 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200224}
Martin KaFai Laufad73a12017-03-22 10:00:32 -0700225
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200226struct bpf_call_arg_meta {
227 struct bpf_map *map_ptr;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200228 bool raw_mode;
Daniel Borkmann36bbef52016-09-20 00:26:13 +0200229 bool pkt_access;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200230 int regno;
231 int access_size;
John Fastabend10060502020-03-30 14:36:19 -0700232 u64 msize_max_value;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700233 int ref_obj_id;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800234 int func_id;
Alexei Starovoitova7658e12019-10-15 20:25:04 -0700235 u32 btf_id;
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200236};
237
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700238struct btf *btf_vmlinux;
239
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700240static DEFINE_MUTEX(bpf_verifier_lock);
241
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800242static const struct bpf_line_info *
243find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
244{
245 const struct bpf_line_info *linfo;
246 const struct bpf_prog *prog;
247 u32 i, nr_linfo;
248
249 prog = env->prog;
250 nr_linfo = prog->aux->nr_linfo;
251
252 if (!nr_linfo || insn_off >= prog->len)
253 return NULL;
254
255 linfo = prog->aux->linfo;
256 for (i = 1; i < nr_linfo; i++)
257 if (insn_off < linfo[i].insn_off)
258 break;
259
260 return &linfo[i - 1];
261}
262
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700263void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
264 va_list args)
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700265{
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700266 unsigned int n;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700267
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700268 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700269
270 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
271 "verifier log line truncated - local buffer too short\n");
272
273 n = min(log->len_total - log->len_used - 1, n);
274 log->kbuf[n] = '\0';
275
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700276 if (log->level == BPF_LOG_KERNEL) {
277 pr_err("BPF:%s\n", log->kbuf);
278 return;
279 }
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700280 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
281 log->len_used += n;
282 else
283 log->ubuf = NULL;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700284}
Jiri Olsaabe08842018-03-23 11:41:28 +0100285
286/* log_level controls verbosity level of eBPF verifier.
287 * bpf_verifier_log_write() is used to dump the verification trace to the log,
288 * so the user can figure out what's wrong with the program
Quentin Monnet430e68d2018-01-10 12:26:06 +0000289 */
Jiri Olsaabe08842018-03-23 11:41:28 +0100290__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
291 const char *fmt, ...)
292{
293 va_list args;
294
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700295 if (!bpf_verifier_log_needed(&env->log))
296 return;
297
Jiri Olsaabe08842018-03-23 11:41:28 +0100298 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700299 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100300 va_end(args);
301}
302EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
303
304__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
305{
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700306 struct bpf_verifier_env *env = private_data;
Jiri Olsaabe08842018-03-23 11:41:28 +0100307 va_list args;
308
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700309 if (!bpf_verifier_log_needed(&env->log))
310 return;
311
Jiri Olsaabe08842018-03-23 11:41:28 +0100312 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700313 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100314 va_end(args);
315}
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700316
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700317__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
318 const char *fmt, ...)
319{
320 va_list args;
321
322 if (!bpf_verifier_log_needed(log))
323 return;
324
325 va_start(args, fmt);
326 bpf_verifier_vlog(log, fmt, args);
327 va_end(args);
328}
329
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800330static const char *ltrim(const char *s)
331{
332 while (isspace(*s))
333 s++;
334
335 return s;
336}
337
338__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
339 u32 insn_off,
340 const char *prefix_fmt, ...)
341{
342 const struct bpf_line_info *linfo;
343
344 if (!bpf_verifier_log_needed(&env->log))
345 return;
346
347 linfo = find_linfo(env, insn_off);
348 if (!linfo || linfo == env->prev_linfo)
349 return;
350
351 if (prefix_fmt) {
352 va_list args;
353
354 va_start(args, prefix_fmt);
355 bpf_verifier_vlog(&env->log, prefix_fmt, args);
356 va_end(args);
357 }
358
359 verbose(env, "%s\n",
360 ltrim(btf_name_by_offset(env->prog->aux->btf,
361 linfo->line_off)));
362
363 env->prev_linfo = linfo;
364}
365
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200366static bool type_is_pkt_pointer(enum bpf_reg_type type)
367{
368 return type == PTR_TO_PACKET ||
369 type == PTR_TO_PACKET_META;
370}
371
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800372static bool type_is_sk_pointer(enum bpf_reg_type type)
373{
374 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800375 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700376 type == PTR_TO_TCP_SOCK ||
377 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800378}
379
Joe Stringer840b9612018-10-02 13:35:32 -0700380static bool reg_type_may_be_null(enum bpf_reg_type type)
381{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700382 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800383 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800384 type == PTR_TO_SOCK_COMMON_OR_NULL ||
385 type == PTR_TO_TCP_SOCK_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700386}
387
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800388static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
389{
390 return reg->type == PTR_TO_MAP_VALUE &&
391 map_value_has_spin_lock(reg->map_ptr);
392}
393
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700394static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
395{
396 return type == PTR_TO_SOCKET ||
397 type == PTR_TO_SOCKET_OR_NULL ||
398 type == PTR_TO_TCP_SOCK ||
399 type == PTR_TO_TCP_SOCK_OR_NULL;
400}
401
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700402static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700403{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700404 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700405}
406
407/* Determine whether the function releases some resources allocated by another
408 * function call. The first reference type argument will be assumed to be
409 * released by release_reference().
410 */
411static bool is_release_function(enum bpf_func_id func_id)
412{
Joe Stringer6acc9b42018-10-02 13:35:36 -0700413 return func_id == BPF_FUNC_sk_release;
Joe Stringer840b9612018-10-02 13:35:32 -0700414}
415
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800416static bool is_acquire_function(enum bpf_func_id func_id)
417{
418 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800419 func_id == BPF_FUNC_sk_lookup_udp ||
420 func_id == BPF_FUNC_skc_lookup_tcp;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800421}
422
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700423static bool is_ptr_cast_function(enum bpf_func_id func_id)
424{
425 return func_id == BPF_FUNC_tcp_sock ||
426 func_id == BPF_FUNC_sk_fullsock;
427}
428
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700429/* string representation of 'enum bpf_reg_type' */
430static const char * const reg_type_str[] = {
431 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100432 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700433 [PTR_TO_CTX] = "ctx",
434 [CONST_PTR_TO_MAP] = "map_ptr",
435 [PTR_TO_MAP_VALUE] = "map_value",
436 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700437 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700438 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200439 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700440 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700441 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700442 [PTR_TO_SOCKET] = "sock",
443 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800444 [PTR_TO_SOCK_COMMON] = "sock_common",
445 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800446 [PTR_TO_TCP_SOCK] = "tcp_sock",
447 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700448 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700449 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700450 [PTR_TO_BTF_ID] = "ptr_",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700451};
452
Edward Cree8efea212018-08-22 20:02:44 +0100453static char slot_type_char[] = {
454 [STACK_INVALID] = '?',
455 [STACK_SPILL] = 'r',
456 [STACK_MISC] = 'm',
457 [STACK_ZERO] = '0',
458};
459
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800460static void print_liveness(struct bpf_verifier_env *env,
461 enum bpf_reg_liveness live)
462{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800463 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800464 verbose(env, "_");
465 if (live & REG_LIVE_READ)
466 verbose(env, "r");
467 if (live & REG_LIVE_WRITTEN)
468 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800469 if (live & REG_LIVE_DONE)
470 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800471}
472
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800473static struct bpf_func_state *func(struct bpf_verifier_env *env,
474 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700475{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800476 struct bpf_verifier_state *cur = env->cur_state;
477
478 return cur->frame[reg->frameno];
479}
480
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700481const char *kernel_type_name(u32 id)
482{
483 return btf_name_by_offset(btf_vmlinux,
484 btf_type_by_id(btf_vmlinux, id)->name_off);
485}
486
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800487static void print_verifier_state(struct bpf_verifier_env *env,
488 const struct bpf_func_state *state)
489{
490 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700491 enum bpf_reg_type t;
492 int i;
493
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800494 if (state->frameno)
495 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700496 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700497 reg = &state->regs[i];
498 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700499 if (t == NOT_INIT)
500 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800501 verbose(env, " R%d", i);
502 print_liveness(env, reg->live);
503 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700504 if (t == SCALAR_VALUE && reg->precise)
505 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100506 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
507 tnum_is_const(reg->var_off)) {
508 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700509 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100510 } else {
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700511 if (t == PTR_TO_BTF_ID)
512 verbose(env, "%s", kernel_type_name(reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700513 verbose(env, "(id=%d", reg->id);
514 if (reg_type_may_be_refcounted_or_null(t))
515 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100516 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700517 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200518 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700519 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100520 else if (t == CONST_PTR_TO_MAP ||
521 t == PTR_TO_MAP_VALUE ||
522 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700523 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100524 reg->map_ptr->key_size,
525 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100526 if (tnum_is_const(reg->var_off)) {
527 /* Typically an immediate SCALAR_VALUE, but
528 * could be a pointer whose offset is too big
529 * for reg->off
530 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700531 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100532 } else {
533 if (reg->smin_value != reg->umin_value &&
534 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700535 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100536 (long long)reg->smin_value);
537 if (reg->smax_value != reg->umax_value &&
538 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700539 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100540 (long long)reg->smax_value);
541 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700542 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100543 (unsigned long long)reg->umin_value);
544 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700545 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100546 (unsigned long long)reg->umax_value);
547 if (!tnum_is_unknown(reg->var_off)) {
548 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100549
Edward Cree7d1238f2017-08-07 15:26:56 +0100550 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700551 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100552 }
Edward Creef1174f72017-08-07 15:26:19 +0100553 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700554 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100555 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700556 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700557 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100558 char types_buf[BPF_REG_SIZE + 1];
559 bool valid = false;
560 int j;
561
562 for (j = 0; j < BPF_REG_SIZE; j++) {
563 if (state->stack[i].slot_type[j] != STACK_INVALID)
564 valid = true;
565 types_buf[j] = slot_type_char[
566 state->stack[i].slot_type[j]];
567 }
568 types_buf[BPF_REG_SIZE] = 0;
569 if (!valid)
570 continue;
571 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
572 print_liveness(env, state->stack[i].spilled_ptr.live);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700573 if (state->stack[i].slot_type[0] == STACK_SPILL) {
574 reg = &state->stack[i].spilled_ptr;
575 t = reg->type;
576 verbose(env, "=%s", reg_type_str[t]);
577 if (t == SCALAR_VALUE && reg->precise)
578 verbose(env, "P");
579 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
580 verbose(env, "%lld", reg->var_off.value + reg->off);
581 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100582 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700583 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700584 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700585 if (state->acquired_refs && state->refs[0].id) {
586 verbose(env, " refs=%d", state->refs[0].id);
587 for (i = 1; i < state->acquired_refs; i++)
588 if (state->refs[i].id)
589 verbose(env, ",%d", state->refs[i].id);
590 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700591 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700592}
593
Joe Stringer84dbf352018-10-02 13:35:34 -0700594#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
595static int copy_##NAME##_state(struct bpf_func_state *dst, \
596 const struct bpf_func_state *src) \
597{ \
598 if (!src->FIELD) \
599 return 0; \
600 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
601 /* internal bug, make state invalid to reject the program */ \
602 memset(dst, 0, sizeof(*dst)); \
603 return -EFAULT; \
604 } \
605 memcpy(dst->FIELD, src->FIELD, \
606 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
607 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700608}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700609/* copy_reference_state() */
610COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700611/* copy_stack_state() */
612COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
613#undef COPY_STATE_FN
614
615#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
616static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
617 bool copy_old) \
618{ \
619 u32 old_size = state->COUNT; \
620 struct bpf_##NAME##_state *new_##FIELD; \
621 int slot = size / SIZE; \
622 \
623 if (size <= old_size || !size) { \
624 if (copy_old) \
625 return 0; \
626 state->COUNT = slot * SIZE; \
627 if (!size && old_size) { \
628 kfree(state->FIELD); \
629 state->FIELD = NULL; \
630 } \
631 return 0; \
632 } \
633 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
634 GFP_KERNEL); \
635 if (!new_##FIELD) \
636 return -ENOMEM; \
637 if (copy_old) { \
638 if (state->FIELD) \
639 memcpy(new_##FIELD, state->FIELD, \
640 sizeof(*new_##FIELD) * (old_size / SIZE)); \
641 memset(new_##FIELD + old_size / SIZE, 0, \
642 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
643 } \
644 state->COUNT = slot * SIZE; \
645 kfree(state->FIELD); \
646 state->FIELD = new_##FIELD; \
647 return 0; \
648}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700649/* realloc_reference_state() */
650REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700651/* realloc_stack_state() */
652REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
653#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700654
655/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
656 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800657 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700658 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
659 * which realloc_stack_state() copies over. It points to previous
660 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700661 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700662static int realloc_func_state(struct bpf_func_state *state, int stack_size,
663 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700664{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700665 int err = realloc_reference_state(state, refs_size, copy_old);
666 if (err)
667 return err;
668 return realloc_stack_state(state, stack_size, copy_old);
669}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700670
Joe Stringerfd978bf72018-10-02 13:35:35 -0700671/* Acquire a pointer id from the env and update the state->refs to include
672 * this new pointer reference.
673 * On success, returns a valid pointer id to associate with the register
674 * On failure, returns a negative errno.
675 */
676static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
677{
678 struct bpf_func_state *state = cur_func(env);
679 int new_ofs = state->acquired_refs;
680 int id, err;
681
682 err = realloc_reference_state(state, state->acquired_refs + 1, true);
683 if (err)
684 return err;
685 id = ++env->id_gen;
686 state->refs[new_ofs].id = id;
687 state->refs[new_ofs].insn_idx = insn_idx;
688
689 return id;
690}
691
692/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800693static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700694{
695 int i, last_idx;
696
Joe Stringerfd978bf72018-10-02 13:35:35 -0700697 last_idx = state->acquired_refs - 1;
698 for (i = 0; i < state->acquired_refs; i++) {
699 if (state->refs[i].id == ptr_id) {
700 if (last_idx && i != last_idx)
701 memcpy(&state->refs[i], &state->refs[last_idx],
702 sizeof(*state->refs));
703 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
704 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700705 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700706 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700707 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800708 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700709}
710
711static int transfer_reference_state(struct bpf_func_state *dst,
712 struct bpf_func_state *src)
713{
714 int err = realloc_reference_state(dst, src->acquired_refs, false);
715 if (err)
716 return err;
717 err = copy_reference_state(dst, src);
718 if (err)
719 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700720 return 0;
721}
722
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800723static void free_func_state(struct bpf_func_state *state)
724{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800725 if (!state)
726 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700727 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800728 kfree(state->stack);
729 kfree(state);
730}
731
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700732static void clear_jmp_history(struct bpf_verifier_state *state)
733{
734 kfree(state->jmp_history);
735 state->jmp_history = NULL;
736 state->jmp_history_cnt = 0;
737}
738
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700739static void free_verifier_state(struct bpf_verifier_state *state,
740 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700741{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800742 int i;
743
744 for (i = 0; i <= state->curframe; i++) {
745 free_func_state(state->frame[i]);
746 state->frame[i] = NULL;
747 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700748 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700749 if (free_self)
750 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700751}
752
753/* copy verifier state from src to dst growing dst stack space
754 * when necessary to accommodate larger src stack
755 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800756static int copy_func_state(struct bpf_func_state *dst,
757 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700758{
759 int err;
760
Joe Stringerfd978bf72018-10-02 13:35:35 -0700761 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
762 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700763 if (err)
764 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700765 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
766 err = copy_reference_state(dst, src);
767 if (err)
768 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700769 return copy_stack_state(dst, src);
770}
771
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800772static int copy_verifier_state(struct bpf_verifier_state *dst_state,
773 const struct bpf_verifier_state *src)
774{
775 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700776 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800777 int i, err;
778
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700779 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
780 kfree(dst_state->jmp_history);
781 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
782 if (!dst_state->jmp_history)
783 return -ENOMEM;
784 }
785 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
786 dst_state->jmp_history_cnt = src->jmp_history_cnt;
787
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800788 /* if dst has more stack frames then src frame, free them */
789 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
790 free_func_state(dst_state->frame[i]);
791 dst_state->frame[i] = NULL;
792 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100793 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800794 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800795 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700796 dst_state->branches = src->branches;
797 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700798 dst_state->first_insn_idx = src->first_insn_idx;
799 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800800 for (i = 0; i <= src->curframe; i++) {
801 dst = dst_state->frame[i];
802 if (!dst) {
803 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
804 if (!dst)
805 return -ENOMEM;
806 dst_state->frame[i] = dst;
807 }
808 err = copy_func_state(dst, src->frame[i]);
809 if (err)
810 return err;
811 }
812 return 0;
813}
814
Alexei Starovoitov25897262019-06-15 12:12:20 -0700815static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
816{
817 while (st) {
818 u32 br = --st->branches;
819
820 /* WARN_ON(br > 1) technically makes sense here,
821 * but see comment in push_stack(), hence:
822 */
823 WARN_ONCE((int)br < 0,
824 "BUG update_branch_counts:branches_to_explore=%d\n",
825 br);
826 if (br)
827 break;
828 st = st->parent;
829 }
830}
831
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700832static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
833 int *insn_idx)
834{
835 struct bpf_verifier_state *cur = env->cur_state;
836 struct bpf_verifier_stack_elem *elem, *head = env->head;
837 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700838
839 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700840 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700841
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700842 if (cur) {
843 err = copy_verifier_state(cur, &head->st);
844 if (err)
845 return err;
846 }
847 if (insn_idx)
848 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700849 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700850 *prev_insn_idx = head->prev_insn_idx;
851 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700852 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700853 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700854 env->head = elem;
855 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700856 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700857}
858
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100859static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100860 int insn_idx, int prev_insn_idx,
861 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700862{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700863 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100864 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700865 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700866
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700867 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700868 if (!elem)
869 goto err;
870
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700871 elem->insn_idx = insn_idx;
872 elem->prev_insn_idx = prev_insn_idx;
873 elem->next = env->head;
874 env->head = elem;
875 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700876 err = copy_verifier_state(&elem->st, cur);
877 if (err)
878 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100879 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700880 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
881 verbose(env, "The sequence of %d jumps is too complex.\n",
882 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700883 goto err;
884 }
Alexei Starovoitov25897262019-06-15 12:12:20 -0700885 if (elem->st.parent) {
886 ++elem->st.parent->branches;
887 /* WARN_ON(branches > 2) technically makes sense here,
888 * but
889 * 1. speculative states will bump 'branches' for non-branch
890 * instructions
891 * 2. is_state_visited() heuristics may decide not to create
892 * a new state for a sequence of branches and all such current
893 * and cloned states will be pointing to a single parent state
894 * which might have large 'branches' count.
895 */
896 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700897 return &elem->st;
898err:
Alexei Starovoitov58963512018-01-08 07:51:17 -0800899 free_verifier_state(env->cur_state, true);
900 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700901 /* pop all elements and return */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700902 while (!pop_stack(env, NULL, NULL));
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700903 return NULL;
904}
905
906#define CALLER_SAVED_REGS 6
907static const int caller_saved[CALLER_SAVED_REGS] = {
908 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
909};
910
Daniel Borkmannf54c7892019-12-22 23:37:40 +0100911static void __mark_reg_not_init(const struct bpf_verifier_env *env,
912 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +0100913
Edward Creeb03c9f92017-08-07 15:26:36 +0100914/* Mark the unknown part of a register (variable offset or scalar value) as
915 * known to have the value @imm.
916 */
917static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
918{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -0700919 /* Clear id, off, and union(map_ptr, range) */
920 memset(((u8 *)reg) + sizeof(reg->type), 0,
921 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
Edward Creeb03c9f92017-08-07 15:26:36 +0100922 reg->var_off = tnum_const(imm);
923 reg->smin_value = (s64)imm;
924 reg->smax_value = (s64)imm;
925 reg->umin_value = imm;
926 reg->umax_value = imm;
927}
928
Edward Creef1174f72017-08-07 15:26:19 +0100929/* Mark the 'variable offset' part of a register as zero. This should be
930 * used only on registers holding a pointer type.
931 */
932static void __mark_reg_known_zero(struct bpf_reg_state *reg)
933{
Edward Creeb03c9f92017-08-07 15:26:36 +0100934 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +0100935}
936
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -0800937static void __mark_reg_const_zero(struct bpf_reg_state *reg)
938{
939 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -0800940 reg->type = SCALAR_VALUE;
941}
942
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700943static void mark_reg_known_zero(struct bpf_verifier_env *env,
944 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +0100945{
946 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700947 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +0100948 /* Something bad happened, let's kill all regs */
949 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +0100950 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +0100951 return;
952 }
953 __mark_reg_known_zero(regs + regno);
954}
955
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200956static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
957{
958 return type_is_pkt_pointer(reg->type);
959}
960
961static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
962{
963 return reg_is_pkt_pointer(reg) ||
964 reg->type == PTR_TO_PACKET_END;
965}
966
967/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
968static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
969 enum bpf_reg_type which)
970{
971 /* The register can already have a range from prior markings.
972 * This is fine as long as it hasn't been advanced from its
973 * origin.
974 */
975 return reg->type == which &&
976 reg->id == 0 &&
977 reg->off == 0 &&
978 tnum_equals_const(reg->var_off, 0);
979}
980
Edward Creeb03c9f92017-08-07 15:26:36 +0100981/* Attempts to improve min/max values based on var_off information */
982static void __update_reg_bounds(struct bpf_reg_state *reg)
983{
984 /* min signed is max(sign bit) | min(other bits) */
985 reg->smin_value = max_t(s64, reg->smin_value,
986 reg->var_off.value | (reg->var_off.mask & S64_MIN));
987 /* max signed is min(sign bit) | max(other bits) */
988 reg->smax_value = min_t(s64, reg->smax_value,
989 reg->var_off.value | (reg->var_off.mask & S64_MAX));
990 reg->umin_value = max(reg->umin_value, reg->var_off.value);
991 reg->umax_value = min(reg->umax_value,
992 reg->var_off.value | reg->var_off.mask);
993}
994
995/* Uses signed min/max values to inform unsigned, and vice-versa */
996static void __reg_deduce_bounds(struct bpf_reg_state *reg)
997{
998 /* Learn sign from signed bounds.
999 * If we cannot cross the sign boundary, then signed and unsigned bounds
1000 * are the same, so combine. This works even in the negative case, e.g.
1001 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1002 */
1003 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1004 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1005 reg->umin_value);
1006 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1007 reg->umax_value);
1008 return;
1009 }
1010 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1011 * boundary, so we must be careful.
1012 */
1013 if ((s64)reg->umax_value >= 0) {
1014 /* Positive. We can't learn anything from the smin, but smax
1015 * is positive, hence safe.
1016 */
1017 reg->smin_value = reg->umin_value;
1018 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1019 reg->umax_value);
1020 } else if ((s64)reg->umin_value < 0) {
1021 /* Negative. We can't learn anything from the smax, but smin
1022 * is negative, hence safe.
1023 */
1024 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1025 reg->umin_value);
1026 reg->smax_value = reg->umax_value;
1027 }
1028}
1029
1030/* Attempts to improve var_off based on unsigned min/max information */
1031static void __reg_bound_offset(struct bpf_reg_state *reg)
1032{
1033 reg->var_off = tnum_intersect(reg->var_off,
1034 tnum_range(reg->umin_value,
1035 reg->umax_value));
1036}
1037
1038/* Reset the min/max bounds of a register */
1039static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1040{
1041 reg->smin_value = S64_MIN;
1042 reg->smax_value = S64_MAX;
1043 reg->umin_value = 0;
1044 reg->umax_value = U64_MAX;
1045}
1046
Edward Creef1174f72017-08-07 15:26:19 +01001047/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001048static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1049 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001050{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001051 /*
1052 * Clear type, id, off, and union(map_ptr, range) and
1053 * padding between 'type' and union
1054 */
1055 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001056 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001057 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001058 reg->frameno = 0;
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001059 reg->precise = env->subprog_cnt > 1 || !env->allow_ptr_leaks ?
1060 true : false;
Edward Creeb03c9f92017-08-07 15:26:36 +01001061 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001062}
1063
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001064static void mark_reg_unknown(struct bpf_verifier_env *env,
1065 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001066{
1067 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001068 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001069 /* Something bad happened, let's kill all regs except FP */
1070 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001071 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001072 return;
1073 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001074 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001075}
1076
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001077static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1078 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001079{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001080 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001081 reg->type = NOT_INIT;
1082}
1083
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001084static void mark_reg_not_init(struct bpf_verifier_env *env,
1085 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001086{
Edward Creef1174f72017-08-07 15:26:19 +01001087 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001088 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001089 /* Something bad happened, let's kill all regs except FP */
1090 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001091 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001092 return;
1093 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001094 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001095}
1096
Jiong Wang5327ed32019-05-24 23:25:12 +01001097#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001098static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001099 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001100{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001101 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001102 int i;
1103
Edward Creedc503a82017-08-15 20:34:35 +01001104 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001105 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001106 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001107 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001108 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001109 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001110
1111 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001112 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001113 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001114 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001115}
1116
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001117#define BPF_MAIN_FUNC (-1)
1118static void init_func_state(struct bpf_verifier_env *env,
1119 struct bpf_func_state *state,
1120 int callsite, int frameno, int subprogno)
1121{
1122 state->callsite = callsite;
1123 state->frameno = frameno;
1124 state->subprogno = subprogno;
1125 init_reg_state(env, state);
1126}
1127
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001128enum reg_arg_type {
1129 SRC_OP, /* register is used as source operand */
1130 DST_OP, /* register is used as destination operand */
1131 DST_OP_NO_MARK /* same as above, check only, don't mark */
1132};
1133
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001134static int cmp_subprogs(const void *a, const void *b)
1135{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001136 return ((struct bpf_subprog_info *)a)->start -
1137 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001138}
1139
1140static int find_subprog(struct bpf_verifier_env *env, int off)
1141{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001142 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001143
Jiong Wang9c8105b2018-05-02 16:17:18 -04001144 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1145 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001146 if (!p)
1147 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001148 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001149
1150}
1151
1152static int add_subprog(struct bpf_verifier_env *env, int off)
1153{
1154 int insn_cnt = env->prog->len;
1155 int ret;
1156
1157 if (off >= insn_cnt || off < 0) {
1158 verbose(env, "call to invalid destination\n");
1159 return -EINVAL;
1160 }
1161 ret = find_subprog(env, off);
1162 if (ret >= 0)
1163 return 0;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001164 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001165 verbose(env, "too many subprograms\n");
1166 return -E2BIG;
1167 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04001168 env->subprog_info[env->subprog_cnt++].start = off;
1169 sort(env->subprog_info, env->subprog_cnt,
1170 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001171 return 0;
1172}
1173
1174static int check_subprogs(struct bpf_verifier_env *env)
1175{
1176 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001177 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001178 struct bpf_insn *insn = env->prog->insnsi;
1179 int insn_cnt = env->prog->len;
1180
Jiong Wangf910cef2018-05-02 16:17:17 -04001181 /* Add entry function. */
1182 ret = add_subprog(env, 0);
1183 if (ret < 0)
1184 return ret;
1185
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001186 /* determine subprog starts. The end is one before the next starts */
1187 for (i = 0; i < insn_cnt; i++) {
1188 if (insn[i].code != (BPF_JMP | BPF_CALL))
1189 continue;
1190 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1191 continue;
1192 if (!env->allow_ptr_leaks) {
1193 verbose(env, "function calls to other bpf functions are allowed for root only\n");
1194 return -EPERM;
1195 }
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001196 ret = add_subprog(env, i + insn[i].imm + 1);
1197 if (ret < 0)
1198 return ret;
1199 }
1200
Jiong Wang4cb3d992018-05-02 16:17:19 -04001201 /* Add a fake 'exit' subprog which could simplify subprog iteration
1202 * logic. 'subprog_cnt' should not be increased.
1203 */
1204 subprog[env->subprog_cnt].start = insn_cnt;
1205
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001206 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001207 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001208 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001209
1210 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001211 subprog_start = subprog[cur_subprog].start;
1212 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001213 for (i = 0; i < insn_cnt; i++) {
1214 u8 code = insn[i].code;
1215
Jiong Wang092ed092019-01-26 12:26:01 -05001216 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001217 goto next;
1218 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1219 goto next;
1220 off = i + insn[i].off + 1;
1221 if (off < subprog_start || off >= subprog_end) {
1222 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1223 return -EINVAL;
1224 }
1225next:
1226 if (i == subprog_end - 1) {
1227 /* to avoid fall-through from one subprog into another
1228 * the last insn of the subprog should be either exit
1229 * or unconditional jump back
1230 */
1231 if (code != (BPF_JMP | BPF_EXIT) &&
1232 code != (BPF_JMP | BPF_JA)) {
1233 verbose(env, "last insn is not an exit or jmp\n");
1234 return -EINVAL;
1235 }
1236 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001237 cur_subprog++;
1238 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001239 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001240 }
1241 }
1242 return 0;
1243}
1244
Edward Cree679c7822018-08-22 20:02:19 +01001245/* Parentage chain of this register (or stack slot) should take care of all
1246 * issues like callee-saved registers, stack slot allocation time, etc.
1247 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001248static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001249 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001250 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001251{
1252 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001253 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001254
1255 while (parent) {
1256 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001257 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001258 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001259 if (parent->live & REG_LIVE_DONE) {
1260 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1261 reg_type_str[parent->type],
1262 parent->var_off.value, parent->off);
1263 return -EFAULT;
1264 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001265 /* The first condition is more likely to be true than the
1266 * second, checked it first.
1267 */
1268 if ((parent->live & REG_LIVE_READ) == flag ||
1269 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001270 /* The parentage chain never changes and
1271 * this parent was already marked as LIVE_READ.
1272 * There is no need to keep walking the chain again and
1273 * keep re-marking all parents as LIVE_READ.
1274 * This case happens when the same register is read
1275 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001276 * Also, if parent has the stronger REG_LIVE_READ64 set,
1277 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001278 */
1279 break;
Edward Creedc503a82017-08-15 20:34:35 +01001280 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001281 parent->live |= flag;
1282 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1283 if (flag == REG_LIVE_READ64)
1284 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001285 state = parent;
1286 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001287 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001288 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001289 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001290
1291 if (env->longest_mark_read_walk < cnt)
1292 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001293 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001294}
1295
Jiong Wang5327ed32019-05-24 23:25:12 +01001296/* This function is supposed to be used by the following 32-bit optimization
1297 * code only. It returns TRUE if the source or destination register operates
1298 * on 64-bit, otherwise return FALSE.
1299 */
1300static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1301 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1302{
1303 u8 code, class, op;
1304
1305 code = insn->code;
1306 class = BPF_CLASS(code);
1307 op = BPF_OP(code);
1308 if (class == BPF_JMP) {
1309 /* BPF_EXIT for "main" will reach here. Return TRUE
1310 * conservatively.
1311 */
1312 if (op == BPF_EXIT)
1313 return true;
1314 if (op == BPF_CALL) {
1315 /* BPF to BPF call will reach here because of marking
1316 * caller saved clobber with DST_OP_NO_MARK for which we
1317 * don't care the register def because they are anyway
1318 * marked as NOT_INIT already.
1319 */
1320 if (insn->src_reg == BPF_PSEUDO_CALL)
1321 return false;
1322 /* Helper call will reach here because of arg type
1323 * check, conservatively return TRUE.
1324 */
1325 if (t == SRC_OP)
1326 return true;
1327
1328 return false;
1329 }
1330 }
1331
1332 if (class == BPF_ALU64 || class == BPF_JMP ||
1333 /* BPF_END always use BPF_ALU class. */
1334 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1335 return true;
1336
1337 if (class == BPF_ALU || class == BPF_JMP32)
1338 return false;
1339
1340 if (class == BPF_LDX) {
1341 if (t != SRC_OP)
1342 return BPF_SIZE(code) == BPF_DW;
1343 /* LDX source must be ptr. */
1344 return true;
1345 }
1346
1347 if (class == BPF_STX) {
1348 if (reg->type != SCALAR_VALUE)
1349 return true;
1350 return BPF_SIZE(code) == BPF_DW;
1351 }
1352
1353 if (class == BPF_LD) {
1354 u8 mode = BPF_MODE(code);
1355
1356 /* LD_IMM64 */
1357 if (mode == BPF_IMM)
1358 return true;
1359
1360 /* Both LD_IND and LD_ABS return 32-bit data. */
1361 if (t != SRC_OP)
1362 return false;
1363
1364 /* Implicit ctx ptr. */
1365 if (regno == BPF_REG_6)
1366 return true;
1367
1368 /* Explicit source could be any width. */
1369 return true;
1370 }
1371
1372 if (class == BPF_ST)
1373 /* The only source register for BPF_ST is a ptr. */
1374 return true;
1375
1376 /* Conservatively return true at default. */
1377 return true;
1378}
1379
Jiong Wangb325fbc2019-05-24 23:25:13 +01001380/* Return TRUE if INSN doesn't have explicit value define. */
1381static bool insn_no_def(struct bpf_insn *insn)
1382{
1383 u8 class = BPF_CLASS(insn->code);
1384
1385 return (class == BPF_JMP || class == BPF_JMP32 ||
1386 class == BPF_STX || class == BPF_ST);
1387}
1388
1389/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1390static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1391{
1392 if (insn_no_def(insn))
1393 return false;
1394
1395 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1396}
1397
Jiong Wang5327ed32019-05-24 23:25:12 +01001398static void mark_insn_zext(struct bpf_verifier_env *env,
1399 struct bpf_reg_state *reg)
1400{
1401 s32 def_idx = reg->subreg_def;
1402
1403 if (def_idx == DEF_NOT_SUBREG)
1404 return;
1405
1406 env->insn_aux_data[def_idx - 1].zext_dst = true;
1407 /* The dst will be zero extended, so won't be sub-register anymore. */
1408 reg->subreg_def = DEF_NOT_SUBREG;
1409}
1410
Edward Creedc503a82017-08-15 20:34:35 +01001411static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001412 enum reg_arg_type t)
1413{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001414 struct bpf_verifier_state *vstate = env->cur_state;
1415 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01001416 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01001417 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01001418 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01001419
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001420 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001421 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001422 return -EINVAL;
1423 }
1424
Jiong Wangc342dc12019-04-12 22:59:37 +01001425 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01001426 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001427 if (t == SRC_OP) {
1428 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01001429 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001430 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001431 return -EACCES;
1432 }
Edward Cree679c7822018-08-22 20:02:19 +01001433 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01001434 if (regno == BPF_REG_FP)
1435 return 0;
1436
Jiong Wang5327ed32019-05-24 23:25:12 +01001437 if (rw64)
1438 mark_insn_zext(env, reg);
1439
1440 return mark_reg_read(env, reg, reg->parent,
1441 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001442 } else {
1443 /* check whether register used as dest operand can be written to */
1444 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001445 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001446 return -EACCES;
1447 }
Jiong Wangc342dc12019-04-12 22:59:37 +01001448 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01001449 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001450 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001451 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001452 }
1453 return 0;
1454}
1455
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001456/* for any branch, call, exit record the history of jmps in the given state */
1457static int push_jmp_history(struct bpf_verifier_env *env,
1458 struct bpf_verifier_state *cur)
1459{
1460 u32 cnt = cur->jmp_history_cnt;
1461 struct bpf_idx_pair *p;
1462
1463 cnt++;
1464 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1465 if (!p)
1466 return -ENOMEM;
1467 p[cnt - 1].idx = env->insn_idx;
1468 p[cnt - 1].prev_idx = env->prev_insn_idx;
1469 cur->jmp_history = p;
1470 cur->jmp_history_cnt = cnt;
1471 return 0;
1472}
1473
1474/* Backtrack one insn at a time. If idx is not at the top of recorded
1475 * history then previous instruction came from straight line execution.
1476 */
1477static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1478 u32 *history)
1479{
1480 u32 cnt = *history;
1481
1482 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1483 i = st->jmp_history[cnt - 1].prev_idx;
1484 (*history)--;
1485 } else {
1486 i--;
1487 }
1488 return i;
1489}
1490
1491/* For given verifier state backtrack_insn() is called from the last insn to
1492 * the first insn. Its purpose is to compute a bitmask of registers and
1493 * stack slots that needs precision in the parent verifier state.
1494 */
1495static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1496 u32 *reg_mask, u64 *stack_mask)
1497{
1498 const struct bpf_insn_cbs cbs = {
1499 .cb_print = verbose,
1500 .private_data = env,
1501 };
1502 struct bpf_insn *insn = env->prog->insnsi + idx;
1503 u8 class = BPF_CLASS(insn->code);
1504 u8 opcode = BPF_OP(insn->code);
1505 u8 mode = BPF_MODE(insn->code);
1506 u32 dreg = 1u << insn->dst_reg;
1507 u32 sreg = 1u << insn->src_reg;
1508 u32 spi;
1509
1510 if (insn->code == 0)
1511 return 0;
1512 if (env->log.level & BPF_LOG_LEVEL) {
1513 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1514 verbose(env, "%d: ", idx);
1515 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1516 }
1517
1518 if (class == BPF_ALU || class == BPF_ALU64) {
1519 if (!(*reg_mask & dreg))
1520 return 0;
1521 if (opcode == BPF_MOV) {
1522 if (BPF_SRC(insn->code) == BPF_X) {
1523 /* dreg = sreg
1524 * dreg needs precision after this insn
1525 * sreg needs precision before this insn
1526 */
1527 *reg_mask &= ~dreg;
1528 *reg_mask |= sreg;
1529 } else {
1530 /* dreg = K
1531 * dreg needs precision after this insn.
1532 * Corresponding register is already marked
1533 * as precise=true in this verifier state.
1534 * No further markings in parent are necessary
1535 */
1536 *reg_mask &= ~dreg;
1537 }
1538 } else {
1539 if (BPF_SRC(insn->code) == BPF_X) {
1540 /* dreg += sreg
1541 * both dreg and sreg need precision
1542 * before this insn
1543 */
1544 *reg_mask |= sreg;
1545 } /* else dreg += K
1546 * dreg still needs precision before this insn
1547 */
1548 }
1549 } else if (class == BPF_LDX) {
1550 if (!(*reg_mask & dreg))
1551 return 0;
1552 *reg_mask &= ~dreg;
1553
1554 /* scalars can only be spilled into stack w/o losing precision.
1555 * Load from any other memory can be zero extended.
1556 * The desire to keep that precision is already indicated
1557 * by 'precise' mark in corresponding register of this state.
1558 * No further tracking necessary.
1559 */
1560 if (insn->src_reg != BPF_REG_FP)
1561 return 0;
1562 if (BPF_SIZE(insn->code) != BPF_DW)
1563 return 0;
1564
1565 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1566 * that [fp - off] slot contains scalar that needs to be
1567 * tracked with precision
1568 */
1569 spi = (-insn->off - 1) / BPF_REG_SIZE;
1570 if (spi >= 64) {
1571 verbose(env, "BUG spi %d\n", spi);
1572 WARN_ONCE(1, "verifier backtracking bug");
1573 return -EFAULT;
1574 }
1575 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001576 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001577 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001578 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001579 * to access memory. It means backtracking
1580 * encountered a case of pointer subtraction.
1581 */
1582 return -ENOTSUPP;
1583 /* scalars can only be spilled into stack */
1584 if (insn->dst_reg != BPF_REG_FP)
1585 return 0;
1586 if (BPF_SIZE(insn->code) != BPF_DW)
1587 return 0;
1588 spi = (-insn->off - 1) / BPF_REG_SIZE;
1589 if (spi >= 64) {
1590 verbose(env, "BUG spi %d\n", spi);
1591 WARN_ONCE(1, "verifier backtracking bug");
1592 return -EFAULT;
1593 }
1594 if (!(*stack_mask & (1ull << spi)))
1595 return 0;
1596 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001597 if (class == BPF_STX)
1598 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001599 } else if (class == BPF_JMP || class == BPF_JMP32) {
1600 if (opcode == BPF_CALL) {
1601 if (insn->src_reg == BPF_PSEUDO_CALL)
1602 return -ENOTSUPP;
1603 /* regular helper call sets R0 */
1604 *reg_mask &= ~1;
1605 if (*reg_mask & 0x3f) {
1606 /* if backtracing was looking for registers R1-R5
1607 * they should have been found already.
1608 */
1609 verbose(env, "BUG regs %x\n", *reg_mask);
1610 WARN_ONCE(1, "verifier backtracking bug");
1611 return -EFAULT;
1612 }
1613 } else if (opcode == BPF_EXIT) {
1614 return -ENOTSUPP;
1615 }
1616 } else if (class == BPF_LD) {
1617 if (!(*reg_mask & dreg))
1618 return 0;
1619 *reg_mask &= ~dreg;
1620 /* It's ld_imm64 or ld_abs or ld_ind.
1621 * For ld_imm64 no further tracking of precision
1622 * into parent is necessary
1623 */
1624 if (mode == BPF_IND || mode == BPF_ABS)
1625 /* to be analyzed */
1626 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001627 }
1628 return 0;
1629}
1630
1631/* the scalar precision tracking algorithm:
1632 * . at the start all registers have precise=false.
1633 * . scalar ranges are tracked as normal through alu and jmp insns.
1634 * . once precise value of the scalar register is used in:
1635 * . ptr + scalar alu
1636 * . if (scalar cond K|scalar)
1637 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1638 * backtrack through the verifier states and mark all registers and
1639 * stack slots with spilled constants that these scalar regisers
1640 * should be precise.
1641 * . during state pruning two registers (or spilled stack slots)
1642 * are equivalent if both are not precise.
1643 *
1644 * Note the verifier cannot simply walk register parentage chain,
1645 * since many different registers and stack slots could have been
1646 * used to compute single precise scalar.
1647 *
1648 * The approach of starting with precise=true for all registers and then
1649 * backtrack to mark a register as not precise when the verifier detects
1650 * that program doesn't care about specific value (e.g., when helper
1651 * takes register as ARG_ANYTHING parameter) is not safe.
1652 *
1653 * It's ok to walk single parentage chain of the verifier states.
1654 * It's possible that this backtracking will go all the way till 1st insn.
1655 * All other branches will be explored for needing precision later.
1656 *
1657 * The backtracking needs to deal with cases like:
1658 * 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)
1659 * r9 -= r8
1660 * r5 = r9
1661 * if r5 > 0x79f goto pc+7
1662 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1663 * r5 += 1
1664 * ...
1665 * call bpf_perf_event_output#25
1666 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1667 *
1668 * and this case:
1669 * r6 = 1
1670 * call foo // uses callee's r6 inside to compute r0
1671 * r0 += r6
1672 * if r0 == 0 goto
1673 *
1674 * to track above reg_mask/stack_mask needs to be independent for each frame.
1675 *
1676 * Also if parent's curframe > frame where backtracking started,
1677 * the verifier need to mark registers in both frames, otherwise callees
1678 * may incorrectly prune callers. This is similar to
1679 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1680 *
1681 * For now backtracking falls back into conservative marking.
1682 */
1683static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1684 struct bpf_verifier_state *st)
1685{
1686 struct bpf_func_state *func;
1687 struct bpf_reg_state *reg;
1688 int i, j;
1689
1690 /* big hammer: mark all scalars precise in this path.
1691 * pop_stack may still get !precise scalars.
1692 */
1693 for (; st; st = st->parent)
1694 for (i = 0; i <= st->curframe; i++) {
1695 func = st->frame[i];
1696 for (j = 0; j < BPF_REG_FP; j++) {
1697 reg = &func->regs[j];
1698 if (reg->type != SCALAR_VALUE)
1699 continue;
1700 reg->precise = true;
1701 }
1702 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1703 if (func->stack[j].slot_type[0] != STACK_SPILL)
1704 continue;
1705 reg = &func->stack[j].spilled_ptr;
1706 if (reg->type != SCALAR_VALUE)
1707 continue;
1708 reg->precise = true;
1709 }
1710 }
1711}
1712
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001713static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1714 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001715{
1716 struct bpf_verifier_state *st = env->cur_state;
1717 int first_idx = st->first_insn_idx;
1718 int last_idx = env->insn_idx;
1719 struct bpf_func_state *func;
1720 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001721 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
1722 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001723 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001724 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001725 int i, err;
1726
1727 if (!env->allow_ptr_leaks)
1728 /* backtracking is root only for now */
1729 return 0;
1730
1731 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001732 if (regno >= 0) {
1733 reg = &func->regs[regno];
1734 if (reg->type != SCALAR_VALUE) {
1735 WARN_ONCE(1, "backtracing misuse");
1736 return -EFAULT;
1737 }
1738 if (!reg->precise)
1739 new_marks = true;
1740 else
1741 reg_mask = 0;
1742 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001743 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001744
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001745 while (spi >= 0) {
1746 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
1747 stack_mask = 0;
1748 break;
1749 }
1750 reg = &func->stack[spi].spilled_ptr;
1751 if (reg->type != SCALAR_VALUE) {
1752 stack_mask = 0;
1753 break;
1754 }
1755 if (!reg->precise)
1756 new_marks = true;
1757 else
1758 stack_mask = 0;
1759 reg->precise = true;
1760 break;
1761 }
1762
1763 if (!new_marks)
1764 return 0;
1765 if (!reg_mask && !stack_mask)
1766 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001767 for (;;) {
1768 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001769 u32 history = st->jmp_history_cnt;
1770
1771 if (env->log.level & BPF_LOG_LEVEL)
1772 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
1773 for (i = last_idx;;) {
1774 if (skip_first) {
1775 err = 0;
1776 skip_first = false;
1777 } else {
1778 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
1779 }
1780 if (err == -ENOTSUPP) {
1781 mark_all_scalars_precise(env, st);
1782 return 0;
1783 } else if (err) {
1784 return err;
1785 }
1786 if (!reg_mask && !stack_mask)
1787 /* Found assignment(s) into tracked register in this state.
1788 * Since this state is already marked, just return.
1789 * Nothing to be tracked further in the parent state.
1790 */
1791 return 0;
1792 if (i == first_idx)
1793 break;
1794 i = get_prev_insn_idx(st, i, &history);
1795 if (i >= env->prog->len) {
1796 /* This can happen if backtracking reached insn 0
1797 * and there are still reg_mask or stack_mask
1798 * to backtrack.
1799 * It means the backtracking missed the spot where
1800 * particular register was initialized with a constant.
1801 */
1802 verbose(env, "BUG backtracking idx %d\n", i);
1803 WARN_ONCE(1, "verifier backtracking bug");
1804 return -EFAULT;
1805 }
1806 }
1807 st = st->parent;
1808 if (!st)
1809 break;
1810
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001811 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001812 func = st->frame[st->curframe];
1813 bitmap_from_u64(mask, reg_mask);
1814 for_each_set_bit(i, mask, 32) {
1815 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001816 if (reg->type != SCALAR_VALUE) {
1817 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001818 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001819 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001820 if (!reg->precise)
1821 new_marks = true;
1822 reg->precise = true;
1823 }
1824
1825 bitmap_from_u64(mask, stack_mask);
1826 for_each_set_bit(i, mask, 64) {
1827 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07001828 /* the sequence of instructions:
1829 * 2: (bf) r3 = r10
1830 * 3: (7b) *(u64 *)(r3 -8) = r0
1831 * 4: (79) r4 = *(u64 *)(r10 -8)
1832 * doesn't contain jmps. It's backtracked
1833 * as a single block.
1834 * During backtracking insn 3 is not recognized as
1835 * stack access, so at the end of backtracking
1836 * stack slot fp-8 is still marked in stack_mask.
1837 * However the parent state may not have accessed
1838 * fp-8 and it's "unallocated" stack space.
1839 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001840 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07001841 mark_all_scalars_precise(env, st);
1842 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001843 }
1844
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001845 if (func->stack[i].slot_type[0] != STACK_SPILL) {
1846 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001847 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001848 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001849 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001850 if (reg->type != SCALAR_VALUE) {
1851 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001852 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001853 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001854 if (!reg->precise)
1855 new_marks = true;
1856 reg->precise = true;
1857 }
1858 if (env->log.level & BPF_LOG_LEVEL) {
1859 print_verifier_state(env, func);
1860 verbose(env, "parent %s regs=%x stack=%llx marks\n",
1861 new_marks ? "didn't have" : "already had",
1862 reg_mask, stack_mask);
1863 }
1864
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001865 if (!reg_mask && !stack_mask)
1866 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001867 if (!new_marks)
1868 break;
1869
1870 last_idx = st->last_insn_idx;
1871 first_idx = st->first_insn_idx;
1872 }
1873 return 0;
1874}
1875
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001876static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
1877{
1878 return __mark_chain_precision(env, regno, -1);
1879}
1880
1881static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
1882{
1883 return __mark_chain_precision(env, -1, spi);
1884}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001885
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07001886static bool is_spillable_regtype(enum bpf_reg_type type)
1887{
1888 switch (type) {
1889 case PTR_TO_MAP_VALUE:
1890 case PTR_TO_MAP_VALUE_OR_NULL:
1891 case PTR_TO_STACK:
1892 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07001893 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001894 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07001895 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07001896 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07001897 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07001898 case PTR_TO_SOCKET:
1899 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08001900 case PTR_TO_SOCK_COMMON:
1901 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08001902 case PTR_TO_TCP_SOCK:
1903 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07001904 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08001905 case PTR_TO_BTF_ID:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07001906 return true;
1907 default:
1908 return false;
1909 }
1910}
1911
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001912/* Does this register contain a constant zero? */
1913static bool register_is_null(struct bpf_reg_state *reg)
1914{
1915 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1916}
1917
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001918static bool register_is_const(struct bpf_reg_state *reg)
1919{
1920 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
1921}
1922
1923static void save_register_state(struct bpf_func_state *state,
1924 int spi, struct bpf_reg_state *reg)
1925{
1926 int i;
1927
1928 state->stack[spi].spilled_ptr = *reg;
1929 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1930
1931 for (i = 0; i < BPF_REG_SIZE; i++)
1932 state->stack[spi].slot_type[i] = STACK_SPILL;
1933}
1934
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001935/* check_stack_read/write functions track spill/fill of registers,
1936 * stack boundary and alignment are checked in check_mem_access()
1937 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001938static int check_stack_write(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001939 struct bpf_func_state *state, /* func where register points to */
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07001940 int off, int size, int value_regno, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001941{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001942 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001943 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001944 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001945 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001946
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001947 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07001948 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001949 if (err)
1950 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07001951 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1952 * so it's aligned access and [off, off + size) are within stack limits
1953 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001954 if (!env->allow_ptr_leaks &&
1955 state->stack[spi].slot_type[0] == STACK_SPILL &&
1956 size != BPF_REG_SIZE) {
1957 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1958 return -EACCES;
1959 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001960
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001961 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001962 if (value_regno >= 0)
1963 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001964
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001965 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
1966 !register_is_null(reg) && env->allow_ptr_leaks) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001967 if (dst_reg != BPF_REG_FP) {
1968 /* The backtracking logic can only recognize explicit
1969 * stack slot address like [fp - 8]. Other spill of
1970 * scalar via different register has to be conervative.
1971 * Backtrack from here and mark all registers as precise
1972 * that contributed into 'reg' being a constant.
1973 */
1974 err = mark_chain_precision(env, value_regno);
1975 if (err)
1976 return err;
1977 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001978 save_register_state(state, spi, reg);
1979 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001980 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07001981 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001982 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001983 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001984 return -EACCES;
1985 }
1986
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001987 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001988 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1989 return -EINVAL;
1990 }
1991
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001992 if (!env->allow_ptr_leaks) {
1993 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001994
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001995 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
1996 register_is_const(&state->stack[spi].spilled_ptr))
1997 sanitize = true;
1998 for (i = 0; i < BPF_REG_SIZE; i++)
1999 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2000 sanitize = true;
2001 break;
2002 }
2003 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002004 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2005 int soff = (-spi - 1) * BPF_REG_SIZE;
2006
2007 /* detected reuse of integer stack slot with a pointer
2008 * which means either llvm is reusing stack slot or
2009 * an attacker is trying to exploit CVE-2018-3639
2010 * (speculative store bypass)
2011 * Have to sanitize that slot with preemptive
2012 * store of zero.
2013 */
2014 if (*poff && *poff != soff) {
2015 /* disallow programs where single insn stores
2016 * into two different stack slots, since verifier
2017 * cannot sanitize them
2018 */
2019 verbose(env,
2020 "insn %d cannot access two stack slots fp%d and fp%d",
2021 insn_idx, *poff, soff);
2022 return -EINVAL;
2023 }
2024 *poff = soff;
2025 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002026 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002027 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002028 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002029 u8 type = STACK_MISC;
2030
Edward Cree679c7822018-08-22 20:02:19 +01002031 /* regular write of data into stack destroys any spilled ptr */
2032 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002033 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2034 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2035 for (i = 0; i < BPF_REG_SIZE; i++)
2036 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002037
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002038 /* only mark the slot as written if all 8 bytes were written
2039 * otherwise read propagation may incorrectly stop too soon
2040 * when stack slots are partially written.
2041 * This heuristic means that read propagation will be
2042 * conservative, since it will add reg_live_read marks
2043 * to stack slots all the way to first state when programs
2044 * writes+reads less than 8 bytes
2045 */
2046 if (size == BPF_REG_SIZE)
2047 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2048
2049 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002050 if (reg && register_is_null(reg)) {
2051 /* backtracking doesn't work for STACK_ZERO yet. */
2052 err = mark_chain_precision(env, value_regno);
2053 if (err)
2054 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002055 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002056 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002057
Jiong Wang0bae2d42018-12-15 03:34:40 -05002058 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002059 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002060 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002061 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002062 }
2063 return 0;
2064}
2065
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002066static int check_stack_read(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002067 struct bpf_func_state *reg_state /* func where register points to */,
2068 int off, int size, int value_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002069{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002070 struct bpf_verifier_state *vstate = env->cur_state;
2071 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002072 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002073 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002074 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002075
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002076 if (reg_state->allocated_stack <= slot) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002077 verbose(env, "invalid read from stack off %d+0 size %d\n",
2078 off, size);
2079 return -EACCES;
2080 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002081 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002082 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002083
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002084 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002085 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002086 if (reg->type != SCALAR_VALUE) {
2087 verbose_linfo(env, env->insn_idx, "; ");
2088 verbose(env, "invalid size of register fill\n");
2089 return -EACCES;
2090 }
2091 if (value_regno >= 0) {
2092 mark_reg_unknown(env, state->regs, value_regno);
2093 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2094 }
2095 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2096 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002097 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002098 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002099 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002100 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002101 return -EACCES;
2102 }
2103 }
2104
Edward Creedc503a82017-08-15 20:34:35 +01002105 if (value_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002106 /* restore register state from stack */
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002107 state->regs[value_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002108 /* mark reg as written since spilled pointer state likely
2109 * has its liveness marks cleared by is_state_visited()
2110 * which resets stack/reg liveness for state transitions
2111 */
2112 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
Edward Creedc503a82017-08-15 20:34:35 +01002113 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002114 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002115 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002116 int zeros = 0;
2117
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002118 for (i = 0; i < size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002119 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2120 continue;
2121 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2122 zeros++;
2123 continue;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002124 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002125 verbose(env, "invalid read from stack off %d+%d size %d\n",
2126 off, i, size);
2127 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002128 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002129 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002130 if (value_regno >= 0) {
2131 if (zeros == size) {
2132 /* any size read into register is zero extended,
2133 * so the whole register == const_zero
2134 */
2135 __mark_reg_const_zero(&state->regs[value_regno]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002136 /* backtracking doesn't support STACK_ZERO yet,
2137 * so mark it precise here, so that later
2138 * backtracking can stop here.
2139 * Backtracking may not need this if this register
2140 * doesn't participate in pointer adjustment.
2141 * Forward propagation of precise flag is not
2142 * necessary either. This mark is only to stop
2143 * backtracking. Any register that contributed
2144 * to const 0 was marked precise before spill.
2145 */
2146 state->regs[value_regno].precise = true;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002147 } else {
2148 /* have read misc data from the stack */
2149 mark_reg_unknown(env, state->regs, value_regno);
2150 }
2151 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2152 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002153 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002154 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002155}
2156
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002157static int check_stack_access(struct bpf_verifier_env *env,
2158 const struct bpf_reg_state *reg,
2159 int off, int size)
2160{
2161 /* Stack accesses must be at a fixed offset, so that we
2162 * can determine what type of data were returned. See
2163 * check_stack_read().
2164 */
2165 if (!tnum_is_const(reg->var_off)) {
2166 char tn_buf[48];
2167
2168 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrey Ignatov1fbd20f2019-04-03 23:22:43 -07002169 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002170 tn_buf, off, size);
2171 return -EACCES;
2172 }
2173
2174 if (off >= 0 || off < -MAX_BPF_STACK) {
2175 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2176 return -EACCES;
2177 }
2178
2179 return 0;
2180}
2181
Daniel Borkmann591fe982019-04-09 23:20:05 +02002182static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2183 int off, int size, enum bpf_access_type type)
2184{
2185 struct bpf_reg_state *regs = cur_regs(env);
2186 struct bpf_map *map = regs[regno].map_ptr;
2187 u32 cap = bpf_map_flags_to_cap(map);
2188
2189 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2190 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2191 map->value_size, off, size);
2192 return -EACCES;
2193 }
2194
2195 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2196 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2197 map->value_size, off, size);
2198 return -EACCES;
2199 }
2200
2201 return 0;
2202}
2203
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002204/* check read/write into map element returned by bpf_map_lookup_elem() */
Edward Creef1174f72017-08-07 15:26:19 +01002205static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002206 int size, bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002207{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002208 struct bpf_reg_state *regs = cur_regs(env);
2209 struct bpf_map *map = regs[regno].map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002210
Yonghong Song9fd29c02017-11-12 14:49:09 -08002211 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2212 off + size > map->value_size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002213 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002214 map->value_size, off, size);
2215 return -EACCES;
2216 }
2217 return 0;
2218}
2219
Edward Creef1174f72017-08-07 15:26:19 +01002220/* check read/write into a map element with possible variable offset */
2221static int check_map_access(struct bpf_verifier_env *env, u32 regno,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002222 int off, int size, bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002223{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002224 struct bpf_verifier_state *vstate = env->cur_state;
2225 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002226 struct bpf_reg_state *reg = &state->regs[regno];
2227 int err;
2228
Edward Creef1174f72017-08-07 15:26:19 +01002229 /* We may have adjusted the register to this map value, so we
2230 * need to try adding each of min_value and max_value to off
2231 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002232 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002233 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002234 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002235
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002236 /* The minimum value is only important with signed
2237 * comparisons where we can't assume the floor of a
2238 * value is 0. If we are using signed variables for our
2239 * index'es we need to make sure that whatever we use
2240 * will have a set floor within our range.
2241 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002242 if (reg->smin_value < 0 &&
2243 (reg->smin_value == S64_MIN ||
2244 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2245 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002246 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 -08002247 regno);
2248 return -EACCES;
2249 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08002250 err = __check_map_access(env, regno, reg->smin_value + off, size,
2251 zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002252 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002253 verbose(env, "R%d min value is outside of the array range\n",
2254 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002255 return err;
2256 }
2257
Edward Creeb03c9f92017-08-07 15:26:36 +01002258 /* If we haven't set a max value then we need to bail since we can't be
2259 * sure we won't do bad things.
2260 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002261 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002262 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002263 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002264 regno);
2265 return -EACCES;
2266 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08002267 err = __check_map_access(env, regno, reg->umax_value + off, size,
2268 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01002269 if (err)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002270 verbose(env, "R%d max value is outside of the array range\n",
2271 regno);
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002272
2273 if (map_value_has_spin_lock(reg->map_ptr)) {
2274 u32 lock = reg->map_ptr->spin_lock_off;
2275
2276 /* if any part of struct bpf_spin_lock can be touched by
2277 * load/store reject this program.
2278 * To check that [x1, x2) overlaps with [y1, y2)
2279 * it is sufficient to check x1 < y2 && y1 < x2.
2280 */
2281 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2282 lock < reg->umax_value + off + size) {
2283 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2284 return -EACCES;
2285 }
2286 }
Edward Creef1174f72017-08-07 15:26:19 +01002287 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002288}
2289
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002290#define MAX_PACKET_OFF 0xffff
2291
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01002292static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002293 const struct bpf_call_arg_meta *meta,
2294 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002295{
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002296 switch (env->prog->type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002297 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002298 case BPF_PROG_TYPE_LWT_IN:
2299 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01002300 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07002301 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002302 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02002303 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002304 if (t == BPF_WRITE)
2305 return false;
Alexander Alemayhu7e57fbb2017-02-14 00:02:35 +01002306 /* fallthrough */
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002307
2308 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002309 case BPF_PROG_TYPE_SCHED_CLS:
2310 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002311 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002312 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07002313 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07002314 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002315 if (meta)
2316 return meta->pkt_access;
2317
2318 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002319 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07002320
2321 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2322 if (t == BPF_WRITE)
2323 env->seen_direct_write = true;
2324
2325 return true;
2326
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002327 default:
2328 return false;
2329 }
2330}
2331
Edward Creef1174f72017-08-07 15:26:19 +01002332static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002333 int off, int size, bool zero_size_allowed)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002334{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002335 struct bpf_reg_state *regs = cur_regs(env);
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01002336 struct bpf_reg_state *reg = &regs[regno];
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002337
Yonghong Song9fd29c02017-11-12 14:49:09 -08002338 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2339 (u64)off + size > reg->range) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002340 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
Alexei Starovoitovd91b28e2016-05-19 18:17:13 -07002341 off, size, regno, reg->id, reg->off, reg->range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002342 return -EACCES;
2343 }
2344 return 0;
2345}
2346
Edward Creef1174f72017-08-07 15:26:19 +01002347static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002348 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01002349{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002350 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01002351 struct bpf_reg_state *reg = &regs[regno];
2352 int err;
2353
2354 /* We may have added a variable offset to the packet pointer; but any
2355 * reg->range we have comes after that. We are only checking the fixed
2356 * offset.
2357 */
2358
2359 /* We don't allow negative numbers, because we aren't tracking enough
2360 * detail to prove they're safe.
2361 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002362 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002363 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 +01002364 regno);
2365 return -EACCES;
2366 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08002367 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01002368 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002369 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01002370 return err;
2371 }
Jiong Wange6478152018-11-08 04:08:42 -05002372
2373 /* __check_packet_access has made sure "off + size - 1" is within u16.
2374 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2375 * otherwise find_good_pkt_pointers would have refused to set range info
2376 * that __check_packet_access would have rejected this pkt access.
2377 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2378 */
2379 env->prog->aux->max_pkt_offset =
2380 max_t(u32, env->prog->aux->max_pkt_offset,
2381 off + reg->umax_value + size - 1);
2382
Edward Creef1174f72017-08-07 15:26:19 +01002383 return err;
2384}
2385
2386/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07002387static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002388 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2389 u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002390{
Daniel Borkmannf96da092017-07-02 02:13:27 +02002391 struct bpf_insn_access_aux info = {
2392 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002393 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02002394 };
Yonghong Song31fd8582017-06-13 15:52:13 -07002395
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07002396 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07002397 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02002398 /* A non zero info.ctx_field_size indicates that this field is a
2399 * candidate for later verifier transformation to load the whole
2400 * field and then apply a mask when accessed with a narrower
2401 * access than actual ctx access size. A zero info.ctx_field_size
2402 * will only allow for whole field access and rejects any other
2403 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07002404 */
Yonghong Song23994632017-06-22 15:07:39 -07002405 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07002406
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002407 if (*reg_type == PTR_TO_BTF_ID)
2408 *btf_id = info.btf_id;
2409 else
2410 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002411 /* remember the offset of last byte accessed in ctx */
2412 if (env->prog->aux->max_ctx_offset < off + size)
2413 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002414 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002415 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002416
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002417 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002418 return -EACCES;
2419}
2420
Petar Penkovd58e4682018-09-14 07:46:18 -07002421static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2422 int size)
2423{
2424 if (size < 0 || off < 0 ||
2425 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2426 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2427 off, size);
2428 return -EACCES;
2429 }
2430 return 0;
2431}
2432
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002433static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2434 u32 regno, int off, int size,
2435 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07002436{
2437 struct bpf_reg_state *regs = cur_regs(env);
2438 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002439 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002440 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07002441
2442 if (reg->smin_value < 0) {
2443 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2444 regno);
2445 return -EACCES;
2446 }
2447
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002448 switch (reg->type) {
2449 case PTR_TO_SOCK_COMMON:
2450 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2451 break;
2452 case PTR_TO_SOCKET:
2453 valid = bpf_sock_is_valid_access(off, size, t, &info);
2454 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002455 case PTR_TO_TCP_SOCK:
2456 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2457 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002458 case PTR_TO_XDP_SOCK:
2459 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2460 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002461 default:
2462 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07002463 }
2464
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002465
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002466 if (valid) {
2467 env->insn_aux_data[insn_idx].ctx_field_size =
2468 info.ctx_field_size;
2469 return 0;
2470 }
2471
2472 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2473 regno, reg_type_str[reg->type], off, size);
2474
2475 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07002476}
2477
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002478static bool __is_pointer_value(bool allow_ptr_leaks,
2479 const struct bpf_reg_state *reg)
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002480{
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002481 if (allow_ptr_leaks)
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002482 return false;
2483
Edward Creef1174f72017-08-07 15:26:19 +01002484 return reg->type != SCALAR_VALUE;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002485}
2486
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002487static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2488{
2489 return cur_regs(env) + regno;
2490}
2491
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002492static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2493{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002494 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002495}
2496
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002497static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2498{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002499 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002500
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002501 return reg->type == PTR_TO_CTX;
2502}
2503
2504static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2505{
2506 const struct bpf_reg_state *reg = reg_state(env, regno);
2507
2508 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002509}
2510
Daniel Borkmannca369602018-02-23 22:29:05 +01002511static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2512{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002513 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01002514
2515 return type_is_pkt_pointer(reg->type);
2516}
2517
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02002518static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2519{
2520 const struct bpf_reg_state *reg = reg_state(env, regno);
2521
2522 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2523 return reg->type == PTR_TO_FLOW_KEYS;
2524}
2525
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002526static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2527 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07002528 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002529{
Edward Creef1174f72017-08-07 15:26:19 +01002530 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07002531 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07002532
2533 /* Byte size accesses are always allowed. */
2534 if (!strict || size == 1)
2535 return 0;
2536
David S. Millere4eda882017-05-22 12:27:07 -04002537 /* For platforms that do not have a Kconfig enabling
2538 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2539 * NET_IP_ALIGN is universally set to '2'. And on platforms
2540 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2541 * to this code only in strict mode where we want to emulate
2542 * the NET_IP_ALIGN==2 checking. Therefore use an
2543 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07002544 */
David S. Millere4eda882017-05-22 12:27:07 -04002545 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01002546
2547 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2548 if (!tnum_is_aligned(reg_off, size)) {
2549 char tn_buf[48];
2550
2551 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002552 verbose(env,
2553 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002554 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002555 return -EACCES;
2556 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002557
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002558 return 0;
2559}
2560
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002561static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2562 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01002563 const char *pointer_desc,
2564 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002565{
Edward Creef1174f72017-08-07 15:26:19 +01002566 struct tnum reg_off;
2567
2568 /* Byte size accesses are always allowed. */
2569 if (!strict || size == 1)
2570 return 0;
2571
2572 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2573 if (!tnum_is_aligned(reg_off, size)) {
2574 char tn_buf[48];
2575
2576 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002577 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002578 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002579 return -EACCES;
2580 }
2581
2582 return 0;
2583}
2584
David S. Millere07b98d2017-05-10 11:38:07 -07002585static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01002586 const struct bpf_reg_state *reg, int off,
2587 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002588{
Daniel Borkmannca369602018-02-23 22:29:05 +01002589 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01002590 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07002591
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002592 switch (reg->type) {
2593 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002594 case PTR_TO_PACKET_META:
2595 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2596 * right in front, treat it the very same way.
2597 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002598 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07002599 case PTR_TO_FLOW_KEYS:
2600 pointer_desc = "flow keys ";
2601 break;
Edward Creef1174f72017-08-07 15:26:19 +01002602 case PTR_TO_MAP_VALUE:
2603 pointer_desc = "value ";
2604 break;
2605 case PTR_TO_CTX:
2606 pointer_desc = "context ";
2607 break;
2608 case PTR_TO_STACK:
2609 pointer_desc = "stack ";
Jann Horna5ec6ae2017-12-18 20:11:58 -08002610 /* The stack spill tracking logic in check_stack_write()
2611 * and check_stack_read() relies on stack accesses being
2612 * aligned.
2613 */
2614 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01002615 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07002616 case PTR_TO_SOCKET:
2617 pointer_desc = "sock ";
2618 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002619 case PTR_TO_SOCK_COMMON:
2620 pointer_desc = "sock_common ";
2621 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002622 case PTR_TO_TCP_SOCK:
2623 pointer_desc = "tcp_sock ";
2624 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002625 case PTR_TO_XDP_SOCK:
2626 pointer_desc = "xdp_sock ";
2627 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002628 default:
Edward Creef1174f72017-08-07 15:26:19 +01002629 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002630 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002631 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2632 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002633}
2634
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002635static int update_stack_depth(struct bpf_verifier_env *env,
2636 const struct bpf_func_state *func,
2637 int off)
2638{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002639 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002640
2641 if (stack >= -off)
2642 return 0;
2643
2644 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04002645 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002646 return 0;
2647}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002648
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002649/* starting from main bpf function walk all instructions of the function
2650 * and recursively walk all callees that given function can call.
2651 * Ignore jump and exit insns.
2652 * Since recursion is prevented by check_cfg() this algorithm
2653 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2654 */
2655static int check_max_stack_depth(struct bpf_verifier_env *env)
2656{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002657 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2658 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002659 struct bpf_insn *insn = env->prog->insnsi;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002660 int ret_insn[MAX_CALL_FRAMES];
2661 int ret_prog[MAX_CALL_FRAMES];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002662
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002663process_func:
2664 /* round up to 32-bytes, since this is granularity
2665 * of interpreter stack size
2666 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04002667 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002668 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002669 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002670 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002671 return -EACCES;
2672 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002673continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04002674 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002675 for (; i < subprog_end; i++) {
2676 if (insn[i].code != (BPF_JMP | BPF_CALL))
2677 continue;
2678 if (insn[i].src_reg != BPF_PSEUDO_CALL)
2679 continue;
2680 /* remember insn and function to return to */
2681 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04002682 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002683
2684 /* find the callee */
2685 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04002686 idx = find_subprog(env, i);
2687 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002688 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2689 i);
2690 return -EFAULT;
2691 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002692 frame++;
2693 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01002694 verbose(env, "the call stack of %d frames is too deep !\n",
2695 frame);
2696 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002697 }
2698 goto process_func;
2699 }
2700 /* end of for() loop means the last insn of the 'subprog'
2701 * was reached. Doesn't matter whether it was JA or EXIT
2702 */
2703 if (frame == 0)
2704 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04002705 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002706 frame--;
2707 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04002708 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002709 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002710}
2711
David S. Miller19d28fb2018-01-11 21:27:54 -05002712#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08002713static int get_callee_stack_depth(struct bpf_verifier_env *env,
2714 const struct bpf_insn *insn, int idx)
2715{
2716 int start = idx + insn->imm + 1, subprog;
2717
2718 subprog = find_subprog(env, start);
2719 if (subprog < 0) {
2720 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2721 start);
2722 return -EFAULT;
2723 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04002724 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08002725}
David S. Miller19d28fb2018-01-11 21:27:54 -05002726#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08002727
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08002728int check_ctx_reg(struct bpf_verifier_env *env,
2729 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02002730{
2731 /* Access to ctx or passing it to a helper is only allowed in
2732 * its original, unmodified form.
2733 */
2734
2735 if (reg->off) {
2736 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
2737 regno, reg->off);
2738 return -EACCES;
2739 }
2740
2741 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2742 char tn_buf[48];
2743
2744 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2745 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
2746 return -EACCES;
2747 }
2748
2749 return 0;
2750}
2751
Matt Mullins9df1c282019-04-26 11:49:47 -07002752static int check_tp_buffer_access(struct bpf_verifier_env *env,
2753 const struct bpf_reg_state *reg,
2754 int regno, int off, int size)
2755{
2756 if (off < 0) {
2757 verbose(env,
2758 "R%d invalid tracepoint buffer access: off=%d, size=%d",
2759 regno, off, size);
2760 return -EACCES;
2761 }
2762 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2763 char tn_buf[48];
2764
2765 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2766 verbose(env,
2767 "R%d invalid variable buffer offset: off=%d, var_off=%s",
2768 regno, off, tn_buf);
2769 return -EACCES;
2770 }
2771 if (off + size > env->prog->aux->max_tp_access)
2772 env->prog->aux->max_tp_access = off + size;
2773
2774 return 0;
2775}
2776
2777
Jann Horn0c17d1d2017-12-18 20:11:55 -08002778/* truncate register to smaller size (in bytes)
2779 * must be called with size < BPF_REG_SIZE
2780 */
2781static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
2782{
2783 u64 mask;
2784
2785 /* clear high bits in bit representation */
2786 reg->var_off = tnum_cast(reg->var_off, size);
2787
2788 /* fix arithmetic bounds */
2789 mask = ((u64)1 << (size * 8)) - 1;
2790 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
2791 reg->umin_value &= mask;
2792 reg->umax_value &= mask;
2793 } else {
2794 reg->umin_value = 0;
2795 reg->umax_value = mask;
2796 }
2797 reg->smin_value = reg->umin_value;
2798 reg->smax_value = reg->umax_value;
2799}
2800
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07002801static bool bpf_map_is_rdonly(const struct bpf_map *map)
2802{
2803 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
2804}
2805
2806static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
2807{
2808 void *ptr;
2809 u64 addr;
2810 int err;
2811
2812 err = map->ops->map_direct_value_addr(map, &addr, off);
2813 if (err)
2814 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07002815 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07002816
2817 switch (size) {
2818 case sizeof(u8):
2819 *val = (u64)*(u8 *)ptr;
2820 break;
2821 case sizeof(u16):
2822 *val = (u64)*(u16 *)ptr;
2823 break;
2824 case sizeof(u32):
2825 *val = (u64)*(u32 *)ptr;
2826 break;
2827 case sizeof(u64):
2828 *val = *(u64 *)ptr;
2829 break;
2830 default:
2831 return -EINVAL;
2832 }
2833 return 0;
2834}
2835
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002836static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
2837 struct bpf_reg_state *regs,
2838 int regno, int off, int size,
2839 enum bpf_access_type atype,
2840 int value_regno)
2841{
2842 struct bpf_reg_state *reg = regs + regno;
2843 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
2844 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
2845 u32 btf_id;
2846 int ret;
2847
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002848 if (off < 0) {
2849 verbose(env,
2850 "R%d is ptr_%s invalid negative access: off=%d\n",
2851 regno, tname, off);
2852 return -EACCES;
2853 }
2854 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2855 char tn_buf[48];
2856
2857 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2858 verbose(env,
2859 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
2860 regno, tname, off, tn_buf);
2861 return -EACCES;
2862 }
2863
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08002864 if (env->ops->btf_struct_access) {
2865 ret = env->ops->btf_struct_access(&env->log, t, off, size,
2866 atype, &btf_id);
2867 } else {
2868 if (atype != BPF_READ) {
2869 verbose(env, "only read is supported\n");
2870 return -EACCES;
2871 }
2872
2873 ret = btf_struct_access(&env->log, t, off, size, atype,
2874 &btf_id);
2875 }
2876
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002877 if (ret < 0)
2878 return ret;
2879
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08002880 if (atype == BPF_READ) {
2881 if (ret == SCALAR_VALUE) {
2882 mark_reg_unknown(env, regs, value_regno);
2883 return 0;
2884 }
2885 mark_reg_known_zero(env, regs, value_regno);
2886 regs[value_regno].type = PTR_TO_BTF_ID;
2887 regs[value_regno].btf_id = btf_id;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002888 }
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08002889
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002890 return 0;
2891}
2892
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002893/* check whether memory at (regno + off) is accessible for t = (read | write)
2894 * if t==write, value_regno is a register which value is stored into memory
2895 * if t==read, value_regno is a register which will receive the value from memory
2896 * if t==write && value_regno==-1, some unknown value is stored into memory
2897 * if t==read && value_regno==-1, don't care what we read from memory
2898 */
Daniel Borkmannca369602018-02-23 22:29:05 +01002899static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
2900 int off, int bpf_size, enum bpf_access_type t,
2901 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002902{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002903 struct bpf_reg_state *regs = cur_regs(env);
2904 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002905 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002906 int size, err = 0;
2907
2908 size = bpf_size_to_bytes(bpf_size);
2909 if (size < 0)
2910 return size;
2911
Edward Creef1174f72017-08-07 15:26:19 +01002912 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01002913 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002914 if (err)
2915 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002916
Edward Creef1174f72017-08-07 15:26:19 +01002917 /* for access checks, reg->off is just part of off */
2918 off += reg->off;
2919
2920 if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002921 if (t == BPF_WRITE && value_regno >= 0 &&
2922 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002923 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002924 return -EACCES;
2925 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02002926 err = check_map_access_type(env, regno, off, size, t);
2927 if (err)
2928 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08002929 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07002930 if (!err && t == BPF_READ && value_regno >= 0) {
2931 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002932
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07002933 /* if map is read-only, track its contents as scalars */
2934 if (tnum_is_const(reg->var_off) &&
2935 bpf_map_is_rdonly(map) &&
2936 map->ops->map_direct_value_addr) {
2937 int map_off = off + reg->var_off.value;
2938 u64 val = 0;
2939
2940 err = bpf_map_direct_read(map, map_off, size,
2941 &val);
2942 if (err)
2943 return err;
2944
2945 regs[value_regno].type = SCALAR_VALUE;
2946 __mark_reg_known(&regs[value_regno], val);
2947 } else {
2948 mark_reg_unknown(env, regs, value_regno);
2949 }
2950 }
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07002951 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01002952 enum bpf_reg_type reg_type = SCALAR_VALUE;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002953 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07002954
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002955 if (t == BPF_WRITE && value_regno >= 0 &&
2956 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002957 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002958 return -EACCES;
2959 }
Edward Creef1174f72017-08-07 15:26:19 +01002960
Daniel Borkmann58990d12018-06-07 17:40:03 +02002961 err = check_ctx_reg(env, reg, regno);
2962 if (err < 0)
2963 return err;
2964
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002965 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
2966 if (err)
2967 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002968 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01002969 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002970 * PTR_TO_PACKET[_META,_END]. In the latter
2971 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01002972 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002973 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002974 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002975 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002976 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002977 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002978 if (reg_type_may_be_null(reg_type))
2979 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01002980 /* A load of ctx field could have different
2981 * actual load size with the one encoded in the
2982 * insn. When the dst is PTR, it is for sure not
2983 * a sub-register.
2984 */
2985 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002986 if (reg_type == PTR_TO_BTF_ID)
2987 regs[value_regno].btf_id = btf_id;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002988 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002989 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002990 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002991
Edward Creef1174f72017-08-07 15:26:19 +01002992 } else if (reg->type == PTR_TO_STACK) {
Edward Creef1174f72017-08-07 15:26:19 +01002993 off += reg->var_off.value;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002994 err = check_stack_access(env, reg, off, size);
2995 if (err)
2996 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07002997
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002998 state = func(env, reg);
2999 err = update_stack_depth(env, state, off);
3000 if (err)
3001 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003002
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003003 if (t == BPF_WRITE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003004 err = check_stack_write(env, state, off, size,
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07003005 value_regno, insn_idx);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003006 else
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003007 err = check_stack_read(env, state, off, size,
3008 value_regno);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003009 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003010 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003011 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003012 return -EACCES;
3013 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003014 if (t == BPF_WRITE && value_regno >= 0 &&
3015 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003016 verbose(env, "R%d leaks addr into packet\n",
3017 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003018 return -EACCES;
3019 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08003020 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003021 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003022 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07003023 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3024 if (t == BPF_WRITE && value_regno >= 0 &&
3025 is_pointer_value(env, value_regno)) {
3026 verbose(env, "R%d leaks addr into flow keys\n",
3027 value_regno);
3028 return -EACCES;
3029 }
3030
3031 err = check_flow_keys_access(env, off, size);
3032 if (!err && t == BPF_READ && value_regno >= 0)
3033 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003034 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07003035 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003036 verbose(env, "R%d cannot write into %s\n",
3037 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07003038 return -EACCES;
3039 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003040 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07003041 if (!err && value_regno >= 0)
3042 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07003043 } else if (reg->type == PTR_TO_TP_BUFFER) {
3044 err = check_tp_buffer_access(env, reg, regno, off, size);
3045 if (!err && t == BPF_READ && value_regno >= 0)
3046 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003047 } else if (reg->type == PTR_TO_BTF_ID) {
3048 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3049 value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003050 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003051 verbose(env, "R%d invalid mem access '%s'\n", regno,
3052 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003053 return -EACCES;
3054 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003055
Edward Creef1174f72017-08-07 15:26:19 +01003056 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003057 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01003058 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08003059 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003060 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003061 return err;
3062}
3063
Yonghong Song31fd8582017-06-13 15:52:13 -07003064static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003065{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003066 int err;
3067
3068 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3069 insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003070 verbose(env, "BPF_XADD uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003071 return -EINVAL;
3072 }
3073
3074 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003075 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003076 if (err)
3077 return err;
3078
3079 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003080 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003081 if (err)
3082 return err;
3083
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003084 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003085 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003086 return -EACCES;
3087 }
3088
Daniel Borkmannca369602018-02-23 22:29:05 +01003089 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003090 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003091 is_flow_key_reg(env, insn->dst_reg) ||
3092 is_sk_reg(env, insn->dst_reg)) {
Daniel Borkmannca369602018-02-23 22:29:05 +01003093 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003094 insn->dst_reg,
3095 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003096 return -EACCES;
3097 }
3098
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003099 /* check whether atomic_add can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003100 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003101 BPF_SIZE(insn->code), BPF_READ, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003102 if (err)
3103 return err;
3104
3105 /* check whether atomic_add can write into the same memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003106 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003107 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003108}
3109
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003110static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3111 int off, int access_size,
3112 bool zero_size_allowed)
3113{
3114 struct bpf_reg_state *reg = reg_state(env, regno);
3115
3116 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3117 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3118 if (tnum_is_const(reg->var_off)) {
3119 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3120 regno, off, access_size);
3121 } else {
3122 char tn_buf[48];
3123
3124 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3125 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3126 regno, tn_buf, access_size);
3127 }
3128 return -EACCES;
3129 }
3130 return 0;
3131}
3132
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003133/* when register 'regno' is passed into function that will read 'access_size'
3134 * bytes from that pointer, make sure that it's within stack boundary
Edward Creef1174f72017-08-07 15:26:19 +01003135 * and all elements of stack are initialized.
3136 * Unlike most pointer bounds-checking functions, this one doesn't take an
3137 * 'off' argument, so it has to add in reg->off itself.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003138 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003139static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
Daniel Borkmann435faee12016-04-13 00:10:51 +02003140 int access_size, bool zero_size_allowed,
3141 struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003142{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003143 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003144 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003145 int err, min_off, max_off, i, j, slot, spi;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003146
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003147 if (reg->type != PTR_TO_STACK) {
Edward Creef1174f72017-08-07 15:26:19 +01003148 /* Allow zero-byte read from NULL, regardless of pointer type */
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003149 if (zero_size_allowed && access_size == 0 &&
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003150 register_is_null(reg))
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003151 return 0;
3152
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003153 verbose(env, "R%d type=%s expected=%s\n", regno,
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003154 reg_type_str[reg->type],
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003155 reg_type_str[PTR_TO_STACK]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003156 return -EACCES;
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003157 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003158
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003159 if (tnum_is_const(reg->var_off)) {
3160 min_off = max_off = reg->var_off.value + reg->off;
3161 err = __check_stack_boundary(env, regno, min_off, access_size,
3162 zero_size_allowed);
3163 if (err)
3164 return err;
3165 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07003166 /* Variable offset is prohibited for unprivileged mode for
3167 * simplicity since it requires corresponding support in
3168 * Spectre masking for stack ALU.
3169 * See also retrieve_ptr_limit().
3170 */
3171 if (!env->allow_ptr_leaks) {
3172 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01003173
Andrey Ignatov088ec262019-04-03 23:22:39 -07003174 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3175 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3176 regno, tn_buf);
3177 return -EACCES;
3178 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07003179 /* Only initialized buffer on stack is allowed to be accessed
3180 * with variable offset. With uninitialized buffer it's hard to
3181 * guarantee that whole memory is marked as initialized on
3182 * helper return since specific bounds are unknown what may
3183 * cause uninitialized stack leaking.
3184 */
3185 if (meta && meta->raw_mode)
3186 meta = NULL;
3187
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003188 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3189 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3190 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3191 regno);
3192 return -EACCES;
3193 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003194 min_off = reg->smin_value + reg->off;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003195 max_off = reg->smax_value + reg->off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003196 err = __check_stack_boundary(env, regno, min_off, access_size,
3197 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003198 if (err) {
3199 verbose(env, "R%d min value is outside of stack bound\n",
3200 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003201 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003202 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003203 err = __check_stack_boundary(env, regno, max_off, access_size,
3204 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003205 if (err) {
3206 verbose(env, "R%d max value is outside of stack bound\n",
3207 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003208 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003209 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003210 }
3211
Daniel Borkmann435faee12016-04-13 00:10:51 +02003212 if (meta && meta->raw_mode) {
3213 meta->access_size = access_size;
3214 meta->regno = regno;
3215 return 0;
3216 }
3217
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003218 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003219 u8 *stype;
3220
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003221 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003222 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003223 if (state->allocated_stack <= slot)
3224 goto err;
3225 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3226 if (*stype == STACK_MISC)
3227 goto mark;
3228 if (*stype == STACK_ZERO) {
3229 /* helper can write anything into the stack */
3230 *stype = STACK_MISC;
3231 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003232 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003233 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3234 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003235 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003236 for (j = 0; j < BPF_REG_SIZE; j++)
3237 state->stack[spi].slot_type[j] = STACK_MISC;
3238 goto mark;
3239 }
3240
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003241err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003242 if (tnum_is_const(reg->var_off)) {
3243 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3244 min_off, i - min_off, access_size);
3245 } else {
3246 char tn_buf[48];
3247
3248 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3249 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3250 tn_buf, i - min_off, access_size);
3251 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003252 return -EACCES;
3253mark:
3254 /* reading any byte out of 8-byte 'spill_slot' will cause
3255 * the whole slot to be marked as 'read'
3256 */
Edward Cree679c7822018-08-22 20:02:19 +01003257 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01003258 state->stack[spi].spilled_ptr.parent,
3259 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003260 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003261 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003262}
3263
Gianluca Borello06c1c042017-01-09 10:19:49 -08003264static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3265 int access_size, bool zero_size_allowed,
3266 struct bpf_call_arg_meta *meta)
3267{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003268 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08003269
Edward Creef1174f72017-08-07 15:26:19 +01003270 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08003271 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003272 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08003273 return check_packet_access(env, regno, reg->off, access_size,
3274 zero_size_allowed);
Gianluca Borello06c1c042017-01-09 10:19:49 -08003275 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02003276 if (check_map_access_type(env, regno, reg->off, access_size,
3277 meta && meta->raw_mode ? BPF_WRITE :
3278 BPF_READ))
3279 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003280 return check_map_access(env, regno, reg->off, access_size,
3281 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01003282 default: /* scalar_value|ptr_to_stack or invalid ptr */
Gianluca Borello06c1c042017-01-09 10:19:49 -08003283 return check_stack_boundary(env, regno, access_size,
3284 zero_size_allowed, meta);
3285 }
3286}
3287
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003288/* Implementation details:
3289 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3290 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3291 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3292 * value_or_null->value transition, since the verifier only cares about
3293 * the range of access to valid map value pointer and doesn't care about actual
3294 * address of the map element.
3295 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3296 * reg->id > 0 after value_or_null->value transition. By doing so
3297 * two bpf_map_lookups will be considered two different pointers that
3298 * point to different bpf_spin_locks.
3299 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3300 * dead-locks.
3301 * Since only one bpf_spin_lock is allowed the checks are simpler than
3302 * reg_is_refcounted() logic. The verifier needs to remember only
3303 * one spin_lock instead of array of acquired_refs.
3304 * cur_state->active_spin_lock remembers which map value element got locked
3305 * and clears it after bpf_spin_unlock.
3306 */
3307static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3308 bool is_lock)
3309{
3310 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3311 struct bpf_verifier_state *cur = env->cur_state;
3312 bool is_const = tnum_is_const(reg->var_off);
3313 struct bpf_map *map = reg->map_ptr;
3314 u64 val = reg->var_off.value;
3315
3316 if (reg->type != PTR_TO_MAP_VALUE) {
3317 verbose(env, "R%d is not a pointer to map_value\n", regno);
3318 return -EINVAL;
3319 }
3320 if (!is_const) {
3321 verbose(env,
3322 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3323 regno);
3324 return -EINVAL;
3325 }
3326 if (!map->btf) {
3327 verbose(env,
3328 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3329 map->name);
3330 return -EINVAL;
3331 }
3332 if (!map_value_has_spin_lock(map)) {
3333 if (map->spin_lock_off == -E2BIG)
3334 verbose(env,
3335 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3336 map->name);
3337 else if (map->spin_lock_off == -ENOENT)
3338 verbose(env,
3339 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3340 map->name);
3341 else
3342 verbose(env,
3343 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3344 map->name);
3345 return -EINVAL;
3346 }
3347 if (map->spin_lock_off != val + reg->off) {
3348 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3349 val + reg->off);
3350 return -EINVAL;
3351 }
3352 if (is_lock) {
3353 if (cur->active_spin_lock) {
3354 verbose(env,
3355 "Locking two bpf_spin_locks are not allowed\n");
3356 return -EINVAL;
3357 }
3358 cur->active_spin_lock = reg->id;
3359 } else {
3360 if (!cur->active_spin_lock) {
3361 verbose(env, "bpf_spin_unlock without taking a lock\n");
3362 return -EINVAL;
3363 }
3364 if (cur->active_spin_lock != reg->id) {
3365 verbose(env, "bpf_spin_unlock of different lock\n");
3366 return -EINVAL;
3367 }
3368 cur->active_spin_lock = 0;
3369 }
3370 return 0;
3371}
3372
Daniel Borkmann90133412018-01-20 01:24:29 +01003373static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3374{
3375 return type == ARG_PTR_TO_MEM ||
3376 type == ARG_PTR_TO_MEM_OR_NULL ||
3377 type == ARG_PTR_TO_UNINIT_MEM;
3378}
3379
3380static bool arg_type_is_mem_size(enum bpf_arg_type type)
3381{
3382 return type == ARG_CONST_SIZE ||
3383 type == ARG_CONST_SIZE_OR_ZERO;
3384}
3385
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003386static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3387{
3388 return type == ARG_PTR_TO_INT ||
3389 type == ARG_PTR_TO_LONG;
3390}
3391
3392static int int_ptr_type_to_size(enum bpf_arg_type type)
3393{
3394 if (type == ARG_PTR_TO_INT)
3395 return sizeof(u32);
3396 else if (type == ARG_PTR_TO_LONG)
3397 return sizeof(u64);
3398
3399 return -EINVAL;
3400}
3401
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003402static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
Daniel Borkmann33ff9822016-04-13 00:10:50 +02003403 enum bpf_arg_type arg_type,
3404 struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003405{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003406 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003407 enum bpf_reg_type expected_type, type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003408 int err = 0;
3409
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003410 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003411 return 0;
3412
Edward Creedc503a82017-08-15 20:34:35 +01003413 err = check_reg_arg(env, regno, SRC_OP);
3414 if (err)
3415 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003416
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003417 if (arg_type == ARG_ANYTHING) {
3418 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003419 verbose(env, "R%d leaks addr into helper function\n",
3420 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003421 return -EACCES;
3422 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003423 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003424 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003425
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003426 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003427 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003428 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003429 return -EACCES;
3430 }
3431
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003432 if (arg_type == ARG_PTR_TO_MAP_KEY ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003433 arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003434 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3435 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003436 expected_type = PTR_TO_STACK;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003437 if (register_is_null(reg) &&
3438 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
3439 /* final test in check_stack_boundary() */;
3440 else if (!type_is_pkt_pointer(type) &&
3441 type != PTR_TO_MAP_VALUE &&
3442 type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003443 goto err_type;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003444 } else if (arg_type == ARG_CONST_SIZE ||
3445 arg_type == ARG_CONST_SIZE_OR_ZERO) {
Edward Creef1174f72017-08-07 15:26:19 +01003446 expected_type = SCALAR_VALUE;
3447 if (type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003448 goto err_type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003449 } else if (arg_type == ARG_CONST_MAP_PTR) {
3450 expected_type = CONST_PTR_TO_MAP;
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003451 if (type != expected_type)
3452 goto err_type;
Daniel Borkmannf3189032020-03-27 16:58:52 +01003453 } else if (arg_type == ARG_PTR_TO_CTX ||
3454 arg_type == ARG_PTR_TO_CTX_OR_NULL) {
Alexei Starovoitov608cd712015-03-26 19:53:57 -07003455 expected_type = PTR_TO_CTX;
Daniel Borkmannf3189032020-03-27 16:58:52 +01003456 if (!(register_is_null(reg) &&
3457 arg_type == ARG_PTR_TO_CTX_OR_NULL)) {
3458 if (type != expected_type)
3459 goto err_type;
3460 err = check_ctx_reg(env, reg, regno);
3461 if (err < 0)
3462 return err;
3463 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003464 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
3465 expected_type = PTR_TO_SOCK_COMMON;
3466 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3467 if (!type_is_sk_pointer(type))
3468 goto err_type;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003469 if (reg->ref_obj_id) {
3470 if (meta->ref_obj_id) {
3471 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3472 regno, reg->ref_obj_id,
3473 meta->ref_obj_id);
3474 return -EFAULT;
3475 }
3476 meta->ref_obj_id = reg->ref_obj_id;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003477 }
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003478 } else if (arg_type == ARG_PTR_TO_SOCKET) {
3479 expected_type = PTR_TO_SOCKET;
3480 if (type != expected_type)
3481 goto err_type;
Alexei Starovoitova7658e12019-10-15 20:25:04 -07003482 } else if (arg_type == ARG_PTR_TO_BTF_ID) {
3483 expected_type = PTR_TO_BTF_ID;
3484 if (type != expected_type)
3485 goto err_type;
3486 if (reg->btf_id != meta->btf_id) {
3487 verbose(env, "Helper has type %s got %s in R%d\n",
3488 kernel_type_name(meta->btf_id),
3489 kernel_type_name(reg->btf_id), regno);
3490
3491 return -EACCES;
3492 }
3493 if (!tnum_is_const(reg->var_off) || reg->var_off.value || reg->off) {
3494 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
3495 regno);
3496 return -EACCES;
3497 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003498 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
3499 if (meta->func_id == BPF_FUNC_spin_lock) {
3500 if (process_spin_lock(env, regno, true))
3501 return -EACCES;
3502 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
3503 if (process_spin_lock(env, regno, false))
3504 return -EACCES;
3505 } else {
3506 verbose(env, "verifier internal error\n");
3507 return -EFAULT;
3508 }
Daniel Borkmann90133412018-01-20 01:24:29 +01003509 } else if (arg_type_is_mem_ptr(arg_type)) {
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003510 expected_type = PTR_TO_STACK;
3511 /* One exception here. In case function allows for NULL to be
Edward Creef1174f72017-08-07 15:26:19 +01003512 * passed in as argument, it's a SCALAR_VALUE type. Final test
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003513 * happens during stack boundary checking.
3514 */
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003515 if (register_is_null(reg) &&
Gianluca Borellodb1ac492017-11-22 18:32:53 +00003516 arg_type == ARG_PTR_TO_MEM_OR_NULL)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003517 /* final test in check_stack_boundary() */;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003518 else if (!type_is_pkt_pointer(type) &&
3519 type != PTR_TO_MAP_VALUE &&
Edward Creef1174f72017-08-07 15:26:19 +01003520 type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003521 goto err_type;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003522 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003523 } else if (arg_type_is_int_ptr(arg_type)) {
3524 expected_type = PTR_TO_STACK;
3525 if (!type_is_pkt_pointer(type) &&
3526 type != PTR_TO_MAP_VALUE &&
3527 type != expected_type)
3528 goto err_type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003529 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003530 verbose(env, "unsupported arg_type %d\n", arg_type);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003531 return -EFAULT;
3532 }
3533
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003534 if (arg_type == ARG_CONST_MAP_PTR) {
3535 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02003536 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003537 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
3538 /* bpf_map_xxx(..., map_ptr, ..., key) call:
3539 * check that [key, key + map->key_size) are within
3540 * stack limits and initialized
3541 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02003542 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003543 /* in function declaration map_ptr must come before
3544 * map_key, so that it's verified and known before
3545 * we have to check map_key here. Otherwise it means
3546 * that kernel subsystem misconfigured verifier
3547 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003548 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003549 return -EACCES;
3550 }
Paul Chaignond71962f2018-04-24 15:07:54 +02003551 err = check_helper_mem_access(env, regno,
3552 meta->map_ptr->key_size, false,
3553 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003554 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003555 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
3556 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003557 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003558 /* bpf_map_xxx(..., map_ptr, ..., value) call:
3559 * check [value, value + map->value_size) validity
3560 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02003561 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003562 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003563 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003564 return -EACCES;
3565 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003566 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02003567 err = check_helper_mem_access(env, regno,
3568 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003569 meta);
Daniel Borkmann90133412018-01-20 01:24:29 +01003570 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003571 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003572
John Fastabend10060502020-03-30 14:36:19 -07003573 /* This is used to refine r0 return value bounds for helpers
3574 * that enforce this value as an upper bound on return values.
3575 * See do_refine_retval_range() for helpers that can refine
3576 * the return value. C type of helper is u32 so we pull register
3577 * bound from umax_value however, if negative verifier errors
3578 * out. Only upper bounds can be learned because retval is an
3579 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07003580 */
John Fastabend10060502020-03-30 14:36:19 -07003581 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07003582
Edward Creef1174f72017-08-07 15:26:19 +01003583 /* The register is SCALAR_VALUE; the access check
3584 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08003585 */
Edward Creef1174f72017-08-07 15:26:19 +01003586 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08003587 /* For unprivileged variable accesses, disable raw
3588 * mode so that the program is required to
3589 * initialize all the memory that the helper could
3590 * just partially fill up.
3591 */
3592 meta = NULL;
3593
Edward Creeb03c9f92017-08-07 15:26:36 +01003594 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003595 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01003596 regno);
3597 return -EACCES;
3598 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08003599
Edward Creeb03c9f92017-08-07 15:26:36 +01003600 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01003601 err = check_helper_mem_access(env, regno - 1, 0,
3602 zero_size_allowed,
3603 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08003604 if (err)
3605 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08003606 }
Edward Creef1174f72017-08-07 15:26:19 +01003607
Edward Creeb03c9f92017-08-07 15:26:36 +01003608 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003609 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01003610 regno);
3611 return -EACCES;
3612 }
3613 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01003614 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01003615 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07003616 if (!err)
3617 err = mark_chain_precision(env, regno);
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003618 } else if (arg_type_is_int_ptr(arg_type)) {
3619 int size = int_ptr_type_to_size(arg_type);
3620
3621 err = check_helper_mem_access(env, regno, size, false, meta);
3622 if (err)
3623 return err;
3624 err = check_ptr_alignment(env, reg, 0, size, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003625 }
3626
3627 return err;
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003628err_type:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003629 verbose(env, "R%d type=%s expected=%s\n", regno,
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003630 reg_type_str[type], reg_type_str[expected_type]);
3631 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003632}
3633
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003634static int check_map_func_compatibility(struct bpf_verifier_env *env,
3635 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00003636{
Kaixu Xia35578d72015-08-06 07:02:35 +00003637 if (!map)
3638 return 0;
3639
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003640 /* We need a two way check, first is from map perspective ... */
3641 switch (map->map_type) {
3642 case BPF_MAP_TYPE_PROG_ARRAY:
3643 if (func_id != BPF_FUNC_tail_call)
3644 goto error;
3645 break;
3646 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
3647 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07003648 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07003649 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00003650 func_id != BPF_FUNC_perf_event_read_value &&
3651 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003652 goto error;
3653 break;
3654 case BPF_MAP_TYPE_STACK_TRACE:
3655 if (func_id != BPF_FUNC_get_stackid)
3656 goto error;
3657 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07003658 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04003659 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07003660 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07003661 goto error;
3662 break;
Roman Gushchincd339432018-08-02 14:27:24 -07003663 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00003664 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07003665 if (func_id != BPF_FUNC_get_local_storage)
3666 goto error;
3667 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07003668 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02003669 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02003670 if (func_id != BPF_FUNC_redirect_map &&
3671 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07003672 goto error;
3673 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02003674 /* Restrict bpf side of cpumap and xskmap, open when use-cases
3675 * appear.
3676 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02003677 case BPF_MAP_TYPE_CPUMAP:
3678 if (func_id != BPF_FUNC_redirect_map)
3679 goto error;
3680 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003681 case BPF_MAP_TYPE_XSKMAP:
3682 if (func_id != BPF_FUNC_redirect_map &&
3683 func_id != BPF_FUNC_map_lookup_elem)
3684 goto error;
3685 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07003686 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07003687 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07003688 if (func_id != BPF_FUNC_map_lookup_elem)
3689 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07003690 break;
John Fastabend174a79f2017-08-15 22:32:47 -07003691 case BPF_MAP_TYPE_SOCKMAP:
3692 if (func_id != BPF_FUNC_sk_redirect_map &&
3693 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07003694 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00003695 func_id != BPF_FUNC_msg_redirect_map &&
3696 func_id != BPF_FUNC_sk_select_reuseport)
John Fastabend174a79f2017-08-15 22:32:47 -07003697 goto error;
3698 break;
John Fastabend81110382018-05-14 10:00:17 -07003699 case BPF_MAP_TYPE_SOCKHASH:
3700 if (func_id != BPF_FUNC_sk_redirect_hash &&
3701 func_id != BPF_FUNC_sock_hash_update &&
3702 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00003703 func_id != BPF_FUNC_msg_redirect_hash &&
3704 func_id != BPF_FUNC_sk_select_reuseport)
John Fastabend81110382018-05-14 10:00:17 -07003705 goto error;
3706 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003707 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
3708 if (func_id != BPF_FUNC_sk_select_reuseport)
3709 goto error;
3710 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02003711 case BPF_MAP_TYPE_QUEUE:
3712 case BPF_MAP_TYPE_STACK:
3713 if (func_id != BPF_FUNC_map_peek_elem &&
3714 func_id != BPF_FUNC_map_pop_elem &&
3715 func_id != BPF_FUNC_map_push_elem)
3716 goto error;
3717 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003718 case BPF_MAP_TYPE_SK_STORAGE:
3719 if (func_id != BPF_FUNC_sk_storage_get &&
3720 func_id != BPF_FUNC_sk_storage_delete)
3721 goto error;
3722 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003723 default:
3724 break;
3725 }
3726
3727 /* ... and second from the function itself. */
3728 switch (func_id) {
3729 case BPF_FUNC_tail_call:
3730 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
3731 goto error;
Jiong Wangf910cef2018-05-02 16:17:17 -04003732 if (env->subprog_cnt > 1) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003733 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
3734 return -EINVAL;
3735 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003736 break;
3737 case BPF_FUNC_perf_event_read:
3738 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07003739 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07003740 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00003741 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003742 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
3743 goto error;
3744 break;
3745 case BPF_FUNC_get_stackid:
3746 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
3747 goto error;
3748 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07003749 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02003750 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07003751 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
3752 goto error;
3753 break;
John Fastabend97f91a72017-07-17 09:29:18 -07003754 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02003755 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02003756 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02003757 map->map_type != BPF_MAP_TYPE_CPUMAP &&
3758 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07003759 goto error;
3760 break;
John Fastabend174a79f2017-08-15 22:32:47 -07003761 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07003762 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07003763 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07003764 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
3765 goto error;
3766 break;
John Fastabend81110382018-05-14 10:00:17 -07003767 case BPF_FUNC_sk_redirect_hash:
3768 case BPF_FUNC_msg_redirect_hash:
3769 case BPF_FUNC_sock_hash_update:
3770 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07003771 goto error;
3772 break;
Roman Gushchincd339432018-08-02 14:27:24 -07003773 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00003774 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
3775 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07003776 goto error;
3777 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003778 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00003779 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
3780 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
3781 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003782 goto error;
3783 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02003784 case BPF_FUNC_map_peek_elem:
3785 case BPF_FUNC_map_pop_elem:
3786 case BPF_FUNC_map_push_elem:
3787 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
3788 map->map_type != BPF_MAP_TYPE_STACK)
3789 goto error;
3790 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003791 case BPF_FUNC_sk_storage_get:
3792 case BPF_FUNC_sk_storage_delete:
3793 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
3794 goto error;
3795 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003796 default:
3797 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00003798 }
3799
3800 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003801error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003802 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02003803 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003804 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00003805}
3806
Daniel Borkmann90133412018-01-20 01:24:29 +01003807static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003808{
3809 int count = 0;
3810
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003811 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003812 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003813 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003814 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003815 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003816 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003817 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003818 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003819 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003820 count++;
3821
Daniel Borkmann90133412018-01-20 01:24:29 +01003822 /* We only support one arg being in raw mode at the moment,
3823 * which is sufficient for the helper functions we have
3824 * right now.
3825 */
3826 return count <= 1;
3827}
3828
3829static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
3830 enum bpf_arg_type arg_next)
3831{
3832 return (arg_type_is_mem_ptr(arg_curr) &&
3833 !arg_type_is_mem_size(arg_next)) ||
3834 (!arg_type_is_mem_ptr(arg_curr) &&
3835 arg_type_is_mem_size(arg_next));
3836}
3837
3838static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
3839{
3840 /* bpf_xxx(..., buf, len) call will access 'len'
3841 * bytes from memory 'buf'. Both arg types need
3842 * to be paired, so make sure there's no buggy
3843 * helper function specification.
3844 */
3845 if (arg_type_is_mem_size(fn->arg1_type) ||
3846 arg_type_is_mem_ptr(fn->arg5_type) ||
3847 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
3848 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
3849 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
3850 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
3851 return false;
3852
3853 return true;
3854}
3855
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003856static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07003857{
3858 int count = 0;
3859
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003860 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003861 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003862 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003863 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003864 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003865 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003866 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003867 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003868 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003869 count++;
3870
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003871 /* A reference acquiring function cannot acquire
3872 * another refcounted ptr.
3873 */
3874 if (is_acquire_function(func_id) && count)
3875 return false;
3876
Joe Stringerfd978bf72018-10-02 13:35:35 -07003877 /* We only support one arg being unreferenced at the moment,
3878 * which is sufficient for the helper functions we have right now.
3879 */
3880 return count <= 1;
3881}
3882
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003883static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01003884{
3885 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07003886 check_arg_pair_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003887 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02003888}
3889
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003890/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
3891 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01003892 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003893static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
3894 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003895{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003896 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003897 int i;
3898
3899 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003900 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003901 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003902
Joe Stringerf3709f62018-10-02 13:35:29 -07003903 bpf_for_each_spilled_reg(i, state, reg) {
3904 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003905 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003906 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003907 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003908 }
3909}
3910
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003911static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
3912{
3913 struct bpf_verifier_state *vstate = env->cur_state;
3914 int i;
3915
3916 for (i = 0; i <= vstate->curframe; i++)
3917 __clear_all_pkt_pointers(env, vstate->frame[i]);
3918}
3919
Joe Stringerfd978bf72018-10-02 13:35:35 -07003920static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003921 struct bpf_func_state *state,
3922 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07003923{
3924 struct bpf_reg_state *regs = state->regs, *reg;
3925 int i;
3926
3927 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003928 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07003929 mark_reg_unknown(env, regs, i);
3930
3931 bpf_for_each_spilled_reg(i, state, reg) {
3932 if (!reg)
3933 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003934 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003935 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07003936 }
3937}
3938
3939/* The pointer with the specified id has released its reference to kernel
3940 * resources. Identify all copies of the same pointer and clear the reference.
3941 */
3942static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003943 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07003944{
3945 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003946 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003947 int i;
3948
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003949 err = release_reference_state(cur_func(env), ref_obj_id);
3950 if (err)
3951 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003952
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003953 for (i = 0; i <= vstate->curframe; i++)
3954 release_reg_references(env, vstate->frame[i], ref_obj_id);
3955
3956 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003957}
3958
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003959static void clear_caller_saved_regs(struct bpf_verifier_env *env,
3960 struct bpf_reg_state *regs)
3961{
3962 int i;
3963
3964 /* after the call registers r0 - r5 were scratched */
3965 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3966 mark_reg_not_init(env, regs, caller_saved[i]);
3967 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3968 }
3969}
3970
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003971static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
3972 int *insn_idx)
3973{
3974 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003975 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003976 struct bpf_func_state *caller, *callee;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003977 int i, err, subprog, target_insn;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003978 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003979
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08003980 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003981 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08003982 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003983 return -E2BIG;
3984 }
3985
3986 target_insn = *insn_idx + insn->imm;
3987 subprog = find_subprog(env, target_insn + 1);
3988 if (subprog < 0) {
3989 verbose(env, "verifier bug. No program starts at insn %d\n",
3990 target_insn + 1);
3991 return -EFAULT;
3992 }
3993
3994 caller = state->frame[state->curframe];
3995 if (state->frame[state->curframe + 1]) {
3996 verbose(env, "verifier bug. Frame %d already allocated\n",
3997 state->curframe + 1);
3998 return -EFAULT;
3999 }
4000
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004001 func_info_aux = env->prog->aux->func_info_aux;
4002 if (func_info_aux)
4003 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4004 err = btf_check_func_arg_match(env, subprog, caller->regs);
4005 if (err == -EFAULT)
4006 return err;
4007 if (is_global) {
4008 if (err) {
4009 verbose(env, "Caller passes invalid args into func#%d\n",
4010 subprog);
4011 return err;
4012 } else {
4013 if (env->log.level & BPF_LOG_LEVEL)
4014 verbose(env,
4015 "Func#%d is global and valid. Skipping.\n",
4016 subprog);
4017 clear_caller_saved_regs(env, caller->regs);
4018
4019 /* All global functions return SCALAR_VALUE */
4020 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4021
4022 /* continue with next insn after call */
4023 return 0;
4024 }
4025 }
4026
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004027 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4028 if (!callee)
4029 return -ENOMEM;
4030 state->frame[state->curframe + 1] = callee;
4031
4032 /* callee cannot access r0, r6 - r9 for reading and has to write
4033 * into its own stack before reading from it.
4034 * callee can read/write into caller's stack
4035 */
4036 init_func_state(env, callee,
4037 /* remember the callsite, it will be used by bpf_exit */
4038 *insn_idx /* callsite */,
4039 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04004040 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004041
Joe Stringerfd978bf72018-10-02 13:35:35 -07004042 /* Transfer references to the callee */
4043 err = transfer_reference_state(callee, caller);
4044 if (err)
4045 return err;
4046
Edward Cree679c7822018-08-22 20:02:19 +01004047 /* copy r1 - r5 args that callee can access. The copy includes parent
4048 * pointers, which connects us up to the liveness chain
4049 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004050 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4051 callee->regs[i] = caller->regs[i];
4052
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004053 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004054
4055 /* only increment it after check_reg_arg() finished */
4056 state->curframe++;
4057
4058 /* and go analyze first insn of the callee */
4059 *insn_idx = target_insn;
4060
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004061 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004062 verbose(env, "caller:\n");
4063 print_verifier_state(env, caller);
4064 verbose(env, "callee:\n");
4065 print_verifier_state(env, callee);
4066 }
4067 return 0;
4068}
4069
4070static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4071{
4072 struct bpf_verifier_state *state = env->cur_state;
4073 struct bpf_func_state *caller, *callee;
4074 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004075 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004076
4077 callee = state->frame[state->curframe];
4078 r0 = &callee->regs[BPF_REG_0];
4079 if (r0->type == PTR_TO_STACK) {
4080 /* technically it's ok to return caller's stack pointer
4081 * (or caller's caller's pointer) back to the caller,
4082 * since these pointers are valid. Only current stack
4083 * pointer will be invalid as soon as function exits,
4084 * but let's be conservative
4085 */
4086 verbose(env, "cannot return stack pointer to the caller\n");
4087 return -EINVAL;
4088 }
4089
4090 state->curframe--;
4091 caller = state->frame[state->curframe];
4092 /* return to the caller whatever r0 had in the callee */
4093 caller->regs[BPF_REG_0] = *r0;
4094
Joe Stringerfd978bf72018-10-02 13:35:35 -07004095 /* Transfer references to the caller */
4096 err = transfer_reference_state(caller, callee);
4097 if (err)
4098 return err;
4099
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004100 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004101 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004102 verbose(env, "returning from callee:\n");
4103 print_verifier_state(env, callee);
4104 verbose(env, "to caller at %d:\n", *insn_idx);
4105 print_verifier_state(env, caller);
4106 }
4107 /* clear everything in the callee */
4108 free_func_state(callee);
4109 state->frame[state->curframe + 1] = NULL;
4110 return 0;
4111}
4112
Yonghong Song849fa502018-04-28 22:28:09 -07004113static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4114 int func_id,
4115 struct bpf_call_arg_meta *meta)
4116{
4117 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4118
4119 if (ret_type != RET_INTEGER ||
4120 (func_id != BPF_FUNC_get_stack &&
4121 func_id != BPF_FUNC_probe_read_str))
4122 return;
4123
John Fastabend10060502020-03-30 14:36:19 -07004124 ret_reg->smax_value = meta->msize_max_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004125 __reg_deduce_bounds(ret_reg);
4126 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07004127 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07004128}
4129
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004130static int
4131record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4132 int func_id, int insn_idx)
4133{
4134 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02004135 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004136
4137 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02004138 func_id != BPF_FUNC_map_lookup_elem &&
4139 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004140 func_id != BPF_FUNC_map_delete_elem &&
4141 func_id != BPF_FUNC_map_push_elem &&
4142 func_id != BPF_FUNC_map_pop_elem &&
4143 func_id != BPF_FUNC_map_peek_elem)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004144 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02004145
Daniel Borkmann591fe982019-04-09 23:20:05 +02004146 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004147 verbose(env, "kernel subsystem misconfigured verifier\n");
4148 return -EINVAL;
4149 }
4150
Daniel Borkmann591fe982019-04-09 23:20:05 +02004151 /* In case of read-only, some additional restrictions
4152 * need to be applied in order to prevent altering the
4153 * state of the map from program side.
4154 */
4155 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4156 (func_id == BPF_FUNC_map_delete_elem ||
4157 func_id == BPF_FUNC_map_update_elem ||
4158 func_id == BPF_FUNC_map_push_elem ||
4159 func_id == BPF_FUNC_map_pop_elem)) {
4160 verbose(env, "write into map forbidden\n");
4161 return -EACCES;
4162 }
4163
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004164 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004165 bpf_map_ptr_store(aux, meta->map_ptr,
4166 meta->map_ptr->unpriv_array);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004167 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004168 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
4169 meta->map_ptr->unpriv_array);
4170 return 0;
4171}
4172
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004173static int
4174record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4175 int func_id, int insn_idx)
4176{
4177 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4178 struct bpf_reg_state *regs = cur_regs(env), *reg;
4179 struct bpf_map *map = meta->map_ptr;
4180 struct tnum range;
4181 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004182 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004183
4184 if (func_id != BPF_FUNC_tail_call)
4185 return 0;
4186 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4187 verbose(env, "kernel subsystem misconfigured verifier\n");
4188 return -EINVAL;
4189 }
4190
4191 range = tnum_range(0, map->max_entries - 1);
4192 reg = &regs[BPF_REG_3];
4193
4194 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4195 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4196 return 0;
4197 }
4198
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004199 err = mark_chain_precision(env, BPF_REG_3);
4200 if (err)
4201 return err;
4202
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004203 val = reg->var_off.value;
4204 if (bpf_map_key_unseen(aux))
4205 bpf_map_key_store(aux, val);
4206 else if (!bpf_map_key_poisoned(aux) &&
4207 bpf_map_key_immediate(aux) != val)
4208 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4209 return 0;
4210}
4211
Joe Stringerfd978bf72018-10-02 13:35:35 -07004212static int check_reference_leak(struct bpf_verifier_env *env)
4213{
4214 struct bpf_func_state *state = cur_func(env);
4215 int i;
4216
4217 for (i = 0; i < state->acquired_refs; i++) {
4218 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4219 state->refs[i].id, state->refs[i].insn_idx);
4220 }
4221 return state->acquired_refs ? -EINVAL : 0;
4222}
4223
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004224static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004225{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004226 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004227 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004228 struct bpf_call_arg_meta meta;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004229 bool changes_data;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004230 int i, err;
4231
4232 /* find function prototype */
4233 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004234 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4235 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004236 return -EINVAL;
4237 }
4238
Jakub Kicinski00176a32017-10-16 16:40:54 -07004239 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07004240 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004241 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004242 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4243 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004244 return -EINVAL;
4245 }
4246
4247 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01004248 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02004249 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004250 return -EINVAL;
4251 }
4252
Daniel Borkmann04514d12017-12-14 21:07:25 +01004253 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08004254 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01004255 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4256 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4257 func_id_name(func_id), func_id);
4258 return -EINVAL;
4259 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004260
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004261 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02004262 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004263
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004264 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004265 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004266 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004267 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004268 return err;
4269 }
4270
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004271 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004272 /* check args */
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004273 for (i = 0; i < 5; i++) {
Alexei Starovoitov9cc31b32019-11-14 10:57:14 -08004274 err = btf_resolve_helper_id(&env->log, fn, i);
4275 if (err > 0)
4276 meta.btf_id = err;
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004277 err = check_func_arg(env, BPF_REG_1 + i, fn->arg_type[i], &meta);
4278 if (err)
4279 return err;
4280 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004281
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004282 err = record_func_map(env, &meta, func_id, insn_idx);
4283 if (err)
4284 return err;
4285
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004286 err = record_func_key(env, &meta, func_id, insn_idx);
4287 if (err)
4288 return err;
4289
Daniel Borkmann435faee12016-04-13 00:10:51 +02004290 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4291 * is inferred from register state.
4292 */
4293 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01004294 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4295 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004296 if (err)
4297 return err;
4298 }
4299
Joe Stringerfd978bf72018-10-02 13:35:35 -07004300 if (func_id == BPF_FUNC_tail_call) {
4301 err = check_reference_leak(env);
4302 if (err) {
4303 verbose(env, "tail_call would lead to reference leak\n");
4304 return err;
4305 }
4306 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004307 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004308 if (err) {
4309 verbose(env, "func %s#%d reference has not been acquired before\n",
4310 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07004311 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004312 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07004313 }
4314
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004315 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07004316
4317 /* check that flags argument in get_local_storage(map, flags) is 0,
4318 * this is required because get_local_storage() can't return an error.
4319 */
4320 if (func_id == BPF_FUNC_get_local_storage &&
4321 !register_is_null(&regs[BPF_REG_2])) {
4322 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4323 return -EINVAL;
4324 }
4325
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004326 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01004327 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004328 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01004329 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4330 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004331
Jiong Wang5327ed32019-05-24 23:25:12 +01004332 /* helper call returns 64-bit value. */
4333 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4334
Edward Creedc503a82017-08-15 20:34:35 +01004335 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004336 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01004337 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004338 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004339 } else if (fn->ret_type == RET_VOID) {
4340 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07004341 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4342 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01004343 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004344 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004345 /* remember map_ptr, so that check_map_access()
4346 * can check 'value_size' boundary of memory access
4347 * to map element returned from bpf_map_lookup_elem()
4348 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004349 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004350 verbose(env,
4351 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004352 return -EINVAL;
4353 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004354 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01004355 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4356 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08004357 if (map_value_has_spin_lock(meta.map_ptr))
4358 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01004359 } else {
4360 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4361 regs[BPF_REG_0].id = ++env->id_gen;
4362 }
Joe Stringerc64b7982018-10-02 13:35:33 -07004363 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4364 mark_reg_known_zero(env, regs, BPF_REG_0);
4365 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08004366 regs[BPF_REG_0].id = ++env->id_gen;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08004367 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4368 mark_reg_known_zero(env, regs, BPF_REG_0);
4369 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4370 regs[BPF_REG_0].id = ++env->id_gen;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08004371 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4372 mark_reg_known_zero(env, regs, BPF_REG_0);
4373 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4374 regs[BPF_REG_0].id = ++env->id_gen;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004375 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004376 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004377 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004378 return -EINVAL;
4379 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07004380
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08004381 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004382 /* For release_reference() */
4383 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08004384 } else if (is_acquire_function(func_id)) {
4385 int id = acquire_reference_state(env, insn_idx);
4386
4387 if (id < 0)
4388 return id;
4389 /* For mark_ptr_or_null_reg() */
4390 regs[BPF_REG_0].id = id;
4391 /* For release_reference() */
4392 regs[BPF_REG_0].ref_obj_id = id;
4393 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004394
Yonghong Song849fa502018-04-28 22:28:09 -07004395 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
4396
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004397 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00004398 if (err)
4399 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07004400
Yonghong Songc195651e2018-04-28 22:28:08 -07004401 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
4402 const char *err_str;
4403
4404#ifdef CONFIG_PERF_EVENTS
4405 err = get_callchain_buffers(sysctl_perf_event_max_stack);
4406 err_str = "cannot get callchain buffer for func %s#%d\n";
4407#else
4408 err = -ENOTSUPP;
4409 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4410#endif
4411 if (err) {
4412 verbose(env, err_str, func_id_name(func_id), func_id);
4413 return err;
4414 }
4415
4416 env->prog->has_callchain_buf = true;
4417 }
4418
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004419 if (changes_data)
4420 clear_all_pkt_pointers(env);
4421 return 0;
4422}
4423
Edward Creeb03c9f92017-08-07 15:26:36 +01004424static bool signed_add_overflows(s64 a, s64 b)
4425{
4426 /* Do the add in u64, where overflow is well-defined */
4427 s64 res = (s64)((u64)a + (u64)b);
4428
4429 if (b < 0)
4430 return res > a;
4431 return res < a;
4432}
4433
4434static bool signed_sub_overflows(s64 a, s64 b)
4435{
4436 /* Do the sub in u64, where overflow is well-defined */
4437 s64 res = (s64)((u64)a - (u64)b);
4438
4439 if (b < 0)
4440 return res < a;
4441 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07004442}
4443
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08004444static bool check_reg_sane_offset(struct bpf_verifier_env *env,
4445 const struct bpf_reg_state *reg,
4446 enum bpf_reg_type type)
4447{
4448 bool known = tnum_is_const(reg->var_off);
4449 s64 val = reg->var_off.value;
4450 s64 smin = reg->smin_value;
4451
4452 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
4453 verbose(env, "math between %s pointer and %lld is not allowed\n",
4454 reg_type_str[type], val);
4455 return false;
4456 }
4457
4458 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
4459 verbose(env, "%s pointer offset %d is not allowed\n",
4460 reg_type_str[type], reg->off);
4461 return false;
4462 }
4463
4464 if (smin == S64_MIN) {
4465 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
4466 reg_type_str[type]);
4467 return false;
4468 }
4469
4470 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
4471 verbose(env, "value %lld makes %s pointer be out of bounds\n",
4472 smin, reg_type_str[type]);
4473 return false;
4474 }
4475
4476 return true;
4477}
4478
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004479static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
4480{
4481 return &env->insn_aux_data[env->insn_idx];
4482}
4483
4484static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
4485 u32 *ptr_limit, u8 opcode, bool off_is_neg)
4486{
4487 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
4488 (opcode == BPF_SUB && !off_is_neg);
4489 u32 off;
4490
4491 switch (ptr_reg->type) {
4492 case PTR_TO_STACK:
Andrey Ignatov088ec262019-04-03 23:22:39 -07004493 /* Indirect variable offset stack access is prohibited in
4494 * unprivileged mode so it's not handled here.
4495 */
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004496 off = ptr_reg->off + ptr_reg->var_off.value;
4497 if (mask_to_left)
4498 *ptr_limit = MAX_BPF_STACK + off;
4499 else
4500 *ptr_limit = -off;
4501 return 0;
4502 case PTR_TO_MAP_VALUE:
4503 if (mask_to_left) {
4504 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
4505 } else {
4506 off = ptr_reg->smin_value + ptr_reg->off;
4507 *ptr_limit = ptr_reg->map_ptr->value_size - off;
4508 }
4509 return 0;
4510 default:
4511 return -EINVAL;
4512 }
4513}
4514
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01004515static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
4516 const struct bpf_insn *insn)
4517{
4518 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
4519}
4520
4521static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
4522 u32 alu_state, u32 alu_limit)
4523{
4524 /* If we arrived here from different branches with different
4525 * state or limits to sanitize, then this won't work.
4526 */
4527 if (aux->alu_state &&
4528 (aux->alu_state != alu_state ||
4529 aux->alu_limit != alu_limit))
4530 return -EACCES;
4531
4532 /* Corresponding fixup done in fixup_bpf_calls(). */
4533 aux->alu_state = alu_state;
4534 aux->alu_limit = alu_limit;
4535 return 0;
4536}
4537
4538static int sanitize_val_alu(struct bpf_verifier_env *env,
4539 struct bpf_insn *insn)
4540{
4541 struct bpf_insn_aux_data *aux = cur_aux(env);
4542
4543 if (can_skip_alu_sanitation(env, insn))
4544 return 0;
4545
4546 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
4547}
4548
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004549static int sanitize_ptr_alu(struct bpf_verifier_env *env,
4550 struct bpf_insn *insn,
4551 const struct bpf_reg_state *ptr_reg,
4552 struct bpf_reg_state *dst_reg,
4553 bool off_is_neg)
4554{
4555 struct bpf_verifier_state *vstate = env->cur_state;
4556 struct bpf_insn_aux_data *aux = cur_aux(env);
4557 bool ptr_is_dst_reg = ptr_reg == dst_reg;
4558 u8 opcode = BPF_OP(insn->code);
4559 u32 alu_state, alu_limit;
4560 struct bpf_reg_state tmp;
4561 bool ret;
4562
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01004563 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004564 return 0;
4565
4566 /* We already marked aux for masking from non-speculative
4567 * paths, thus we got here in the first place. We only care
4568 * to explore bad access from here.
4569 */
4570 if (vstate->speculative)
4571 goto do_sim;
4572
4573 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
4574 alu_state |= ptr_is_dst_reg ?
4575 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
4576
4577 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
4578 return 0;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01004579 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004580 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004581do_sim:
4582 /* Simulate and find potential out-of-bounds access under
4583 * speculative execution from truncation as a result of
4584 * masking when off was not within expected range. If off
4585 * sits in dst, then we temporarily need to move ptr there
4586 * to simulate dst (== 0) +/-= ptr. Needed, for example,
4587 * for cases where we use K-based arithmetic in one direction
4588 * and truncated reg-based in the other in order to explore
4589 * bad access.
4590 */
4591 if (!ptr_is_dst_reg) {
4592 tmp = *dst_reg;
4593 *dst_reg = *ptr_reg;
4594 }
4595 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08004596 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004597 *dst_reg = tmp;
4598 return !ret ? -EFAULT : 0;
4599}
4600
Edward Creef1174f72017-08-07 15:26:19 +01004601/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01004602 * Caller should also handle BPF_MOV case separately.
4603 * If we return -EACCES, caller may want to try again treating pointer as a
4604 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
4605 */
4606static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
4607 struct bpf_insn *insn,
4608 const struct bpf_reg_state *ptr_reg,
4609 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04004610{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004611 struct bpf_verifier_state *vstate = env->cur_state;
4612 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4613 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01004614 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01004615 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
4616 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
4617 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
4618 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01004619 u32 dst = insn->dst_reg, src = insn->src_reg;
Josef Bacik48461132016-09-28 10:54:32 -04004620 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004621 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04004622
Edward Creef1174f72017-08-07 15:26:19 +01004623 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04004624
Daniel Borkmann6f161012018-01-18 01:15:21 +01004625 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
4626 smin_val > smax_val || umin_val > umax_val) {
4627 /* Taint dst register if offset had invalid bounds derived from
4628 * e.g. dead branches.
4629 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01004630 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01004631 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04004632 }
4633
Edward Creef1174f72017-08-07 15:26:19 +01004634 if (BPF_CLASS(insn->code) != BPF_ALU64) {
4635 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004636 verbose(env,
4637 "R%d 32-bit pointer arithmetic prohibited\n",
4638 dst);
Edward Creef1174f72017-08-07 15:26:19 +01004639 return -EACCES;
4640 }
David S. Millerd1174412017-05-10 11:22:52 -07004641
Joe Stringeraad2eea2018-10-02 13:35:30 -07004642 switch (ptr_reg->type) {
4643 case PTR_TO_MAP_VALUE_OR_NULL:
4644 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
4645 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01004646 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07004647 case CONST_PTR_TO_MAP:
4648 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07004649 case PTR_TO_SOCKET:
4650 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004651 case PTR_TO_SOCK_COMMON:
4652 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08004653 case PTR_TO_TCP_SOCK:
4654 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07004655 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07004656 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
4657 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01004658 return -EACCES;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01004659 case PTR_TO_MAP_VALUE:
4660 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
4661 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
4662 off_reg == dst_reg ? dst : src);
4663 return -EACCES;
4664 }
4665 /* fall-through */
Joe Stringeraad2eea2018-10-02 13:35:30 -07004666 default:
4667 break;
Edward Creef1174f72017-08-07 15:26:19 +01004668 }
4669
4670 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
4671 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04004672 */
Edward Creef1174f72017-08-07 15:26:19 +01004673 dst_reg->type = ptr_reg->type;
4674 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05004675
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08004676 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
4677 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
4678 return -EINVAL;
4679
Josef Bacik48461132016-09-28 10:54:32 -04004680 switch (opcode) {
4681 case BPF_ADD:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004682 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4683 if (ret < 0) {
4684 verbose(env, "R%d tried to add from different maps or paths\n", dst);
4685 return ret;
4686 }
Edward Creef1174f72017-08-07 15:26:19 +01004687 /* We can take a fixed offset as long as it doesn't overflow
4688 * the s32 'off' field
4689 */
Edward Creeb03c9f92017-08-07 15:26:36 +01004690 if (known && (ptr_reg->off + smin_val ==
4691 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01004692 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01004693 dst_reg->smin_value = smin_ptr;
4694 dst_reg->smax_value = smax_ptr;
4695 dst_reg->umin_value = umin_ptr;
4696 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01004697 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01004698 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01004699 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01004700 break;
4701 }
Edward Creef1174f72017-08-07 15:26:19 +01004702 /* A new variable offset is created. Note that off_reg->off
4703 * == 0, since it's a scalar.
4704 * dst_reg gets the pointer type and since some positive
4705 * integer value was added to the pointer, give it a new 'id'
4706 * if it's a PTR_TO_PACKET.
4707 * this creates a new 'base' pointer, off_reg (variable) gets
4708 * added into the variable offset, and we copy the fixed offset
4709 * from ptr_reg.
4710 */
Edward Creeb03c9f92017-08-07 15:26:36 +01004711 if (signed_add_overflows(smin_ptr, smin_val) ||
4712 signed_add_overflows(smax_ptr, smax_val)) {
4713 dst_reg->smin_value = S64_MIN;
4714 dst_reg->smax_value = S64_MAX;
4715 } else {
4716 dst_reg->smin_value = smin_ptr + smin_val;
4717 dst_reg->smax_value = smax_ptr + smax_val;
4718 }
4719 if (umin_ptr + umin_val < umin_ptr ||
4720 umax_ptr + umax_val < umax_ptr) {
4721 dst_reg->umin_value = 0;
4722 dst_reg->umax_value = U64_MAX;
4723 } else {
4724 dst_reg->umin_value = umin_ptr + umin_val;
4725 dst_reg->umax_value = umax_ptr + umax_val;
4726 }
Edward Creef1174f72017-08-07 15:26:19 +01004727 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
4728 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01004729 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004730 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01004731 dst_reg->id = ++env->id_gen;
4732 /* something was added to pkt_ptr, set range to zero */
Daniel Borkmann09625902018-11-01 00:05:52 +01004733 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01004734 }
Josef Bacik48461132016-09-28 10:54:32 -04004735 break;
4736 case BPF_SUB:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004737 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4738 if (ret < 0) {
4739 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
4740 return ret;
4741 }
Edward Creef1174f72017-08-07 15:26:19 +01004742 if (dst_reg == off_reg) {
4743 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004744 verbose(env, "R%d tried to subtract pointer from scalar\n",
4745 dst);
Edward Creef1174f72017-08-07 15:26:19 +01004746 return -EACCES;
4747 }
4748 /* We don't allow subtraction from FP, because (according to
4749 * test_verifier.c test "invalid fp arithmetic", JITs might not
4750 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01004751 */
Edward Creef1174f72017-08-07 15:26:19 +01004752 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004753 verbose(env, "R%d subtraction from stack pointer prohibited\n",
4754 dst);
Edward Creef1174f72017-08-07 15:26:19 +01004755 return -EACCES;
4756 }
Edward Creeb03c9f92017-08-07 15:26:36 +01004757 if (known && (ptr_reg->off - smin_val ==
4758 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01004759 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01004760 dst_reg->smin_value = smin_ptr;
4761 dst_reg->smax_value = smax_ptr;
4762 dst_reg->umin_value = umin_ptr;
4763 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01004764 dst_reg->var_off = ptr_reg->var_off;
4765 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01004766 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01004767 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01004768 break;
4769 }
Edward Creef1174f72017-08-07 15:26:19 +01004770 /* A new variable offset is created. If the subtrahend is known
4771 * nonnegative, then any reg->range we had before is still good.
4772 */
Edward Creeb03c9f92017-08-07 15:26:36 +01004773 if (signed_sub_overflows(smin_ptr, smax_val) ||
4774 signed_sub_overflows(smax_ptr, smin_val)) {
4775 /* Overflow possible, we know nothing */
4776 dst_reg->smin_value = S64_MIN;
4777 dst_reg->smax_value = S64_MAX;
4778 } else {
4779 dst_reg->smin_value = smin_ptr - smax_val;
4780 dst_reg->smax_value = smax_ptr - smin_val;
4781 }
4782 if (umin_ptr < umax_val) {
4783 /* Overflow possible, we know nothing */
4784 dst_reg->umin_value = 0;
4785 dst_reg->umax_value = U64_MAX;
4786 } else {
4787 /* Cannot overflow (as long as bounds are consistent) */
4788 dst_reg->umin_value = umin_ptr - umax_val;
4789 dst_reg->umax_value = umax_ptr - umin_val;
4790 }
Edward Creef1174f72017-08-07 15:26:19 +01004791 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
4792 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01004793 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004794 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01004795 dst_reg->id = ++env->id_gen;
4796 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01004797 if (smin_val < 0)
Daniel Borkmann09625902018-11-01 00:05:52 +01004798 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01004799 }
4800 break;
4801 case BPF_AND:
4802 case BPF_OR:
4803 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004804 /* bitwise ops on pointers are troublesome, prohibit. */
4805 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
4806 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01004807 return -EACCES;
4808 default:
4809 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004810 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
4811 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01004812 return -EACCES;
4813 }
4814
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08004815 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
4816 return -EINVAL;
4817
Edward Creeb03c9f92017-08-07 15:26:36 +01004818 __update_reg_bounds(dst_reg);
4819 __reg_deduce_bounds(dst_reg);
4820 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01004821
4822 /* For unprivileged we require that resulting offset must be in bounds
4823 * in order to be able to sanitize access later on.
4824 */
Daniel Borkmanne4298d22019-01-03 00:58:31 +01004825 if (!env->allow_ptr_leaks) {
4826 if (dst_reg->type == PTR_TO_MAP_VALUE &&
4827 check_map_access(env, dst, dst_reg->off, 1, false)) {
4828 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
4829 "prohibited for !root\n", dst);
4830 return -EACCES;
4831 } else if (dst_reg->type == PTR_TO_STACK &&
4832 check_stack_access(env, dst_reg, dst_reg->off +
4833 dst_reg->var_off.value, 1)) {
4834 verbose(env, "R%d stack pointer arithmetic goes out of range, "
4835 "prohibited for !root\n", dst);
4836 return -EACCES;
4837 }
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01004838 }
4839
Edward Creef1174f72017-08-07 15:26:19 +01004840 return 0;
4841}
4842
John Fastabend07cd2632020-03-24 10:38:15 -07004843static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
4844 struct bpf_reg_state *src_reg)
4845{
4846 s64 smin_val = src_reg->smin_value;
4847 s64 smax_val = src_reg->smax_value;
4848 u64 umin_val = src_reg->umin_value;
4849 u64 umax_val = src_reg->umax_value;
4850
4851 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
4852 signed_add_overflows(dst_reg->smax_value, smax_val)) {
4853 dst_reg->smin_value = S64_MIN;
4854 dst_reg->smax_value = S64_MAX;
4855 } else {
4856 dst_reg->smin_value += smin_val;
4857 dst_reg->smax_value += smax_val;
4858 }
4859 if (dst_reg->umin_value + umin_val < umin_val ||
4860 dst_reg->umax_value + umax_val < umax_val) {
4861 dst_reg->umin_value = 0;
4862 dst_reg->umax_value = U64_MAX;
4863 } else {
4864 dst_reg->umin_value += umin_val;
4865 dst_reg->umax_value += umax_val;
4866 }
4867 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg->var_off);
4868}
4869
4870static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
4871 struct bpf_reg_state *src_reg)
4872{
4873 s64 smin_val = src_reg->smin_value;
4874 s64 smax_val = src_reg->smax_value;
4875 u64 umin_val = src_reg->umin_value;
4876 u64 umax_val = src_reg->umax_value;
4877
4878 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
4879 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
4880 /* Overflow possible, we know nothing */
4881 dst_reg->smin_value = S64_MIN;
4882 dst_reg->smax_value = S64_MAX;
4883 } else {
4884 dst_reg->smin_value -= smax_val;
4885 dst_reg->smax_value -= smin_val;
4886 }
4887 if (dst_reg->umin_value < umax_val) {
4888 /* Overflow possible, we know nothing */
4889 dst_reg->umin_value = 0;
4890 dst_reg->umax_value = U64_MAX;
4891 } else {
4892 /* Cannot overflow (as long as bounds are consistent) */
4893 dst_reg->umin_value -= umax_val;
4894 dst_reg->umax_value -= umin_val;
4895 }
4896 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg->var_off);
4897}
4898
4899static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
4900 struct bpf_reg_state *src_reg)
4901{
4902 s64 smin_val = src_reg->smin_value;
4903 u64 umin_val = src_reg->umin_value;
4904 u64 umax_val = src_reg->umax_value;
4905
4906 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg->var_off);
4907 if (smin_val < 0 || dst_reg->smin_value < 0) {
4908 /* Ain't nobody got time to multiply that sign */
4909 __mark_reg_unbounded(dst_reg);
4910 __update_reg_bounds(dst_reg);
4911 return;
4912 }
4913 /* Both values are positive, so we can work with unsigned and
4914 * copy the result to signed (unless it exceeds S64_MAX).
4915 */
4916 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
4917 /* Potential overflow, we know nothing */
4918 __mark_reg_unbounded(dst_reg);
4919 /* (except what we can learn from the var_off) */
4920 __update_reg_bounds(dst_reg);
4921 return;
4922 }
4923 dst_reg->umin_value *= umin_val;
4924 dst_reg->umax_value *= umax_val;
4925 if (dst_reg->umax_value > S64_MAX) {
4926 /* Overflow possible, we know nothing */
4927 dst_reg->smin_value = S64_MIN;
4928 dst_reg->smax_value = S64_MAX;
4929 } else {
4930 dst_reg->smin_value = dst_reg->umin_value;
4931 dst_reg->smax_value = dst_reg->umax_value;
4932 }
4933}
4934
4935static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
4936 struct bpf_reg_state *src_reg)
4937{
4938 s64 smin_val = src_reg->smin_value;
4939 u64 umax_val = src_reg->umax_value;
4940
4941 /* We get our minimum from the var_off, since that's inherently
4942 * bitwise. Our maximum is the minimum of the operands' maxima.
4943 */
4944 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg->var_off);
4945 dst_reg->umin_value = dst_reg->var_off.value;
4946 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
4947 if (dst_reg->smin_value < 0 || smin_val < 0) {
4948 /* Lose signed bounds when ANDing negative numbers,
4949 * ain't nobody got time for that.
4950 */
4951 dst_reg->smin_value = S64_MIN;
4952 dst_reg->smax_value = S64_MAX;
4953 } else {
4954 /* ANDing two positives gives a positive, so safe to
4955 * cast result into s64.
4956 */
4957 dst_reg->smin_value = dst_reg->umin_value;
4958 dst_reg->smax_value = dst_reg->umax_value;
4959 }
4960 /* We may learn something more from the var_off */
4961 __update_reg_bounds(dst_reg);
4962}
4963
4964static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
4965 struct bpf_reg_state *src_reg)
4966{
4967 s64 smin_val = src_reg->smin_value;
4968 u64 umin_val = src_reg->umin_value;
4969
4970 /* We get our maximum from the var_off, and our minimum is the
4971 * maximum of the operands' minima
4972 */
4973 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg->var_off);
4974 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
4975 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
4976 if (dst_reg->smin_value < 0 || smin_val < 0) {
4977 /* Lose signed bounds when ORing negative numbers,
4978 * ain't nobody got time for that.
4979 */
4980 dst_reg->smin_value = S64_MIN;
4981 dst_reg->smax_value = S64_MAX;
4982 } else {
4983 /* ORing two positives gives a positive, so safe to
4984 * cast result into s64.
4985 */
4986 dst_reg->smin_value = dst_reg->umin_value;
4987 dst_reg->smax_value = dst_reg->umax_value;
4988 }
4989 /* We may learn something more from the var_off */
4990 __update_reg_bounds(dst_reg);
4991}
4992
4993static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
4994 struct bpf_reg_state *src_reg)
4995{
4996 u64 umax_val = src_reg->umax_value;
4997 u64 umin_val = src_reg->umin_value;
4998
4999 /* We lose all sign bit information (except what we can pick
5000 * up from var_off)
5001 */
5002 dst_reg->smin_value = S64_MIN;
5003 dst_reg->smax_value = S64_MAX;
5004 /* If we might shift our top bit out, then we know nothing */
5005 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
5006 dst_reg->umin_value = 0;
5007 dst_reg->umax_value = U64_MAX;
5008 } else {
5009 dst_reg->umin_value <<= umin_val;
5010 dst_reg->umax_value <<= umax_val;
5011 }
5012 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
5013 /* We may learn something more from the var_off */
5014 __update_reg_bounds(dst_reg);
5015}
5016
5017static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
5018 struct bpf_reg_state *src_reg)
5019{
5020 u64 umax_val = src_reg->umax_value;
5021 u64 umin_val = src_reg->umin_value;
5022
5023 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
5024 * be negative, then either:
5025 * 1) src_reg might be zero, so the sign bit of the result is
5026 * unknown, so we lose our signed bounds
5027 * 2) it's known negative, thus the unsigned bounds capture the
5028 * signed bounds
5029 * 3) the signed bounds cross zero, so they tell us nothing
5030 * about the result
5031 * If the value in dst_reg is known nonnegative, then again the
5032 * unsigned bounts capture the signed bounds.
5033 * Thus, in all cases it suffices to blow away our signed bounds
5034 * and rely on inferring new ones from the unsigned bounds and
5035 * var_off of the result.
5036 */
5037 dst_reg->smin_value = S64_MIN;
5038 dst_reg->smax_value = S64_MAX;
5039 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
5040 dst_reg->umin_value >>= umax_val;
5041 dst_reg->umax_value >>= umin_val;
5042 /* We may learn something more from the var_off */
5043 __update_reg_bounds(dst_reg);
5044}
5045
5046static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
5047 struct bpf_reg_state *src_reg,
5048 u64 insn_bitness)
5049{
5050 u64 umin_val = src_reg->umin_value;
5051
5052 /* Upon reaching here, src_known is true and
5053 * umax_val is equal to umin_val.
5054 */
5055 if (insn_bitness == 32) {
5056 dst_reg->smin_value = (u32)(((s32)dst_reg->smin_value) >> umin_val);
5057 dst_reg->smax_value = (u32)(((s32)dst_reg->smax_value) >> umin_val);
5058 } else {
5059 dst_reg->smin_value >>= umin_val;
5060 dst_reg->smax_value >>= umin_val;
5061 }
5062
5063 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val,
5064 insn_bitness);
5065
5066 /* blow away the dst_reg umin_value/umax_value and rely on
5067 * dst_reg var_off to refine the result.
5068 */
5069 dst_reg->umin_value = 0;
5070 dst_reg->umax_value = U64_MAX;
5071 __update_reg_bounds(dst_reg);
5072}
5073
Jann Horn468f6ea2017-12-18 20:11:56 -08005074/* WARNING: This function does calculations on 64-bit values, but the actual
5075 * execution may occur on 32-bit values. Therefore, things like bitshifts
5076 * need extra checks in the 32-bit case.
5077 */
Edward Creef1174f72017-08-07 15:26:19 +01005078static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
5079 struct bpf_insn *insn,
5080 struct bpf_reg_state *dst_reg,
5081 struct bpf_reg_state src_reg)
5082{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005083 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01005084 u8 opcode = BPF_OP(insn->code);
5085 bool src_known, dst_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01005086 s64 smin_val, smax_val;
5087 u64 umin_val, umax_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08005088 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005089 u32 dst = insn->dst_reg;
5090 int ret;
Edward Creef1174f72017-08-07 15:26:19 +01005091
Jann Hornb7992072018-10-05 18:17:59 +02005092 if (insn_bitness == 32) {
5093 /* Relevant for 32-bit RSH: Information can propagate towards
5094 * LSB, so it isn't sufficient to only truncate the output to
5095 * 32 bits.
5096 */
5097 coerce_reg_to_size(dst_reg, 4);
5098 coerce_reg_to_size(&src_reg, 4);
5099 }
5100
Edward Creeb03c9f92017-08-07 15:26:36 +01005101 smin_val = src_reg.smin_value;
5102 smax_val = src_reg.smax_value;
5103 umin_val = src_reg.umin_value;
5104 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01005105 src_known = tnum_is_const(src_reg.var_off);
5106 dst_known = tnum_is_const(dst_reg->var_off);
5107
Daniel Borkmann6f161012018-01-18 01:15:21 +01005108 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
5109 smin_val > smax_val || umin_val > umax_val) {
5110 /* Taint dst register if offset had invalid bounds derived from
5111 * e.g. dead branches.
5112 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005113 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01005114 return 0;
5115 }
5116
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005117 if (!src_known &&
5118 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005119 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005120 return 0;
5121 }
5122
Edward Creef1174f72017-08-07 15:26:19 +01005123 switch (opcode) {
5124 case BPF_ADD:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005125 ret = sanitize_val_alu(env, insn);
5126 if (ret < 0) {
5127 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
5128 return ret;
5129 }
John Fastabend07cd2632020-03-24 10:38:15 -07005130 scalar_min_max_add(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005131 break;
5132 case BPF_SUB:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005133 ret = sanitize_val_alu(env, insn);
5134 if (ret < 0) {
5135 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
5136 return ret;
5137 }
John Fastabend07cd2632020-03-24 10:38:15 -07005138 scalar_min_max_sub(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005139 break;
5140 case BPF_MUL:
John Fastabend07cd2632020-03-24 10:38:15 -07005141 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005142 break;
5143 case BPF_AND:
Edward Creef1174f72017-08-07 15:26:19 +01005144 if (src_known && dst_known) {
Edward Creeb03c9f92017-08-07 15:26:36 +01005145 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5146 src_reg.var_off.value);
Edward Creef1174f72017-08-07 15:26:19 +01005147 break;
5148 }
John Fastabend07cd2632020-03-24 10:38:15 -07005149 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005150 break;
5151 case BPF_OR:
5152 if (src_known && dst_known) {
Edward Creeb03c9f92017-08-07 15:26:36 +01005153 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5154 src_reg.var_off.value);
Edward Creef1174f72017-08-07 15:26:19 +01005155 break;
5156 }
John Fastabend07cd2632020-03-24 10:38:15 -07005157 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005158 break;
5159 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08005160 if (umax_val >= insn_bitness) {
5161 /* Shifts greater than 31 or 63 are undefined.
5162 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01005163 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005164 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005165 break;
5166 }
John Fastabend07cd2632020-03-24 10:38:15 -07005167 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005168 break;
5169 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08005170 if (umax_val >= insn_bitness) {
5171 /* Shifts greater than 31 or 63 are undefined.
5172 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01005173 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005174 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005175 break;
5176 }
John Fastabend07cd2632020-03-24 10:38:15 -07005177 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005178 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07005179 case BPF_ARSH:
5180 if (umax_val >= insn_bitness) {
5181 /* Shifts greater than 31 or 63 are undefined.
5182 * This includes shifts by a negative number.
5183 */
5184 mark_reg_unknown(env, regs, insn->dst_reg);
5185 break;
5186 }
John Fastabend07cd2632020-03-24 10:38:15 -07005187 scalar_min_max_arsh(dst_reg, &src_reg, insn_bitness);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07005188 break;
Josef Bacik48461132016-09-28 10:54:32 -04005189 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005190 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005191 break;
5192 }
5193
Jann Horn468f6ea2017-12-18 20:11:56 -08005194 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5195 /* 32-bit ALU ops are (32,32)->32 */
5196 coerce_reg_to_size(dst_reg, 4);
Jann Horn468f6ea2017-12-18 20:11:56 -08005197 }
5198
John Fastabend294f2fc2020-03-24 10:38:37 -07005199 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01005200 __reg_deduce_bounds(dst_reg);
5201 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005202 return 0;
5203}
5204
5205/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
5206 * and var_off.
5207 */
5208static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
5209 struct bpf_insn *insn)
5210{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005211 struct bpf_verifier_state *vstate = env->cur_state;
5212 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5213 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01005214 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
5215 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005216 int err;
Edward Creef1174f72017-08-07 15:26:19 +01005217
5218 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01005219 src_reg = NULL;
5220 if (dst_reg->type != SCALAR_VALUE)
5221 ptr_reg = dst_reg;
5222 if (BPF_SRC(insn->code) == BPF_X) {
5223 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01005224 if (src_reg->type != SCALAR_VALUE) {
5225 if (dst_reg->type != SCALAR_VALUE) {
5226 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005227 * an arbitrary scalar. Disallow all math except
5228 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01005229 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07005230 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005231 mark_reg_unknown(env, regs, insn->dst_reg);
5232 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01005233 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005234 verbose(env, "R%d pointer %s pointer prohibited\n",
5235 insn->dst_reg,
5236 bpf_alu_string[opcode >> 4]);
5237 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01005238 } else {
5239 /* scalar += pointer
5240 * This is legal, but we have to reverse our
5241 * src/dest handling in computing the range
5242 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005243 err = mark_chain_precision(env, insn->dst_reg);
5244 if (err)
5245 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005246 return adjust_ptr_min_max_vals(env, insn,
5247 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005248 }
5249 } else if (ptr_reg) {
5250 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005251 err = mark_chain_precision(env, insn->src_reg);
5252 if (err)
5253 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005254 return adjust_ptr_min_max_vals(env, insn,
5255 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005256 }
5257 } else {
5258 /* Pretend the src is a reg with a known value, since we only
5259 * need to be able to read from this state.
5260 */
5261 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01005262 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01005263 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005264 if (ptr_reg) /* pointer += K */
5265 return adjust_ptr_min_max_vals(env, insn,
5266 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005267 }
5268
5269 /* Got here implies adding two SCALAR_VALUEs */
5270 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005271 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005272 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01005273 return -EINVAL;
5274 }
5275 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005276 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005277 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01005278 return -EINVAL;
5279 }
5280 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005281}
5282
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005283/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01005284static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005285{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005286 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005287 u8 opcode = BPF_OP(insn->code);
5288 int err;
5289
5290 if (opcode == BPF_END || opcode == BPF_NEG) {
5291 if (opcode == BPF_NEG) {
5292 if (BPF_SRC(insn->code) != 0 ||
5293 insn->src_reg != BPF_REG_0 ||
5294 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005295 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005296 return -EINVAL;
5297 }
5298 } else {
5299 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01005300 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
5301 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005302 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005303 return -EINVAL;
5304 }
5305 }
5306
5307 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01005308 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005309 if (err)
5310 return err;
5311
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005312 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005313 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005314 insn->dst_reg);
5315 return -EACCES;
5316 }
5317
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005318 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01005319 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005320 if (err)
5321 return err;
5322
5323 } else if (opcode == BPF_MOV) {
5324
5325 if (BPF_SRC(insn->code) == BPF_X) {
5326 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005327 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005328 return -EINVAL;
5329 }
5330
5331 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01005332 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005333 if (err)
5334 return err;
5335 } else {
5336 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005337 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005338 return -EINVAL;
5339 }
5340 }
5341
Arthur Fabrefbeb1602018-07-31 18:17:22 +01005342 /* check dest operand, mark as required later */
5343 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005344 if (err)
5345 return err;
5346
5347 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05005348 struct bpf_reg_state *src_reg = regs + insn->src_reg;
5349 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
5350
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005351 if (BPF_CLASS(insn->code) == BPF_ALU64) {
5352 /* case: R1 = R2
5353 * copy register state to dest reg
5354 */
Jiong Wange434b8c2018-12-07 12:16:18 -05005355 *dst_reg = *src_reg;
5356 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01005357 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005358 } else {
Edward Creef1174f72017-08-07 15:26:19 +01005359 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005360 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005361 verbose(env,
5362 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005363 insn->src_reg);
5364 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05005365 } else if (src_reg->type == SCALAR_VALUE) {
5366 *dst_reg = *src_reg;
5367 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01005368 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05005369 } else {
5370 mark_reg_unknown(env, regs,
5371 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005372 }
Jiong Wange434b8c2018-12-07 12:16:18 -05005373 coerce_reg_to_size(dst_reg, 4);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005374 }
5375 } else {
5376 /* case: R = imm
5377 * remember the value we stored into this reg
5378 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01005379 /* clear any state __mark_reg_known doesn't set */
5380 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005381 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08005382 if (BPF_CLASS(insn->code) == BPF_ALU64) {
5383 __mark_reg_known(regs + insn->dst_reg,
5384 insn->imm);
5385 } else {
5386 __mark_reg_known(regs + insn->dst_reg,
5387 (u32)insn->imm);
5388 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005389 }
5390
5391 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005392 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005393 return -EINVAL;
5394
5395 } else { /* all other ALU ops: and, sub, xor, add, ... */
5396
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005397 if (BPF_SRC(insn->code) == BPF_X) {
5398 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005399 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005400 return -EINVAL;
5401 }
5402 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01005403 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005404 if (err)
5405 return err;
5406 } else {
5407 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005408 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005409 return -EINVAL;
5410 }
5411 }
5412
5413 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01005414 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005415 if (err)
5416 return err;
5417
5418 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
5419 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005420 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005421 return -EINVAL;
5422 }
5423
Rabin Vincent229394e82016-01-12 20:17:08 +01005424 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
5425 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
5426 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
5427
5428 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005429 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01005430 return -EINVAL;
5431 }
5432 }
5433
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07005434 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01005435 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07005436 if (err)
5437 return err;
5438
Edward Creef1174f72017-08-07 15:26:19 +01005439 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005440 }
5441
5442 return 0;
5443}
5444
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02005445static void __find_good_pkt_pointers(struct bpf_func_state *state,
5446 struct bpf_reg_state *dst_reg,
5447 enum bpf_reg_type type, u16 new_range)
5448{
5449 struct bpf_reg_state *reg;
5450 int i;
5451
5452 for (i = 0; i < MAX_BPF_REG; i++) {
5453 reg = &state->regs[i];
5454 if (reg->type == type && reg->id == dst_reg->id)
5455 /* keep the maximum range already checked */
5456 reg->range = max(reg->range, new_range);
5457 }
5458
5459 bpf_for_each_spilled_reg(i, state, reg) {
5460 if (!reg)
5461 continue;
5462 if (reg->type == type && reg->id == dst_reg->id)
5463 reg->range = max(reg->range, new_range);
5464 }
5465}
5466
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005467static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005468 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01005469 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005470 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005471{
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005472 u16 new_range;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02005473 int i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005474
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005475 if (dst_reg->off < 0 ||
5476 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01005477 /* This doesn't give us any range */
5478 return;
5479
Edward Creeb03c9f92017-08-07 15:26:36 +01005480 if (dst_reg->umax_value > MAX_PACKET_OFF ||
5481 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01005482 /* Risk of overflow. For instance, ptr + (1<<63) may be less
5483 * than pkt_end, but that's because it's also less than pkt.
5484 */
5485 return;
5486
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005487 new_range = dst_reg->off;
5488 if (range_right_open)
5489 new_range--;
5490
5491 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005492 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005493 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005494 *
5495 * r2 = r3;
5496 * r2 += 8;
5497 * if (r2 > pkt_end) goto <handle exception>
5498 * <access okay>
5499 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005500 * r2 = r3;
5501 * r2 += 8;
5502 * if (r2 < pkt_end) goto <access okay>
5503 * <handle exception>
5504 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005505 * Where:
5506 * r2 == dst_reg, pkt_end == src_reg
5507 * r2=pkt(id=n,off=8,r=0)
5508 * r3=pkt(id=n,off=0,r=0)
5509 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005510 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005511 *
5512 * r2 = r3;
5513 * r2 += 8;
5514 * if (pkt_end >= r2) goto <access okay>
5515 * <handle exception>
5516 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005517 * r2 = r3;
5518 * r2 += 8;
5519 * if (pkt_end <= r2) goto <handle exception>
5520 * <access okay>
5521 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005522 * Where:
5523 * pkt_end == dst_reg, r2 == src_reg
5524 * r2=pkt(id=n,off=8,r=0)
5525 * r3=pkt(id=n,off=0,r=0)
5526 *
5527 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005528 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
5529 * and [r3, r3 + 8-1) respectively is safe to access depending on
5530 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005531 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005532
Edward Creef1174f72017-08-07 15:26:19 +01005533 /* If our ids match, then we must have the same max_value. And we
5534 * don't care about the other reg's fixed offset, since if it's too big
5535 * the range won't allow anything.
5536 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
5537 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02005538 for (i = 0; i <= vstate->curframe; i++)
5539 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
5540 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005541}
5542
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005543/* compute branch direction of the expression "if (reg opcode val) goto target;"
5544 * and return:
5545 * 1 - branch will be taken and "goto target" will be executed
5546 * 0 - branch will not be taken and fall-through to next insn
5547 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
5548 */
Jiong Wang092ed092019-01-26 12:26:01 -05005549static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
5550 bool is_jmp32)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005551{
Jiong Wang092ed092019-01-26 12:26:01 -05005552 struct bpf_reg_state reg_lo;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005553 s64 sval;
5554
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005555 if (__is_pointer_value(false, reg))
5556 return -1;
5557
Jiong Wang092ed092019-01-26 12:26:01 -05005558 if (is_jmp32) {
5559 reg_lo = *reg;
5560 reg = &reg_lo;
5561 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
5562 * could truncate high bits and update umin/umax according to
5563 * information of low bits.
5564 */
5565 coerce_reg_to_size(reg, 4);
5566 /* smin/smax need special handling. For example, after coerce,
5567 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
5568 * used as operand to JMP32. It is a negative number from s32's
5569 * point of view, while it is a positive number when seen as
5570 * s64. The smin/smax are kept as s64, therefore, when used with
5571 * JMP32, they need to be transformed into s32, then sign
5572 * extended back to s64.
5573 *
5574 * Also, smin/smax were copied from umin/umax. If umin/umax has
5575 * different sign bit, then min/max relationship doesn't
5576 * maintain after casting into s32, for this case, set smin/smax
5577 * to safest range.
5578 */
5579 if ((reg->umax_value ^ reg->umin_value) &
5580 (1ULL << 31)) {
5581 reg->smin_value = S32_MIN;
5582 reg->smax_value = S32_MAX;
5583 }
5584 reg->smin_value = (s64)(s32)reg->smin_value;
5585 reg->smax_value = (s64)(s32)reg->smax_value;
5586
5587 val = (u32)val;
5588 sval = (s64)(s32)val;
5589 } else {
5590 sval = (s64)val;
5591 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05005592
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005593 switch (opcode) {
5594 case BPF_JEQ:
5595 if (tnum_is_const(reg->var_off))
5596 return !!tnum_equals_const(reg->var_off, val);
5597 break;
5598 case BPF_JNE:
5599 if (tnum_is_const(reg->var_off))
5600 return !tnum_equals_const(reg->var_off, val);
5601 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08005602 case BPF_JSET:
5603 if ((~reg->var_off.mask & reg->var_off.value) & val)
5604 return 1;
5605 if (!((reg->var_off.mask | reg->var_off.value) & val))
5606 return 0;
5607 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005608 case BPF_JGT:
5609 if (reg->umin_value > val)
5610 return 1;
5611 else if (reg->umax_value <= val)
5612 return 0;
5613 break;
5614 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005615 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005616 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005617 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005618 return 0;
5619 break;
5620 case BPF_JLT:
5621 if (reg->umax_value < val)
5622 return 1;
5623 else if (reg->umin_value >= val)
5624 return 0;
5625 break;
5626 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005627 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005628 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005629 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005630 return 0;
5631 break;
5632 case BPF_JGE:
5633 if (reg->umin_value >= val)
5634 return 1;
5635 else if (reg->umax_value < val)
5636 return 0;
5637 break;
5638 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005639 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005640 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005641 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005642 return 0;
5643 break;
5644 case BPF_JLE:
5645 if (reg->umax_value <= val)
5646 return 1;
5647 else if (reg->umin_value > val)
5648 return 0;
5649 break;
5650 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005651 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005652 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005653 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005654 return 0;
5655 break;
5656 }
5657
5658 return -1;
5659}
5660
Jiong Wang092ed092019-01-26 12:26:01 -05005661/* Generate min value of the high 32-bit from TNUM info. */
5662static u64 gen_hi_min(struct tnum var)
5663{
5664 return var.value & ~0xffffffffULL;
5665}
5666
5667/* Generate max value of the high 32-bit from TNUM info. */
5668static u64 gen_hi_max(struct tnum var)
5669{
5670 return (var.value | var.mask) & ~0xffffffffULL;
5671}
5672
5673/* Return true if VAL is compared with a s64 sign extended from s32, and they
5674 * are with the same signedness.
5675 */
5676static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
5677{
5678 return ((s32)sval >= 0 &&
5679 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
5680 ((s32)sval < 0 &&
5681 reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
5682}
5683
Jann Horn604dca52020-03-30 18:03:23 +02005684/* Constrain the possible values of @reg with unsigned upper bound @bound.
5685 * If @is_exclusive, @bound is an exclusive limit, otherwise it is inclusive.
5686 * If @is_jmp32, @bound is a 32-bit value that only constrains the low 32 bits
5687 * of @reg.
5688 */
5689static void set_upper_bound(struct bpf_reg_state *reg, u64 bound, bool is_jmp32,
5690 bool is_exclusive)
5691{
5692 if (is_exclusive) {
5693 /* There are no values for `reg` that make `reg<0` true. */
5694 if (bound == 0)
5695 return;
5696 bound--;
5697 }
5698 if (is_jmp32) {
5699 /* Constrain the register's value in the tnum representation.
5700 * For 64-bit comparisons this happens later in
5701 * __reg_bound_offset(), but for 32-bit comparisons, we can be
5702 * more precise than what can be derived from the updated
5703 * numeric bounds.
5704 */
5705 struct tnum t = tnum_range(0, bound);
5706
5707 t.mask |= ~0xffffffffULL; /* upper half is unknown */
5708 reg->var_off = tnum_intersect(reg->var_off, t);
5709
5710 /* Compute the 64-bit bound from the 32-bit bound. */
5711 bound += gen_hi_max(reg->var_off);
5712 }
5713 reg->umax_value = min(reg->umax_value, bound);
5714}
5715
5716/* Constrain the possible values of @reg with unsigned lower bound @bound.
5717 * If @is_exclusive, @bound is an exclusive limit, otherwise it is inclusive.
5718 * If @is_jmp32, @bound is a 32-bit value that only constrains the low 32 bits
5719 * of @reg.
5720 */
5721static void set_lower_bound(struct bpf_reg_state *reg, u64 bound, bool is_jmp32,
5722 bool is_exclusive)
5723{
5724 if (is_exclusive) {
5725 /* There are no values for `reg` that make `reg>MAX` true. */
5726 if (bound == (is_jmp32 ? U32_MAX : U64_MAX))
5727 return;
5728 bound++;
5729 }
5730 if (is_jmp32) {
5731 /* Constrain the register's value in the tnum representation.
5732 * For 64-bit comparisons this happens later in
5733 * __reg_bound_offset(), but for 32-bit comparisons, we can be
5734 * more precise than what can be derived from the updated
5735 * numeric bounds.
5736 */
5737 struct tnum t = tnum_range(bound, U32_MAX);
5738
5739 t.mask |= ~0xffffffffULL; /* upper half is unknown */
5740 reg->var_off = tnum_intersect(reg->var_off, t);
5741
5742 /* Compute the 64-bit bound from the 32-bit bound. */
5743 bound += gen_hi_min(reg->var_off);
5744 }
5745 reg->umin_value = max(reg->umin_value, bound);
5746}
5747
Josef Bacik48461132016-09-28 10:54:32 -04005748/* Adjusts the register min/max values in the case that the dst_reg is the
5749 * variable register that we are working on, and src_reg is a constant or we're
5750 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01005751 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04005752 */
5753static void reg_set_min_max(struct bpf_reg_state *true_reg,
5754 struct bpf_reg_state *false_reg, u64 val,
Jiong Wang092ed092019-01-26 12:26:01 -05005755 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04005756{
Jiong Wanga72dafa2019-01-26 12:26:00 -05005757 s64 sval;
5758
Edward Creef1174f72017-08-07 15:26:19 +01005759 /* If the dst_reg is a pointer, we can't learn anything about its
5760 * variable offset from the compare (unless src_reg were a pointer into
5761 * the same object, but we don't bother with that.
5762 * Since false_reg and true_reg have the same type by construction, we
5763 * only need to check one of them for pointerness.
5764 */
5765 if (__is_pointer_value(false, false_reg))
5766 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02005767
Jiong Wang092ed092019-01-26 12:26:01 -05005768 val = is_jmp32 ? (u32)val : val;
5769 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005770
Josef Bacik48461132016-09-28 10:54:32 -04005771 switch (opcode) {
5772 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04005773 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005774 {
5775 struct bpf_reg_state *reg =
5776 opcode == BPF_JEQ ? true_reg : false_reg;
5777
5778 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
5779 * if it is true we know the value for sure. Likewise for
5780 * BPF_JNE.
Josef Bacik48461132016-09-28 10:54:32 -04005781 */
Jiong Wang092ed092019-01-26 12:26:01 -05005782 if (is_jmp32) {
5783 u64 old_v = reg->var_off.value;
5784 u64 hi_mask = ~0xffffffffULL;
5785
5786 reg->var_off.value = (old_v & hi_mask) | val;
5787 reg->var_off.mask &= hi_mask;
5788 } else {
5789 __mark_reg_known(reg, val);
5790 }
Josef Bacik48461132016-09-28 10:54:32 -04005791 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005792 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08005793 case BPF_JSET:
5794 false_reg->var_off = tnum_and(false_reg->var_off,
5795 tnum_const(~val));
5796 if (is_power_of_2(val))
5797 true_reg->var_off = tnum_or(true_reg->var_off,
5798 tnum_const(val));
5799 break;
Josef Bacik48461132016-09-28 10:54:32 -04005800 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005801 case BPF_JGT:
5802 {
Jann Horn604dca52020-03-30 18:03:23 +02005803 set_upper_bound(false_reg, val, is_jmp32, opcode == BPF_JGE);
5804 set_lower_bound(true_reg, val, is_jmp32, opcode == BPF_JGT);
Edward Creeb03c9f92017-08-07 15:26:36 +01005805 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005806 }
Josef Bacik48461132016-09-28 10:54:32 -04005807 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005808 case BPF_JSGT:
5809 {
5810 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
5811 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
5812
Jiong Wang092ed092019-01-26 12:26:01 -05005813 /* If the full s64 was not sign-extended from s32 then don't
5814 * deduct further info.
5815 */
5816 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5817 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005818 false_reg->smax_value = min(false_reg->smax_value, false_smax);
5819 true_reg->smin_value = max(true_reg->smin_value, true_smin);
Josef Bacik48461132016-09-28 10:54:32 -04005820 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005821 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005822 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005823 case BPF_JLT:
5824 {
Jann Horn604dca52020-03-30 18:03:23 +02005825 set_lower_bound(false_reg, val, is_jmp32, opcode == BPF_JLE);
5826 set_upper_bound(true_reg, val, is_jmp32, opcode == BPF_JLT);
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005827 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005828 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005829 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005830 case BPF_JSLT:
5831 {
5832 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
5833 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
5834
Jiong Wang092ed092019-01-26 12:26:01 -05005835 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5836 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005837 false_reg->smin_value = max(false_reg->smin_value, false_smin);
5838 true_reg->smax_value = min(true_reg->smax_value, true_smax);
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005839 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005840 }
Josef Bacik48461132016-09-28 10:54:32 -04005841 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02005842 return;
Josef Bacik48461132016-09-28 10:54:32 -04005843 }
5844
Edward Creeb03c9f92017-08-07 15:26:36 +01005845 __reg_deduce_bounds(false_reg);
5846 __reg_deduce_bounds(true_reg);
5847 /* We might have learned some bits from the bounds. */
5848 __reg_bound_offset(false_reg);
5849 __reg_bound_offset(true_reg);
5850 /* Intersecting with the old var_off might have improved our bounds
5851 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5852 * then new var_off is (0; 0x7f...fc) which improves our umax.
5853 */
5854 __update_reg_bounds(false_reg);
5855 __update_reg_bounds(true_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005856}
5857
Edward Creef1174f72017-08-07 15:26:19 +01005858/* Same as above, but for the case that dst_reg holds a constant and src_reg is
5859 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04005860 */
5861static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
5862 struct bpf_reg_state *false_reg, u64 val,
Jiong Wang092ed092019-01-26 12:26:01 -05005863 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04005864{
Jann Horn0fc31b12020-03-30 18:03:24 +02005865 /* How can we transform "a <op> b" into "b <op> a"? */
5866 static const u8 opcode_flip[16] = {
5867 /* these stay the same */
5868 [BPF_JEQ >> 4] = BPF_JEQ,
5869 [BPF_JNE >> 4] = BPF_JNE,
5870 [BPF_JSET >> 4] = BPF_JSET,
5871 /* these swap "lesser" and "greater" (L and G in the opcodes) */
5872 [BPF_JGE >> 4] = BPF_JLE,
5873 [BPF_JGT >> 4] = BPF_JLT,
5874 [BPF_JLE >> 4] = BPF_JGE,
5875 [BPF_JLT >> 4] = BPF_JGT,
5876 [BPF_JSGE >> 4] = BPF_JSLE,
5877 [BPF_JSGT >> 4] = BPF_JSLT,
5878 [BPF_JSLE >> 4] = BPF_JSGE,
5879 [BPF_JSLT >> 4] = BPF_JSGT
5880 };
5881 opcode = opcode_flip[opcode >> 4];
5882 /* This uses zero as "not present in table"; luckily the zero opcode,
5883 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01005884 */
Jann Horn0fc31b12020-03-30 18:03:24 +02005885 if (opcode)
5886 reg_set_min_max(true_reg, false_reg, val, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01005887}
5888
5889/* Regs are known to be equal, so intersect their min/max/var_off */
5890static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
5891 struct bpf_reg_state *dst_reg)
5892{
Edward Creeb03c9f92017-08-07 15:26:36 +01005893 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
5894 dst_reg->umin_value);
5895 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
5896 dst_reg->umax_value);
5897 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
5898 dst_reg->smin_value);
5899 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
5900 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01005901 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
5902 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01005903 /* We might have learned new bounds from the var_off. */
5904 __update_reg_bounds(src_reg);
5905 __update_reg_bounds(dst_reg);
5906 /* We might have learned something about the sign bit. */
5907 __reg_deduce_bounds(src_reg);
5908 __reg_deduce_bounds(dst_reg);
5909 /* We might have learned some bits from the bounds. */
5910 __reg_bound_offset(src_reg);
5911 __reg_bound_offset(dst_reg);
5912 /* Intersecting with the old var_off might have improved our bounds
5913 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5914 * then new var_off is (0; 0x7f...fc) which improves our umax.
5915 */
5916 __update_reg_bounds(src_reg);
5917 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005918}
5919
5920static void reg_combine_min_max(struct bpf_reg_state *true_src,
5921 struct bpf_reg_state *true_dst,
5922 struct bpf_reg_state *false_src,
5923 struct bpf_reg_state *false_dst,
5924 u8 opcode)
5925{
5926 switch (opcode) {
5927 case BPF_JEQ:
5928 __reg_combine_min_max(true_src, true_dst);
5929 break;
5930 case BPF_JNE:
5931 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01005932 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02005933 }
Josef Bacik48461132016-09-28 10:54:32 -04005934}
5935
Joe Stringerfd978bf72018-10-02 13:35:35 -07005936static void mark_ptr_or_null_reg(struct bpf_func_state *state,
5937 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07005938 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02005939{
Joe Stringer840b9612018-10-02 13:35:32 -07005940 if (reg_type_may_be_null(reg->type) && reg->id == id) {
Edward Creef1174f72017-08-07 15:26:19 +01005941 /* Old offset (both fixed and variable parts) should
5942 * have been known-zero, because we don't allow pointer
5943 * arithmetic on pointers that might be NULL.
5944 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005945 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
5946 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01005947 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01005948 __mark_reg_known_zero(reg);
5949 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01005950 }
5951 if (is_null) {
5952 reg->type = SCALAR_VALUE;
Joe Stringer840b9612018-10-02 13:35:32 -07005953 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
5954 if (reg->map_ptr->inner_map_meta) {
5955 reg->type = CONST_PTR_TO_MAP;
5956 reg->map_ptr = reg->map_ptr->inner_map_meta;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07005957 } else if (reg->map_ptr->map_type ==
5958 BPF_MAP_TYPE_XSKMAP) {
5959 reg->type = PTR_TO_XDP_SOCK;
Joe Stringer840b9612018-10-02 13:35:32 -07005960 } else {
5961 reg->type = PTR_TO_MAP_VALUE;
5962 }
Joe Stringerc64b7982018-10-02 13:35:33 -07005963 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
5964 reg->type = PTR_TO_SOCKET;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005965 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
5966 reg->type = PTR_TO_SOCK_COMMON;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005967 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
5968 reg->type = PTR_TO_TCP_SOCK;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07005969 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005970 if (is_null) {
5971 /* We don't need id and ref_obj_id from this point
5972 * onwards anymore, thus we should better reset it,
5973 * so that state pruning has chances to take effect.
5974 */
5975 reg->id = 0;
5976 reg->ref_obj_id = 0;
5977 } else if (!reg_may_point_to_spin_lock(reg)) {
5978 /* For not-NULL ptr, reg->ref_obj_id will be reset
5979 * in release_reg_references().
5980 *
5981 * reg->id is still used by spin_lock ptr. Other
5982 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07005983 */
5984 reg->id = 0;
5985 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02005986 }
5987}
5988
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02005989static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
5990 bool is_null)
5991{
5992 struct bpf_reg_state *reg;
5993 int i;
5994
5995 for (i = 0; i < MAX_BPF_REG; i++)
5996 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
5997
5998 bpf_for_each_spilled_reg(i, state, reg) {
5999 if (!reg)
6000 continue;
6001 mark_ptr_or_null_reg(state, reg, id, is_null);
6002 }
6003}
6004
Thomas Graf57a09bf2016-10-18 19:51:19 +02006005/* The logic is similar to find_good_pkt_pointers(), both could eventually
6006 * be folded together at some point.
6007 */
Joe Stringer840b9612018-10-02 13:35:32 -07006008static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
6009 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02006010{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006011 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006012 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006013 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01006014 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006015 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02006016
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006017 if (ref_obj_id && ref_obj_id == id && is_null)
6018 /* regs[regno] is in the " == NULL" branch.
6019 * No one could have freed the reference state before
6020 * doing the NULL check.
6021 */
6022 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07006023
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006024 for (i = 0; i <= vstate->curframe; i++)
6025 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02006026}
6027
Daniel Borkmann5beca082017-11-01 23:58:10 +01006028static bool try_match_pkt_pointers(const struct bpf_insn *insn,
6029 struct bpf_reg_state *dst_reg,
6030 struct bpf_reg_state *src_reg,
6031 struct bpf_verifier_state *this_branch,
6032 struct bpf_verifier_state *other_branch)
6033{
6034 if (BPF_SRC(insn->code) != BPF_X)
6035 return false;
6036
Jiong Wang092ed092019-01-26 12:26:01 -05006037 /* Pointers are always 64-bit. */
6038 if (BPF_CLASS(insn->code) == BPF_JMP32)
6039 return false;
6040
Daniel Borkmann5beca082017-11-01 23:58:10 +01006041 switch (BPF_OP(insn->code)) {
6042 case BPF_JGT:
6043 if ((dst_reg->type == PTR_TO_PACKET &&
6044 src_reg->type == PTR_TO_PACKET_END) ||
6045 (dst_reg->type == PTR_TO_PACKET_META &&
6046 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6047 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
6048 find_good_pkt_pointers(this_branch, dst_reg,
6049 dst_reg->type, false);
6050 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6051 src_reg->type == PTR_TO_PACKET) ||
6052 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6053 src_reg->type == PTR_TO_PACKET_META)) {
6054 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
6055 find_good_pkt_pointers(other_branch, src_reg,
6056 src_reg->type, true);
6057 } else {
6058 return false;
6059 }
6060 break;
6061 case BPF_JLT:
6062 if ((dst_reg->type == PTR_TO_PACKET &&
6063 src_reg->type == PTR_TO_PACKET_END) ||
6064 (dst_reg->type == PTR_TO_PACKET_META &&
6065 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6066 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
6067 find_good_pkt_pointers(other_branch, dst_reg,
6068 dst_reg->type, true);
6069 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6070 src_reg->type == PTR_TO_PACKET) ||
6071 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6072 src_reg->type == PTR_TO_PACKET_META)) {
6073 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
6074 find_good_pkt_pointers(this_branch, src_reg,
6075 src_reg->type, false);
6076 } else {
6077 return false;
6078 }
6079 break;
6080 case BPF_JGE:
6081 if ((dst_reg->type == PTR_TO_PACKET &&
6082 src_reg->type == PTR_TO_PACKET_END) ||
6083 (dst_reg->type == PTR_TO_PACKET_META &&
6084 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6085 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
6086 find_good_pkt_pointers(this_branch, dst_reg,
6087 dst_reg->type, true);
6088 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6089 src_reg->type == PTR_TO_PACKET) ||
6090 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6091 src_reg->type == PTR_TO_PACKET_META)) {
6092 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
6093 find_good_pkt_pointers(other_branch, src_reg,
6094 src_reg->type, false);
6095 } else {
6096 return false;
6097 }
6098 break;
6099 case BPF_JLE:
6100 if ((dst_reg->type == PTR_TO_PACKET &&
6101 src_reg->type == PTR_TO_PACKET_END) ||
6102 (dst_reg->type == PTR_TO_PACKET_META &&
6103 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6104 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
6105 find_good_pkt_pointers(other_branch, dst_reg,
6106 dst_reg->type, false);
6107 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6108 src_reg->type == PTR_TO_PACKET) ||
6109 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6110 src_reg->type == PTR_TO_PACKET_META)) {
6111 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
6112 find_good_pkt_pointers(this_branch, src_reg,
6113 src_reg->type, true);
6114 } else {
6115 return false;
6116 }
6117 break;
6118 default:
6119 return false;
6120 }
6121
6122 return true;
6123}
6124
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006125static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006126 struct bpf_insn *insn, int *insn_idx)
6127{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006128 struct bpf_verifier_state *this_branch = env->cur_state;
6129 struct bpf_verifier_state *other_branch;
6130 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006131 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006132 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05006133 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006134 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006135 int err;
6136
Jiong Wang092ed092019-01-26 12:26:01 -05006137 /* Only conditional jumps are expected to reach here. */
6138 if (opcode == BPF_JA || opcode > BPF_JSLE) {
6139 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006140 return -EINVAL;
6141 }
6142
6143 if (BPF_SRC(insn->code) == BPF_X) {
6144 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05006145 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006146 return -EINVAL;
6147 }
6148
6149 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006150 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006151 if (err)
6152 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006153
6154 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006155 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006156 insn->src_reg);
6157 return -EACCES;
6158 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006159 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006160 } else {
6161 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05006162 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006163 return -EINVAL;
6164 }
6165 }
6166
6167 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006168 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006169 if (err)
6170 return err;
6171
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006172 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05006173 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006174
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006175 if (BPF_SRC(insn->code) == BPF_K)
6176 pred = is_branch_taken(dst_reg, insn->imm,
6177 opcode, is_jmp32);
6178 else if (src_reg->type == SCALAR_VALUE &&
6179 tnum_is_const(src_reg->var_off))
6180 pred = is_branch_taken(dst_reg, src_reg->var_off.value,
6181 opcode, is_jmp32);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006182 if (pred >= 0) {
6183 err = mark_chain_precision(env, insn->dst_reg);
6184 if (BPF_SRC(insn->code) == BPF_X && !err)
6185 err = mark_chain_precision(env, insn->src_reg);
6186 if (err)
6187 return err;
6188 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006189 if (pred == 1) {
6190 /* only follow the goto, ignore fall-through */
6191 *insn_idx += insn->off;
6192 return 0;
6193 } else if (pred == 0) {
6194 /* only follow fall-through branch, since
6195 * that's where the program will go
6196 */
6197 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006198 }
6199
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006200 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
6201 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006202 if (!other_branch)
6203 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006204 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006205
Josef Bacik48461132016-09-28 10:54:32 -04006206 /* detect if we are comparing against a constant value so we can adjust
6207 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01006208 * this is only legit if both are scalars (or pointers to the same
6209 * object, I suppose, but we don't support that right now), because
6210 * otherwise the different base pointers mean the offsets aren't
6211 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04006212 */
6213 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05006214 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
6215 struct bpf_reg_state lo_reg0 = *dst_reg;
6216 struct bpf_reg_state lo_reg1 = *src_reg;
6217 struct bpf_reg_state *src_lo, *dst_lo;
6218
6219 dst_lo = &lo_reg0;
6220 src_lo = &lo_reg1;
6221 coerce_reg_to_size(dst_lo, 4);
6222 coerce_reg_to_size(src_lo, 4);
6223
Edward Creef1174f72017-08-07 15:26:19 +01006224 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05006225 src_reg->type == SCALAR_VALUE) {
6226 if (tnum_is_const(src_reg->var_off) ||
6227 (is_jmp32 && tnum_is_const(src_lo->var_off)))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006228 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05006229 dst_reg,
6230 is_jmp32
6231 ? src_lo->var_off.value
6232 : src_reg->var_off.value,
6233 opcode, is_jmp32);
6234 else if (tnum_is_const(dst_reg->var_off) ||
6235 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006236 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05006237 src_reg,
6238 is_jmp32
6239 ? dst_lo->var_off.value
6240 : dst_reg->var_off.value,
6241 opcode, is_jmp32);
6242 else if (!is_jmp32 &&
6243 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01006244 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006245 reg_combine_min_max(&other_branch_regs[insn->src_reg],
6246 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05006247 src_reg, dst_reg, opcode);
Edward Creef1174f72017-08-07 15:26:19 +01006248 }
6249 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006250 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05006251 dst_reg, insn->imm, opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04006252 }
6253
Jiong Wang092ed092019-01-26 12:26:01 -05006254 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
6255 * NOTE: these optimizations below are related with pointer comparison
6256 * which will never be JMP32.
6257 */
6258 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006259 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07006260 reg_type_may_be_null(dst_reg->type)) {
6261 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02006262 * safe or unknown depending R == 0 or R != 0 conditional.
6263 */
Joe Stringer840b9612018-10-02 13:35:32 -07006264 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
6265 opcode == BPF_JNE);
6266 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
6267 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01006268 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
6269 this_branch, other_branch) &&
6270 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006271 verbose(env, "R%d pointer comparison prohibited\n",
6272 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006273 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006274 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07006275 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006276 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006277 return 0;
6278}
6279
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006280/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006281static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006282{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02006283 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006284 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02006285 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006286 int err;
6287
6288 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006289 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006290 return -EINVAL;
6291 }
6292 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006293 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006294 return -EINVAL;
6295 }
6296
Edward Creedc503a82017-08-15 20:34:35 +01006297 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006298 if (err)
6299 return err;
6300
Jakub Kicinski6b173872016-09-21 11:43:59 +01006301 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01006302 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
6303
Edward Creef1174f72017-08-07 15:26:19 +01006304 regs[insn->dst_reg].type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01006305 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006306 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01006307 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006308
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02006309 map = env->used_maps[aux->map_index];
6310 mark_reg_known_zero(env, regs, insn->dst_reg);
6311 regs[insn->dst_reg].map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006312
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02006313 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
6314 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
6315 regs[insn->dst_reg].off = aux->map_off;
6316 if (map_value_has_spin_lock(map))
6317 regs[insn->dst_reg].id = ++env->id_gen;
6318 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
6319 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
6320 } else {
6321 verbose(env, "bpf verifier is misconfigured\n");
6322 return -EINVAL;
6323 }
6324
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006325 return 0;
6326}
6327
Daniel Borkmann96be4322015-03-01 12:31:46 +01006328static bool may_access_skb(enum bpf_prog_type type)
6329{
6330 switch (type) {
6331 case BPF_PROG_TYPE_SOCKET_FILTER:
6332 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01006333 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01006334 return true;
6335 default:
6336 return false;
6337 }
6338}
6339
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006340/* verify safety of LD_ABS|LD_IND instructions:
6341 * - they can only appear in the programs where ctx == skb
6342 * - since they are wrappers of function calls, they scratch R1-R5 registers,
6343 * preserve R6-R9, and store return value into R0
6344 *
6345 * Implicit input:
6346 * ctx == skb == R6 == CTX
6347 *
6348 * Explicit input:
6349 * SRC == any register
6350 * IMM == 32-bit immediate
6351 *
6352 * Output:
6353 * R0 - 8/16/32-bit skb data converted to cpu endianness
6354 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006355static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006356{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006357 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01006358 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006359 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006360 int i, err;
6361
Daniel Borkmann24701ec2015-03-01 12:31:47 +01006362 if (!may_access_skb(env->prog->type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006363 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006364 return -EINVAL;
6365 }
6366
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02006367 if (!env->ops->gen_ld_abs) {
6368 verbose(env, "bpf verifier is misconfigured\n");
6369 return -EINVAL;
6370 }
6371
Jiong Wangf910cef2018-05-02 16:17:17 -04006372 if (env->subprog_cnt > 1) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006373 /* when program has LD_ABS insn JITs and interpreter assume
6374 * that r1 == ctx == skb which is not the case for callees
6375 * that can have arbitrary arguments. It's problematic
6376 * for main prog as well since JITs would need to analyze
6377 * all functions in order to make proper register save/restore
6378 * decisions in the main prog. Hence disallow LD_ABS with calls
6379 */
6380 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
6381 return -EINVAL;
6382 }
6383
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006384 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07006385 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006386 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006387 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006388 return -EINVAL;
6389 }
6390
6391 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01006392 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006393 if (err)
6394 return err;
6395
Joe Stringerfd978bf72018-10-02 13:35:35 -07006396 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
6397 * gen_ld_abs() may terminate the program at runtime, leading to
6398 * reference leak.
6399 */
6400 err = check_reference_leak(env);
6401 if (err) {
6402 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
6403 return err;
6404 }
6405
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08006406 if (env->cur_state->active_spin_lock) {
6407 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
6408 return -EINVAL;
6409 }
6410
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01006411 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006412 verbose(env,
6413 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006414 return -EINVAL;
6415 }
6416
6417 if (mode == BPF_IND) {
6418 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01006419 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006420 if (err)
6421 return err;
6422 }
6423
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01006424 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
6425 if (err < 0)
6426 return err;
6427
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006428 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01006429 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006430 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01006431 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6432 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006433
6434 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01006435 * the value fetched from the packet.
6436 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006437 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006438 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01006439 /* ld_abs load up to 32-bit skb data. */
6440 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006441 return 0;
6442}
6443
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006444static int check_return_code(struct bpf_verifier_env *env)
6445{
brakmo5cf1e912019-05-28 16:59:36 -07006446 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08006447 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006448 struct bpf_reg_state *reg;
6449 struct tnum range = tnum_range(0, 1);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08006450 int err;
6451
KP Singh9e4e01d2020-03-29 01:43:52 +01006452 /* LSM and struct_ops func-ptr's return type could be "void" */
6453 if ((env->prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
6454 env->prog->type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08006455 !prog->aux->attach_func_proto->type)
6456 return 0;
6457
6458 /* eBPF calling convetion is such that R0 is used
6459 * to return the value from eBPF program.
6460 * Make sure that it's readable at this time
6461 * of bpf_exit, which means that program wrote
6462 * something into it earlier
6463 */
6464 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
6465 if (err)
6466 return err;
6467
6468 if (is_pointer_value(env, BPF_REG_0)) {
6469 verbose(env, "R0 leaks addr as return value\n");
6470 return -EACCES;
6471 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006472
6473 switch (env->prog->type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02006474 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
6475 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
6476 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
6477 range = tnum_range(1, 1);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05006478 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006479 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07006480 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
6481 range = tnum_range(0, 3);
6482 enforce_attach_type_range = tnum_range(2, 3);
6483 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05006484 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006485 case BPF_PROG_TYPE_CGROUP_SOCK:
6486 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05006487 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08006488 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07006489 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006490 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07006491 case BPF_PROG_TYPE_RAW_TRACEPOINT:
6492 if (!env->prog->aux->attach_btf_id)
6493 return 0;
6494 range = tnum_const(0);
6495 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006496 default:
6497 return 0;
6498 }
6499
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006500 reg = cur_regs(env) + BPF_REG_0;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006501 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006502 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006503 reg_type_str[reg->type]);
6504 return -EINVAL;
6505 }
6506
6507 if (!tnum_in(range, reg->var_off)) {
brakmo5cf1e912019-05-28 16:59:36 -07006508 char tn_buf[48];
6509
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006510 verbose(env, "At program exit the register R0 ");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006511 if (!tnum_is_unknown(reg->var_off)) {
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006512 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006513 verbose(env, "has value %s", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006514 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006515 verbose(env, "has unknown scalar value");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006516 }
brakmo5cf1e912019-05-28 16:59:36 -07006517 tnum_strn(tn_buf, sizeof(tn_buf), range);
Daniel Borkmann983695f2019-06-07 01:48:57 +02006518 verbose(env, " should have been in %s\n", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006519 return -EINVAL;
6520 }
brakmo5cf1e912019-05-28 16:59:36 -07006521
6522 if (!tnum_is_unknown(enforce_attach_type_range) &&
6523 tnum_in(enforce_attach_type_range, reg->var_off))
6524 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006525 return 0;
6526}
6527
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006528/* non-recursive DFS pseudo code
6529 * 1 procedure DFS-iterative(G,v):
6530 * 2 label v as discovered
6531 * 3 let S be a stack
6532 * 4 S.push(v)
6533 * 5 while S is not empty
6534 * 6 t <- S.pop()
6535 * 7 if t is what we're looking for:
6536 * 8 return t
6537 * 9 for all edges e in G.adjacentEdges(t) do
6538 * 10 if edge e is already labelled
6539 * 11 continue with the next edge
6540 * 12 w <- G.adjacentVertex(t,e)
6541 * 13 if vertex w is not discovered and not explored
6542 * 14 label e as tree-edge
6543 * 15 label w as discovered
6544 * 16 S.push(w)
6545 * 17 continue at 5
6546 * 18 else if vertex w is discovered
6547 * 19 label e as back-edge
6548 * 20 else
6549 * 21 // vertex w is explored
6550 * 22 label e as forward- or cross-edge
6551 * 23 label t as explored
6552 * 24 S.pop()
6553 *
6554 * convention:
6555 * 0x10 - discovered
6556 * 0x11 - discovered and fall-through edge labelled
6557 * 0x12 - discovered and fall-through and branch edges labelled
6558 * 0x20 - explored
6559 */
6560
6561enum {
6562 DISCOVERED = 0x10,
6563 EXPLORED = 0x20,
6564 FALLTHROUGH = 1,
6565 BRANCH = 2,
6566};
6567
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07006568static u32 state_htab_size(struct bpf_verifier_env *env)
6569{
6570 return env->prog->len;
6571}
6572
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006573static struct bpf_verifier_state_list **explored_state(
6574 struct bpf_verifier_env *env,
6575 int idx)
6576{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07006577 struct bpf_verifier_state *cur = env->cur_state;
6578 struct bpf_func_state *state = cur->frame[cur->curframe];
6579
6580 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006581}
6582
6583static void init_explored_state(struct bpf_verifier_env *env, int idx)
6584{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07006585 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006586}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07006587
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006588/* t, w, e - match pseudo-code above:
6589 * t - index of current instruction
6590 * w - next instruction
6591 * e - edge
6592 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07006593static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
6594 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006595{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006596 int *insn_stack = env->cfg.insn_stack;
6597 int *insn_state = env->cfg.insn_state;
6598
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006599 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
6600 return 0;
6601
6602 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
6603 return 0;
6604
6605 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08006606 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006607 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006608 return -EINVAL;
6609 }
6610
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07006611 if (e == BRANCH)
6612 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006613 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07006614
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006615 if (insn_state[w] == 0) {
6616 /* tree-edge */
6617 insn_state[t] = DISCOVERED | e;
6618 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006619 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006620 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006621 insn_stack[env->cfg.cur_stack++] = w;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006622 return 1;
6623 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07006624 if (loop_ok && env->allow_ptr_leaks)
6625 return 0;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08006626 verbose_linfo(env, t, "%d: ", t);
6627 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006628 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006629 return -EINVAL;
6630 } else if (insn_state[w] == EXPLORED) {
6631 /* forward- or cross-edge */
6632 insn_state[t] = DISCOVERED | e;
6633 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006634 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006635 return -EFAULT;
6636 }
6637 return 0;
6638}
6639
6640/* non-recursive depth-first-search to detect loops in BPF program
6641 * loop == back-edge in directed graph
6642 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006643static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006644{
6645 struct bpf_insn *insns = env->prog->insnsi;
6646 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006647 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006648 int ret = 0;
6649 int i, t;
6650
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006651 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006652 if (!insn_state)
6653 return -ENOMEM;
6654
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006655 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006656 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07006657 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006658 return -ENOMEM;
6659 }
6660
6661 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
6662 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006663 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006664
6665peek_stack:
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006666 if (env->cfg.cur_stack == 0)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006667 goto check_state;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006668 t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006669
Jiong Wang092ed092019-01-26 12:26:01 -05006670 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
6671 BPF_CLASS(insns[t].code) == BPF_JMP32) {
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006672 u8 opcode = BPF_OP(insns[t].code);
6673
6674 if (opcode == BPF_EXIT) {
6675 goto mark_explored;
6676 } else if (opcode == BPF_CALL) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07006677 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006678 if (ret == 1)
6679 goto peek_stack;
6680 else if (ret < 0)
6681 goto err_free;
Daniel Borkmann07016152016-04-05 22:33:17 +02006682 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006683 init_explored_state(env, t + 1);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08006684 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006685 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07006686 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
6687 env, false);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08006688 if (ret == 1)
6689 goto peek_stack;
6690 else if (ret < 0)
6691 goto err_free;
6692 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006693 } else if (opcode == BPF_JA) {
6694 if (BPF_SRC(insns[t].code) != BPF_K) {
6695 ret = -EINVAL;
6696 goto err_free;
6697 }
6698 /* unconditional jump with single edge */
6699 ret = push_insn(t, t + insns[t].off + 1,
Alexei Starovoitov25897262019-06-15 12:12:20 -07006700 FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006701 if (ret == 1)
6702 goto peek_stack;
6703 else if (ret < 0)
6704 goto err_free;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006705 /* unconditional jmp is not a good pruning point,
6706 * but it's marked, since backtracking needs
6707 * to record jmp history in is_state_visited().
6708 */
6709 init_explored_state(env, t + insns[t].off + 1);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07006710 /* tell verifier to check for equivalent states
6711 * after every call and jump
6712 */
Alexei Starovoitovc3de6312015-04-14 15:57:13 -07006713 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006714 init_explored_state(env, t + 1);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006715 } else {
6716 /* conditional jump with two edges */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006717 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07006718 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006719 if (ret == 1)
6720 goto peek_stack;
6721 else if (ret < 0)
6722 goto err_free;
6723
Alexei Starovoitov25897262019-06-15 12:12:20 -07006724 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006725 if (ret == 1)
6726 goto peek_stack;
6727 else if (ret < 0)
6728 goto err_free;
6729 }
6730 } else {
6731 /* all other non-branch instructions with single
6732 * fall-through edge
6733 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07006734 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006735 if (ret == 1)
6736 goto peek_stack;
6737 else if (ret < 0)
6738 goto err_free;
6739 }
6740
6741mark_explored:
6742 insn_state[t] = EXPLORED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006743 if (env->cfg.cur_stack-- <= 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006744 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006745 ret = -EFAULT;
6746 goto err_free;
6747 }
6748 goto peek_stack;
6749
6750check_state:
6751 for (i = 0; i < insn_cnt; i++) {
6752 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006753 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006754 ret = -EINVAL;
6755 goto err_free;
6756 }
6757 }
6758 ret = 0; /* cfg looks good */
6759
6760err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07006761 kvfree(insn_state);
6762 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006763 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006764 return ret;
6765}
6766
Yonghong Song838e9692018-11-19 15:29:11 -08006767/* The minimum supported BTF func info size */
6768#define MIN_BPF_FUNCINFO_SIZE 8
6769#define MAX_FUNCINFO_REC_SIZE 252
6770
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006771static int check_btf_func(struct bpf_verifier_env *env,
6772 const union bpf_attr *attr,
6773 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08006774{
Peter Oskolkovd0b28182019-01-16 10:43:01 -08006775 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08006776 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006777 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006778 struct bpf_func_info_aux *info_aux = NULL;
Yonghong Song838e9692018-11-19 15:29:11 -08006779 const struct btf_type *type;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006780 struct bpf_prog *prog;
6781 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08006782 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08006783 u32 prev_offset = 0;
Yonghong Song838e9692018-11-19 15:29:11 -08006784 int ret = 0;
6785
6786 nfuncs = attr->func_info_cnt;
6787 if (!nfuncs)
6788 return 0;
6789
6790 if (nfuncs != env->subprog_cnt) {
6791 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
6792 return -EINVAL;
6793 }
6794
6795 urec_size = attr->func_info_rec_size;
6796 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
6797 urec_size > MAX_FUNCINFO_REC_SIZE ||
6798 urec_size % sizeof(u32)) {
6799 verbose(env, "invalid func info rec size %u\n", urec_size);
6800 return -EINVAL;
6801 }
6802
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006803 prog = env->prog;
6804 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08006805
6806 urecord = u64_to_user_ptr(attr->func_info);
6807 min_size = min_t(u32, krec_size, urec_size);
6808
Yonghong Songba64e7d2018-11-24 23:20:44 -08006809 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006810 if (!krecord)
6811 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006812 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
6813 if (!info_aux)
6814 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08006815
Yonghong Song838e9692018-11-19 15:29:11 -08006816 for (i = 0; i < nfuncs; i++) {
6817 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
6818 if (ret) {
6819 if (ret == -E2BIG) {
6820 verbose(env, "nonzero tailing record in func info");
6821 /* set the size kernel expects so loader can zero
6822 * out the rest of the record.
6823 */
6824 if (put_user(min_size, &uattr->func_info_rec_size))
6825 ret = -EFAULT;
6826 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006827 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006828 }
6829
Yonghong Songba64e7d2018-11-24 23:20:44 -08006830 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08006831 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006832 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006833 }
6834
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006835 /* check insn_off */
Yonghong Song838e9692018-11-19 15:29:11 -08006836 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006837 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08006838 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006839 "nonzero insn_off %u for the first func info record",
6840 krecord[i].insn_off);
Yonghong Song838e9692018-11-19 15:29:11 -08006841 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006842 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006843 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006844 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08006845 verbose(env,
6846 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006847 krecord[i].insn_off, prev_offset);
Yonghong Song838e9692018-11-19 15:29:11 -08006848 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006849 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006850 }
6851
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006852 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08006853 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
6854 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006855 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006856 }
6857
6858 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08006859 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08006860 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08006861 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08006862 krecord[i].type_id);
Yonghong Song838e9692018-11-19 15:29:11 -08006863 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006864 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006865 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08006866 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006867 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08006868 urecord += urec_size;
6869 }
6870
Yonghong Songba64e7d2018-11-24 23:20:44 -08006871 prog->aux->func_info = krecord;
6872 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006873 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08006874 return 0;
6875
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006876err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08006877 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006878 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08006879 return ret;
6880}
6881
Yonghong Songba64e7d2018-11-24 23:20:44 -08006882static void adjust_btf_func(struct bpf_verifier_env *env)
6883{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006884 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08006885 int i;
6886
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006887 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08006888 return;
6889
6890 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006891 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08006892}
6893
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006894#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
6895 sizeof(((struct bpf_line_info *)(0))->line_col))
6896#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
6897
6898static int check_btf_line(struct bpf_verifier_env *env,
6899 const union bpf_attr *attr,
6900 union bpf_attr __user *uattr)
6901{
6902 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
6903 struct bpf_subprog_info *sub;
6904 struct bpf_line_info *linfo;
6905 struct bpf_prog *prog;
6906 const struct btf *btf;
6907 void __user *ulinfo;
6908 int err;
6909
6910 nr_linfo = attr->line_info_cnt;
6911 if (!nr_linfo)
6912 return 0;
6913
6914 rec_size = attr->line_info_rec_size;
6915 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
6916 rec_size > MAX_LINEINFO_REC_SIZE ||
6917 rec_size & (sizeof(u32) - 1))
6918 return -EINVAL;
6919
6920 /* Need to zero it in case the userspace may
6921 * pass in a smaller bpf_line_info object.
6922 */
6923 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
6924 GFP_KERNEL | __GFP_NOWARN);
6925 if (!linfo)
6926 return -ENOMEM;
6927
6928 prog = env->prog;
6929 btf = prog->aux->btf;
6930
6931 s = 0;
6932 sub = env->subprog_info;
6933 ulinfo = u64_to_user_ptr(attr->line_info);
6934 expected_size = sizeof(struct bpf_line_info);
6935 ncopy = min_t(u32, expected_size, rec_size);
6936 for (i = 0; i < nr_linfo; i++) {
6937 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
6938 if (err) {
6939 if (err == -E2BIG) {
6940 verbose(env, "nonzero tailing record in line_info");
6941 if (put_user(expected_size,
6942 &uattr->line_info_rec_size))
6943 err = -EFAULT;
6944 }
6945 goto err_free;
6946 }
6947
6948 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
6949 err = -EFAULT;
6950 goto err_free;
6951 }
6952
6953 /*
6954 * Check insn_off to ensure
6955 * 1) strictly increasing AND
6956 * 2) bounded by prog->len
6957 *
6958 * The linfo[0].insn_off == 0 check logically falls into
6959 * the later "missing bpf_line_info for func..." case
6960 * because the first linfo[0].insn_off must be the
6961 * first sub also and the first sub must have
6962 * subprog_info[0].start == 0.
6963 */
6964 if ((i && linfo[i].insn_off <= prev_offset) ||
6965 linfo[i].insn_off >= prog->len) {
6966 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
6967 i, linfo[i].insn_off, prev_offset,
6968 prog->len);
6969 err = -EINVAL;
6970 goto err_free;
6971 }
6972
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08006973 if (!prog->insnsi[linfo[i].insn_off].code) {
6974 verbose(env,
6975 "Invalid insn code at line_info[%u].insn_off\n",
6976 i);
6977 err = -EINVAL;
6978 goto err_free;
6979 }
6980
Martin KaFai Lau23127b32018-12-13 10:41:46 -08006981 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
6982 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006983 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
6984 err = -EINVAL;
6985 goto err_free;
6986 }
6987
6988 if (s != env->subprog_cnt) {
6989 if (linfo[i].insn_off == sub[s].start) {
6990 sub[s].linfo_idx = i;
6991 s++;
6992 } else if (sub[s].start < linfo[i].insn_off) {
6993 verbose(env, "missing bpf_line_info for func#%u\n", s);
6994 err = -EINVAL;
6995 goto err_free;
6996 }
6997 }
6998
6999 prev_offset = linfo[i].insn_off;
7000 ulinfo += rec_size;
7001 }
7002
7003 if (s != env->subprog_cnt) {
7004 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
7005 env->subprog_cnt - s, s);
7006 err = -EINVAL;
7007 goto err_free;
7008 }
7009
7010 prog->aux->linfo = linfo;
7011 prog->aux->nr_linfo = nr_linfo;
7012
7013 return 0;
7014
7015err_free:
7016 kvfree(linfo);
7017 return err;
7018}
7019
7020static int check_btf_info(struct bpf_verifier_env *env,
7021 const union bpf_attr *attr,
7022 union bpf_attr __user *uattr)
7023{
7024 struct btf *btf;
7025 int err;
7026
7027 if (!attr->func_info_cnt && !attr->line_info_cnt)
7028 return 0;
7029
7030 btf = btf_get_by_fd(attr->prog_btf_fd);
7031 if (IS_ERR(btf))
7032 return PTR_ERR(btf);
7033 env->prog->aux->btf = btf;
7034
7035 err = check_btf_func(env, attr, uattr);
7036 if (err)
7037 return err;
7038
7039 err = check_btf_line(env, attr, uattr);
7040 if (err)
7041 return err;
7042
7043 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07007044}
7045
Edward Creef1174f72017-08-07 15:26:19 +01007046/* check %cur's range satisfies %old's */
7047static bool range_within(struct bpf_reg_state *old,
7048 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007049{
Edward Creeb03c9f92017-08-07 15:26:36 +01007050 return old->umin_value <= cur->umin_value &&
7051 old->umax_value >= cur->umax_value &&
7052 old->smin_value <= cur->smin_value &&
7053 old->smax_value >= cur->smax_value;
Edward Creef1174f72017-08-07 15:26:19 +01007054}
7055
7056/* Maximum number of register states that can exist at once */
7057#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
7058struct idpair {
7059 u32 old;
7060 u32 cur;
7061};
7062
7063/* If in the old state two registers had the same id, then they need to have
7064 * the same id in the new state as well. But that id could be different from
7065 * the old state, so we need to track the mapping from old to new ids.
7066 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
7067 * regs with old id 5 must also have new id 9 for the new state to be safe. But
7068 * regs with a different old id could still have new id 9, we don't care about
7069 * that.
7070 * So we look through our idmap to see if this old id has been seen before. If
7071 * so, we require the new id to match; otherwise, we add the id pair to the map.
7072 */
7073static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
7074{
7075 unsigned int i;
7076
7077 for (i = 0; i < ID_MAP_SIZE; i++) {
7078 if (!idmap[i].old) {
7079 /* Reached an empty slot; haven't seen this id before */
7080 idmap[i].old = old_id;
7081 idmap[i].cur = cur_id;
7082 return true;
7083 }
7084 if (idmap[i].old == old_id)
7085 return idmap[i].cur == cur_id;
7086 }
7087 /* We ran out of idmap slots, which should be impossible */
7088 WARN_ON_ONCE(1);
7089 return false;
7090}
7091
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007092static void clean_func_state(struct bpf_verifier_env *env,
7093 struct bpf_func_state *st)
7094{
7095 enum bpf_reg_liveness live;
7096 int i, j;
7097
7098 for (i = 0; i < BPF_REG_FP; i++) {
7099 live = st->regs[i].live;
7100 /* liveness must not touch this register anymore */
7101 st->regs[i].live |= REG_LIVE_DONE;
7102 if (!(live & REG_LIVE_READ))
7103 /* since the register is unused, clear its state
7104 * to make further comparison simpler
7105 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01007106 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007107 }
7108
7109 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
7110 live = st->stack[i].spilled_ptr.live;
7111 /* liveness must not touch this stack slot anymore */
7112 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
7113 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01007114 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007115 for (j = 0; j < BPF_REG_SIZE; j++)
7116 st->stack[i].slot_type[j] = STACK_INVALID;
7117 }
7118 }
7119}
7120
7121static void clean_verifier_state(struct bpf_verifier_env *env,
7122 struct bpf_verifier_state *st)
7123{
7124 int i;
7125
7126 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
7127 /* all regs in this state in all frames were already marked */
7128 return;
7129
7130 for (i = 0; i <= st->curframe; i++)
7131 clean_func_state(env, st->frame[i]);
7132}
7133
7134/* the parentage chains form a tree.
7135 * the verifier states are added to state lists at given insn and
7136 * pushed into state stack for future exploration.
7137 * when the verifier reaches bpf_exit insn some of the verifer states
7138 * stored in the state lists have their final liveness state already,
7139 * but a lot of states will get revised from liveness point of view when
7140 * the verifier explores other branches.
7141 * Example:
7142 * 1: r0 = 1
7143 * 2: if r1 == 100 goto pc+1
7144 * 3: r0 = 2
7145 * 4: exit
7146 * when the verifier reaches exit insn the register r0 in the state list of
7147 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
7148 * of insn 2 and goes exploring further. At the insn 4 it will walk the
7149 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
7150 *
7151 * Since the verifier pushes the branch states as it sees them while exploring
7152 * the program the condition of walking the branch instruction for the second
7153 * time means that all states below this branch were already explored and
7154 * their final liveness markes are already propagated.
7155 * Hence when the verifier completes the search of state list in is_state_visited()
7156 * we can call this clean_live_states() function to mark all liveness states
7157 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
7158 * will not be used.
7159 * This function also clears the registers and stack for states that !READ
7160 * to simplify state merging.
7161 *
7162 * Important note here that walking the same branch instruction in the callee
7163 * doesn't meant that the states are DONE. The verifier has to compare
7164 * the callsites
7165 */
7166static void clean_live_states(struct bpf_verifier_env *env, int insn,
7167 struct bpf_verifier_state *cur)
7168{
7169 struct bpf_verifier_state_list *sl;
7170 int i;
7171
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007172 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007173 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07007174 if (sl->state.branches)
7175 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007176 if (sl->state.insn_idx != insn ||
7177 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007178 goto next;
7179 for (i = 0; i <= cur->curframe; i++)
7180 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
7181 goto next;
7182 clean_verifier_state(env, &sl->state);
7183next:
7184 sl = sl->next;
7185 }
7186}
7187
Edward Creef1174f72017-08-07 15:26:19 +01007188/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01007189static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7190 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01007191{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007192 bool equal;
7193
Edward Creedc503a82017-08-15 20:34:35 +01007194 if (!(rold->live & REG_LIVE_READ))
7195 /* explored state didn't use this */
7196 return true;
7197
Edward Cree679c7822018-08-22 20:02:19 +01007198 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007199
7200 if (rold->type == PTR_TO_STACK)
7201 /* two stack pointers are equal only if they're pointing to
7202 * the same stack frame, since fp-8 in foo != fp-8 in bar
7203 */
7204 return equal && rold->frameno == rcur->frameno;
7205
7206 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01007207 return true;
7208
7209 if (rold->type == NOT_INIT)
7210 /* explored state can't have used this */
7211 return true;
7212 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007213 return false;
Edward Creef1174f72017-08-07 15:26:19 +01007214 switch (rold->type) {
7215 case SCALAR_VALUE:
7216 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007217 if (!rold->precise && !rcur->precise)
7218 return true;
Edward Creef1174f72017-08-07 15:26:19 +01007219 /* new val must satisfy old val knowledge */
7220 return range_within(rold, rcur) &&
7221 tnum_in(rold->var_off, rcur->var_off);
7222 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08007223 /* We're trying to use a pointer in place of a scalar.
7224 * Even if the scalar was unbounded, this could lead to
7225 * pointer leaks because scalars are allowed to leak
7226 * while pointers are not. We could make this safe in
7227 * special cases if root is calling us, but it's
7228 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01007229 */
Jann Horn179d1c52017-12-18 20:11:59 -08007230 return false;
Edward Creef1174f72017-08-07 15:26:19 +01007231 }
7232 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01007233 /* If the new min/max/var_off satisfy the old ones and
7234 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08007235 * 'id' is not compared, since it's only used for maps with
7236 * bpf_spin_lock inside map element and in such cases if
7237 * the rest of the prog is valid for one map element then
7238 * it's valid for all map elements regardless of the key
7239 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01007240 */
7241 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
7242 range_within(rold, rcur) &&
7243 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01007244 case PTR_TO_MAP_VALUE_OR_NULL:
7245 /* a PTR_TO_MAP_VALUE could be safe to use as a
7246 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
7247 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
7248 * checked, doing so could have affected others with the same
7249 * id, and we can't check for that because we lost the id when
7250 * we converted to a PTR_TO_MAP_VALUE.
7251 */
7252 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
7253 return false;
7254 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
7255 return false;
7256 /* Check our ids match any regs they're supposed to */
7257 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007258 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01007259 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007260 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01007261 return false;
7262 /* We must have at least as much range as the old ptr
7263 * did, so that any accesses which were safe before are
7264 * still safe. This is true even if old range < old off,
7265 * since someone could have accessed through (ptr - k), or
7266 * even done ptr -= k in a register, to get a safe access.
7267 */
7268 if (rold->range > rcur->range)
7269 return false;
7270 /* If the offsets don't match, we can't trust our alignment;
7271 * nor can we be sure that we won't fall out of range.
7272 */
7273 if (rold->off != rcur->off)
7274 return false;
7275 /* id relations must be preserved */
7276 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
7277 return false;
7278 /* new val must satisfy old val knowledge */
7279 return range_within(rold, rcur) &&
7280 tnum_in(rold->var_off, rcur->var_off);
7281 case PTR_TO_CTX:
7282 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01007283 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07007284 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07007285 case PTR_TO_SOCKET:
7286 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08007287 case PTR_TO_SOCK_COMMON:
7288 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08007289 case PTR_TO_TCP_SOCK:
7290 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07007291 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01007292 /* Only valid matches are exact, which memcmp() above
7293 * would have accepted
7294 */
7295 default:
7296 /* Don't know what's going on, just say it's not safe */
7297 return false;
7298 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007299
Edward Creef1174f72017-08-07 15:26:19 +01007300 /* Shouldn't get here; if we do, say it's not safe */
7301 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007302 return false;
7303}
7304
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007305static bool stacksafe(struct bpf_func_state *old,
7306 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007307 struct idpair *idmap)
7308{
7309 int i, spi;
7310
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007311 /* walk slots of the explored stack and ignore any additional
7312 * slots in the current stack, since explored(safe) state
7313 * didn't use them
7314 */
7315 for (i = 0; i < old->allocated_stack; i++) {
7316 spi = i / BPF_REG_SIZE;
7317
Alexei Starovoitovb2339202018-12-13 11:42:31 -08007318 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
7319 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08007320 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +00007321 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -08007322 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08007323
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007324 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
7325 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -08007326
7327 /* explored stack has more populated slots than current stack
7328 * and these slots were used
7329 */
7330 if (i >= cur->allocated_stack)
7331 return false;
7332
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08007333 /* if old state was safe with misc data in the stack
7334 * it will be safe with zero-initialized stack.
7335 * The opposite is not true
7336 */
7337 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
7338 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
7339 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007340 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
7341 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
7342 /* Ex: old explored (safe) state has STACK_SPILL in
7343 * this stack slot, but current has has STACK_MISC ->
7344 * this verifier states are not equivalent,
7345 * return false to continue verification of this path
7346 */
7347 return false;
7348 if (i % BPF_REG_SIZE)
7349 continue;
7350 if (old->stack[spi].slot_type[0] != STACK_SPILL)
7351 continue;
7352 if (!regsafe(&old->stack[spi].spilled_ptr,
7353 &cur->stack[spi].spilled_ptr,
7354 idmap))
7355 /* when explored and current stack slot are both storing
7356 * spilled registers, check that stored pointers types
7357 * are the same as well.
7358 * Ex: explored safe path could have stored
7359 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
7360 * but current path has stored:
7361 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
7362 * such verifier states are not equivalent.
7363 * return false to continue verification of this path
7364 */
7365 return false;
7366 }
7367 return true;
7368}
7369
Joe Stringerfd978bf72018-10-02 13:35:35 -07007370static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
7371{
7372 if (old->acquired_refs != cur->acquired_refs)
7373 return false;
7374 return !memcmp(old->refs, cur->refs,
7375 sizeof(*old->refs) * old->acquired_refs);
7376}
7377
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007378/* compare two verifier states
7379 *
7380 * all states stored in state_list are known to be valid, since
7381 * verifier reached 'bpf_exit' instruction through them
7382 *
7383 * this function is called when verifier exploring different branches of
7384 * execution popped from the state stack. If it sees an old state that has
7385 * more strict register state and more strict stack state then this execution
7386 * branch doesn't need to be explored further, since verifier already
7387 * concluded that more strict state leads to valid finish.
7388 *
7389 * Therefore two states are equivalent if register state is more conservative
7390 * and explored stack state is more conservative than the current one.
7391 * Example:
7392 * explored current
7393 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
7394 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
7395 *
7396 * In other words if current stack state (one being explored) has more
7397 * valid slots than old one that already passed validation, it means
7398 * the verifier can stop exploring and conclude that current state is valid too
7399 *
7400 * Similarly with registers. If explored state has register type as invalid
7401 * whereas register type in current state is meaningful, it means that
7402 * the current state will reach 'bpf_exit' instruction safely
7403 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007404static bool func_states_equal(struct bpf_func_state *old,
7405 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007406{
Edward Creef1174f72017-08-07 15:26:19 +01007407 struct idpair *idmap;
7408 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007409 int i;
7410
Edward Creef1174f72017-08-07 15:26:19 +01007411 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
7412 /* If we failed to allocate the idmap, just say it's not safe */
7413 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007414 return false;
Edward Creef1174f72017-08-07 15:26:19 +01007415
7416 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +01007417 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +01007418 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007419 }
7420
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007421 if (!stacksafe(old, cur, idmap))
7422 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -07007423
7424 if (!refsafe(old, cur))
7425 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +01007426 ret = true;
7427out_free:
7428 kfree(idmap);
7429 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007430}
7431
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007432static bool states_equal(struct bpf_verifier_env *env,
7433 struct bpf_verifier_state *old,
7434 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +01007435{
Edward Creedc503a82017-08-15 20:34:35 +01007436 int i;
7437
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007438 if (old->curframe != cur->curframe)
7439 return false;
7440
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007441 /* Verification state from speculative execution simulation
7442 * must never prune a non-speculative execution one.
7443 */
7444 if (old->speculative && !cur->speculative)
7445 return false;
7446
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08007447 if (old->active_spin_lock != cur->active_spin_lock)
7448 return false;
7449
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007450 /* for states to be equal callsites have to be the same
7451 * and all frame states need to be equivalent
7452 */
7453 for (i = 0; i <= old->curframe; i++) {
7454 if (old->frame[i]->callsite != cur->frame[i]->callsite)
7455 return false;
7456 if (!func_states_equal(old->frame[i], cur->frame[i]))
7457 return false;
7458 }
7459 return true;
7460}
7461
Jiong Wang5327ed32019-05-24 23:25:12 +01007462/* Return 0 if no propagation happened. Return negative error code if error
7463 * happened. Otherwise, return the propagated bit.
7464 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007465static int propagate_liveness_reg(struct bpf_verifier_env *env,
7466 struct bpf_reg_state *reg,
7467 struct bpf_reg_state *parent_reg)
7468{
Jiong Wang5327ed32019-05-24 23:25:12 +01007469 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
7470 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007471 int err;
7472
Jiong Wang5327ed32019-05-24 23:25:12 +01007473 /* When comes here, read flags of PARENT_REG or REG could be any of
7474 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
7475 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
7476 */
7477 if (parent_flag == REG_LIVE_READ64 ||
7478 /* Or if there is no read flag from REG. */
7479 !flag ||
7480 /* Or if the read flag from REG is the same as PARENT_REG. */
7481 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007482 return 0;
7483
Jiong Wang5327ed32019-05-24 23:25:12 +01007484 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007485 if (err)
7486 return err;
7487
Jiong Wang5327ed32019-05-24 23:25:12 +01007488 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007489}
7490
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007491/* A write screens off any subsequent reads; but write marks come from the
7492 * straight-line code between a state and its parent. When we arrive at an
7493 * equivalent state (jump target or such) we didn't arrive by the straight-line
7494 * code, so read marks in the state must propagate to the parent regardless
7495 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +01007496 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007497 */
7498static int propagate_liveness(struct bpf_verifier_env *env,
7499 const struct bpf_verifier_state *vstate,
7500 struct bpf_verifier_state *vparent)
7501{
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007502 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007503 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007504 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007505
7506 if (vparent->curframe != vstate->curframe) {
7507 WARN(1, "propagate_live: parent frame %d current frame %d\n",
7508 vparent->curframe, vstate->curframe);
7509 return -EFAULT;
7510 }
Edward Creedc503a82017-08-15 20:34:35 +01007511 /* Propagate read liveness of registers... */
7512 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -07007513 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007514 parent = vparent->frame[frame];
7515 state = vstate->frame[frame];
7516 parent_reg = parent->regs;
7517 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -07007518 /* We don't need to worry about FP liveness, it's read-only */
7519 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007520 err = propagate_liveness_reg(env, &state_reg[i],
7521 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +01007522 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007523 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +01007524 if (err == REG_LIVE_READ64)
7525 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +01007526 }
Edward Creedc503a82017-08-15 20:34:35 +01007527
Jiong Wang1b04aee2019-04-12 22:59:34 +01007528 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007529 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
7530 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007531 parent_reg = &parent->stack[i].spilled_ptr;
7532 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007533 err = propagate_liveness_reg(env, state_reg,
7534 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +01007535 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007536 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007537 }
Edward Creedc503a82017-08-15 20:34:35 +01007538 }
Jiong Wang5327ed32019-05-24 23:25:12 +01007539 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01007540}
7541
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07007542/* find precise scalars in the previous equivalent state and
7543 * propagate them into the current state
7544 */
7545static int propagate_precision(struct bpf_verifier_env *env,
7546 const struct bpf_verifier_state *old)
7547{
7548 struct bpf_reg_state *state_reg;
7549 struct bpf_func_state *state;
7550 int i, err = 0;
7551
7552 state = old->frame[old->curframe];
7553 state_reg = state->regs;
7554 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
7555 if (state_reg->type != SCALAR_VALUE ||
7556 !state_reg->precise)
7557 continue;
7558 if (env->log.level & BPF_LOG_LEVEL2)
7559 verbose(env, "propagating r%d\n", i);
7560 err = mark_chain_precision(env, i);
7561 if (err < 0)
7562 return err;
7563 }
7564
7565 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
7566 if (state->stack[i].slot_type[0] != STACK_SPILL)
7567 continue;
7568 state_reg = &state->stack[i].spilled_ptr;
7569 if (state_reg->type != SCALAR_VALUE ||
7570 !state_reg->precise)
7571 continue;
7572 if (env->log.level & BPF_LOG_LEVEL2)
7573 verbose(env, "propagating fp%d\n",
7574 (-i - 1) * BPF_REG_SIZE);
7575 err = mark_chain_precision_stack(env, i);
7576 if (err < 0)
7577 return err;
7578 }
7579 return 0;
7580}
7581
Alexei Starovoitov25897262019-06-15 12:12:20 -07007582static bool states_maybe_looping(struct bpf_verifier_state *old,
7583 struct bpf_verifier_state *cur)
7584{
7585 struct bpf_func_state *fold, *fcur;
7586 int i, fr = cur->curframe;
7587
7588 if (old->curframe != fr)
7589 return false;
7590
7591 fold = old->frame[fr];
7592 fcur = cur->frame[fr];
7593 for (i = 0; i < MAX_BPF_REG; i++)
7594 if (memcmp(&fold->regs[i], &fcur->regs[i],
7595 offsetof(struct bpf_reg_state, parent)))
7596 return false;
7597 return true;
7598}
7599
7600
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007601static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007602{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007603 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007604 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +01007605 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08007606 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -07007607 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007608
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007609 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007610 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007611 /* this 'insn_idx' instruction wasn't marked, so we will not
7612 * be doing state search here
7613 */
7614 return 0;
7615
Alexei Starovoitov25897262019-06-15 12:12:20 -07007616 /* bpf progs typically have pruning point every 4 instructions
7617 * http://vger.kernel.org/bpfconf2019.html#session-1
7618 * Do not add new state for future pruning if the verifier hasn't seen
7619 * at least 2 jumps and at least 8 instructions.
7620 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
7621 * In tests that amounts to up to 50% reduction into total verifier
7622 * memory consumption and 20% verifier time speedup.
7623 */
7624 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
7625 env->insn_processed - env->prev_insn_processed >= 8)
7626 add_new_state = true;
7627
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007628 pprev = explored_state(env, insn_idx);
7629 sl = *pprev;
7630
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007631 clean_live_states(env, insn_idx, cur);
7632
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007633 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007634 states_cnt++;
7635 if (sl->state.insn_idx != insn_idx)
7636 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -07007637 if (sl->state.branches) {
7638 if (states_maybe_looping(&sl->state, cur) &&
7639 states_equal(env, &sl->state, cur)) {
7640 verbose_linfo(env, insn_idx, "; ");
7641 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
7642 return -EINVAL;
7643 }
7644 /* if the verifier is processing a loop, avoid adding new state
7645 * too often, since different loop iterations have distinct
7646 * states and may not help future pruning.
7647 * This threshold shouldn't be too low to make sure that
7648 * a loop with large bound will be rejected quickly.
7649 * The most abusive loop will be:
7650 * r1 += 1
7651 * if r1 < 1000000 goto pc-2
7652 * 1M insn_procssed limit / 100 == 10k peak states.
7653 * This threshold shouldn't be too high either, since states
7654 * at the end of the loop are likely to be useful in pruning.
7655 */
7656 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
7657 env->insn_processed - env->prev_insn_processed < 100)
7658 add_new_state = false;
7659 goto miss;
7660 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007661 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007662 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007663 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +01007664 * prune the search.
7665 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +01007666 * If we have any write marks in env->cur_state, they
7667 * will prevent corresponding reads in the continuation
7668 * from reaching our parent (an explored_state). Our
7669 * own state will get the read marks recorded, but
7670 * they'll be immediately forgotten as we're pruning
7671 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007672 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007673 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07007674
7675 /* if previous state reached the exit with precision and
7676 * current state is equivalent to it (except precsion marks)
7677 * the precision needs to be propagated back in
7678 * the current state.
7679 */
7680 err = err ? : push_jmp_history(env, cur);
7681 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007682 if (err)
7683 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007684 return 1;
Edward Creedc503a82017-08-15 20:34:35 +01007685 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07007686miss:
7687 /* when new state is not going to be added do not increase miss count.
7688 * Otherwise several loop iterations will remove the state
7689 * recorded earlier. The goal of these heuristics is to have
7690 * states from some iterations of the loop (some in the beginning
7691 * and some at the end) to help pruning.
7692 */
7693 if (add_new_state)
7694 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007695 /* heuristic to determine whether this state is beneficial
7696 * to keep checking from state equivalence point of view.
7697 * Higher numbers increase max_states_per_insn and verification time,
7698 * but do not meaningfully decrease insn_processed.
7699 */
7700 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
7701 /* the state is unlikely to be useful. Remove it to
7702 * speed up verification
7703 */
7704 *pprev = sl->next;
7705 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07007706 u32 br = sl->state.branches;
7707
7708 WARN_ONCE(br,
7709 "BUG live_done but branches_to_explore %d\n",
7710 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007711 free_verifier_state(&sl->state, false);
7712 kfree(sl);
7713 env->peak_states--;
7714 } else {
7715 /* cannot free this state, since parentage chain may
7716 * walk it later. Add it for free_list instead to
7717 * be freed at the end of verification
7718 */
7719 sl->next = env->free_list;
7720 env->free_list = sl;
7721 }
7722 sl = *pprev;
7723 continue;
7724 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007725next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007726 pprev = &sl->next;
7727 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007728 }
7729
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007730 if (env->max_states_per_insn < states_cnt)
7731 env->max_states_per_insn = states_cnt;
7732
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08007733 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007734 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08007735
Alexei Starovoitov25897262019-06-15 12:12:20 -07007736 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007737 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -07007738
7739 /* There were no equivalent states, remember the current one.
7740 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007741 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -07007742 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007743 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -07007744 * again on the way to bpf_exit.
7745 * When looping the sl->state.branches will be > 0 and this state
7746 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007747 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007748 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007749 if (!new_sl)
7750 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007751 env->total_states++;
7752 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -07007753 env->prev_jmps_processed = env->jmps_processed;
7754 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007755
7756 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +01007757 new = &new_sl->state;
7758 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07007759 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +01007760 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07007761 kfree(new_sl);
7762 return err;
7763 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007764 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -07007765 WARN_ONCE(new->branches != 1,
7766 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007767
Alexei Starovoitov25897262019-06-15 12:12:20 -07007768 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007769 cur->first_insn_idx = insn_idx;
7770 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007771 new_sl->next = *explored_state(env, insn_idx);
7772 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -08007773 /* connect new state to parentage chain. Current frame needs all
7774 * registers connected. Only r6 - r9 of the callers are alive (pushed
7775 * to the stack implicitly by JITs) so in callers' frames connect just
7776 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
7777 * the state of the call instruction (with WRITTEN set), and r0 comes
7778 * from callee with its full parentage chain, anyway.
7779 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +01007780 /* clear write marks in current state: the writes we did are not writes
7781 * our child did, so they don't screen off its reads from us.
7782 * (There are no read marks in current state, because reads always mark
7783 * their parent and current state never has children yet. Only
7784 * explored_states can get read marks.)
7785 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -07007786 for (j = 0; j <= cur->curframe; j++) {
7787 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
7788 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
7789 for (i = 0; i < BPF_REG_FP; i++)
7790 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
7791 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007792
7793 /* all stack frames are accessible from callee, clear them all */
7794 for (j = 0; j <= cur->curframe; j++) {
7795 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +01007796 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007797
Edward Cree679c7822018-08-22 20:02:19 +01007798 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08007799 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01007800 frame->stack[i].spilled_ptr.parent =
7801 &newframe->stack[i].spilled_ptr;
7802 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007803 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007804 return 0;
7805}
7806
Joe Stringerc64b7982018-10-02 13:35:33 -07007807/* Return true if it's OK to have the same insn return a different type. */
7808static bool reg_type_mismatch_ok(enum bpf_reg_type type)
7809{
7810 switch (type) {
7811 case PTR_TO_CTX:
7812 case PTR_TO_SOCKET:
7813 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08007814 case PTR_TO_SOCK_COMMON:
7815 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08007816 case PTR_TO_TCP_SOCK:
7817 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07007818 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -07007819 case PTR_TO_BTF_ID:
Joe Stringerc64b7982018-10-02 13:35:33 -07007820 return false;
7821 default:
7822 return true;
7823 }
7824}
7825
7826/* If an instruction was previously used with particular pointer types, then we
7827 * need to be careful to avoid cases such as the below, where it may be ok
7828 * for one branch accessing the pointer, but not ok for the other branch:
7829 *
7830 * R1 = sock_ptr
7831 * goto X;
7832 * ...
7833 * R1 = some_other_valid_ptr;
7834 * goto X;
7835 * ...
7836 * R2 = *(u32 *)(R1 + 0);
7837 */
7838static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
7839{
7840 return src != prev && (!reg_type_mismatch_ok(src) ||
7841 !reg_type_mismatch_ok(prev));
7842}
7843
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007844static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007845{
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08007846 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007847 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007848 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007849 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007850 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007851 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007852
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007853 for (;;) {
7854 struct bpf_insn *insn;
7855 u8 class;
7856 int err;
7857
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007858 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007859 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007860 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007861 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007862 return -EFAULT;
7863 }
7864
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007865 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007866 class = BPF_CLASS(insn->code);
7867
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007868 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007869 verbose(env,
7870 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007871 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007872 return -E2BIG;
7873 }
7874
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007875 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007876 if (err < 0)
7877 return err;
7878 if (err == 1) {
7879 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007880 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007881 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007882 verbose(env, "\nfrom %d to %d%s: safe\n",
7883 env->prev_insn_idx, env->insn_idx,
7884 env->cur_state->speculative ?
7885 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007886 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007887 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007888 }
7889 goto process_bpf_exit;
7890 }
7891
Alexei Starovoitovc3494802018-12-03 22:46:04 -08007892 if (signal_pending(current))
7893 return -EAGAIN;
7894
Daniel Borkmann3c2ce602017-05-18 03:00:06 +02007895 if (need_resched())
7896 cond_resched();
7897
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007898 if (env->log.level & BPF_LOG_LEVEL2 ||
7899 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
7900 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007901 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -07007902 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007903 verbose(env, "\nfrom %d to %d%s:",
7904 env->prev_insn_idx, env->insn_idx,
7905 env->cur_state->speculative ?
7906 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007907 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007908 do_print_state = false;
7909 }
7910
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007911 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01007912 const struct bpf_insn_cbs cbs = {
7913 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +01007914 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +01007915 };
7916
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007917 verbose_linfo(env, env->insn_idx, "; ");
7918 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +01007919 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007920 }
7921
Jakub Kicinskicae19272017-12-27 18:39:05 -08007922 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007923 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
7924 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -08007925 if (err)
7926 return err;
7927 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +01007928
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007929 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08007930 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007931 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -07007932
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007933 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007934 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007935 if (err)
7936 return err;
7937
7938 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007939 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007940
7941 /* check for reserved fields is already done */
7942
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007943 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007944 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007945 if (err)
7946 return err;
7947
Edward Creedc503a82017-08-15 20:34:35 +01007948 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007949 if (err)
7950 return err;
7951
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -07007952 src_reg_type = regs[insn->src_reg].type;
7953
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007954 /* check that memory (src_reg + off) is readable,
7955 * the state of dst_reg will be updated by this func
7956 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007957 err = check_mem_access(env, env->insn_idx, insn->src_reg,
7958 insn->off, BPF_SIZE(insn->code),
7959 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007960 if (err)
7961 return err;
7962
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007963 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007964
7965 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007966 /* saw a valid insn
7967 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007968 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007969 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007970 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007971
Joe Stringerc64b7982018-10-02 13:35:33 -07007972 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007973 /* ABuser program is trying to use the same insn
7974 * dst_reg = *(u32*) (src_reg + off)
7975 * with different pointer types:
7976 * src_reg == ctx in one branch and
7977 * src_reg == stack|map in some other branch.
7978 * Reject it.
7979 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007980 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007981 return -EINVAL;
7982 }
7983
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007984 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007985 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07007986
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007987 if (BPF_MODE(insn->code) == BPF_XADD) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007988 err = check_xadd(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007989 if (err)
7990 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007991 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007992 continue;
7993 }
7994
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007995 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007996 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007997 if (err)
7998 return err;
7999 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008000 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008001 if (err)
8002 return err;
8003
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008004 dst_reg_type = regs[insn->dst_reg].type;
8005
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008006 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008007 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8008 insn->off, BPF_SIZE(insn->code),
8009 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008010 if (err)
8011 return err;
8012
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008013 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01008014
8015 if (*prev_dst_type == NOT_INIT) {
8016 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -07008017 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008018 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008019 return -EINVAL;
8020 }
8021
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008022 } else if (class == BPF_ST) {
8023 if (BPF_MODE(insn->code) != BPF_MEM ||
8024 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008025 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008026 return -EINVAL;
8027 }
8028 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01008029 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008030 if (err)
8031 return err;
8032
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01008033 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -07008034 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02008035 insn->dst_reg,
8036 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01008037 return -EACCES;
8038 }
8039
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008040 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008041 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8042 insn->off, BPF_SIZE(insn->code),
8043 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008044 if (err)
8045 return err;
8046
Jiong Wang092ed092019-01-26 12:26:01 -05008047 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008048 u8 opcode = BPF_OP(insn->code);
8049
Alexei Starovoitov25897262019-06-15 12:12:20 -07008050 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008051 if (opcode == BPF_CALL) {
8052 if (BPF_SRC(insn->code) != BPF_K ||
8053 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008054 (insn->src_reg != BPF_REG_0 &&
8055 insn->src_reg != BPF_PSEUDO_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -05008056 insn->dst_reg != BPF_REG_0 ||
8057 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008058 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008059 return -EINVAL;
8060 }
8061
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008062 if (env->cur_state->active_spin_lock &&
8063 (insn->src_reg == BPF_PSEUDO_CALL ||
8064 insn->imm != BPF_FUNC_spin_unlock)) {
8065 verbose(env, "function calls are not allowed while holding a lock\n");
8066 return -EINVAL;
8067 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008068 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008069 err = check_func_call(env, insn, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008070 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008071 err = check_helper_call(env, insn->imm, env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008072 if (err)
8073 return err;
8074
8075 } else if (opcode == BPF_JA) {
8076 if (BPF_SRC(insn->code) != BPF_K ||
8077 insn->imm != 0 ||
8078 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05008079 insn->dst_reg != BPF_REG_0 ||
8080 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008081 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008082 return -EINVAL;
8083 }
8084
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008085 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008086 continue;
8087
8088 } else if (opcode == BPF_EXIT) {
8089 if (BPF_SRC(insn->code) != BPF_K ||
8090 insn->imm != 0 ||
8091 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05008092 insn->dst_reg != BPF_REG_0 ||
8093 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008094 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008095 return -EINVAL;
8096 }
8097
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008098 if (env->cur_state->active_spin_lock) {
8099 verbose(env, "bpf_spin_unlock is missing\n");
8100 return -EINVAL;
8101 }
8102
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008103 if (state->curframe) {
8104 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008105 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008106 if (err)
8107 return err;
8108 do_print_state = true;
8109 continue;
8110 }
8111
Joe Stringerfd978bf72018-10-02 13:35:35 -07008112 err = check_reference_leak(env);
8113 if (err)
8114 return err;
8115
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008116 err = check_return_code(env);
8117 if (err)
8118 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008119process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -07008120 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008121 err = pop_stack(env, &prev_insn_idx,
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008122 &env->insn_idx);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008123 if (err < 0) {
8124 if (err != -ENOENT)
8125 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008126 break;
8127 } else {
8128 do_print_state = true;
8129 continue;
8130 }
8131 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008132 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008133 if (err)
8134 return err;
8135 }
8136 } else if (class == BPF_LD) {
8137 u8 mode = BPF_MODE(insn->code);
8138
8139 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008140 err = check_ld_abs(env, insn);
8141 if (err)
8142 return err;
8143
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008144 } else if (mode == BPF_IMM) {
8145 err = check_ld_imm(env, insn);
8146 if (err)
8147 return err;
8148
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008149 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008150 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008151 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008152 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008153 return -EINVAL;
8154 }
8155 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008156 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008157 return -EINVAL;
8158 }
8159
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008160 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008161 }
8162
8163 return 0;
8164}
8165
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07008166static int check_map_prealloc(struct bpf_map *map)
8167{
8168 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07008169 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8170 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07008171 !(map->map_flags & BPF_F_NO_PREALLOC);
8172}
8173
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008174static bool is_tracing_prog_type(enum bpf_prog_type type)
8175{
8176 switch (type) {
8177 case BPF_PROG_TYPE_KPROBE:
8178 case BPF_PROG_TYPE_TRACEPOINT:
8179 case BPF_PROG_TYPE_PERF_EVENT:
8180 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8181 return true;
8182 default:
8183 return false;
8184 }
8185}
8186
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01008187static bool is_preallocated_map(struct bpf_map *map)
8188{
8189 if (!check_map_prealloc(map))
8190 return false;
8191 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
8192 return false;
8193 return true;
8194}
8195
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008196static int check_map_prog_compatibility(struct bpf_verifier_env *env,
8197 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07008198 struct bpf_prog *prog)
8199
8200{
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01008201 /*
8202 * Validate that trace type programs use preallocated hash maps.
8203 *
8204 * For programs attached to PERF events this is mandatory as the
8205 * perf NMI can hit any arbitrary code sequence.
8206 *
8207 * All other trace types using preallocated hash maps are unsafe as
8208 * well because tracepoint or kprobes can be inside locked regions
8209 * of the memory allocator or at a place where a recursion into the
8210 * memory allocator would see inconsistent state.
8211 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01008212 * On RT enabled kernels run-time allocation of all trace type
8213 * programs is strictly prohibited due to lock type constraints. On
8214 * !RT kernels it is allowed for backwards compatibility reasons for
8215 * now, but warnings are emitted so developers are made aware of
8216 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07008217 */
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01008218 if (is_tracing_prog_type(prog->type) && !is_preallocated_map(map)) {
8219 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008220 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07008221 return -EINVAL;
8222 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01008223 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8224 verbose(env, "trace type programs can only use preallocated hash map\n");
8225 return -EINVAL;
8226 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01008227 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
8228 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 -07008229 }
Jakub Kicinskia3884572018-01-11 20:29:09 -08008230
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008231 if ((is_tracing_prog_type(prog->type) ||
8232 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
8233 map_value_has_spin_lock(map)) {
8234 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
8235 return -EINVAL;
8236 }
8237
Jakub Kicinskia3884572018-01-11 20:29:09 -08008238 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -07008239 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -08008240 verbose(env, "offload device mismatch between prog and map\n");
8241 return -EINVAL;
8242 }
8243
Martin KaFai Lau85d33df2020-01-08 16:35:05 -08008244 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
8245 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
8246 return -EINVAL;
8247 }
8248
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07008249 return 0;
8250}
8251
Roman Gushchinb741f162018-09-28 14:45:43 +00008252static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
8253{
8254 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
8255 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
8256}
8257
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008258/* look for pseudo eBPF instructions that access map FDs and
8259 * replace them with actual map pointers
8260 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008261static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008262{
8263 struct bpf_insn *insn = env->prog->insnsi;
8264 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07008265 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008266
Daniel Borkmannf1f77142017-01-13 23:38:15 +01008267 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +01008268 if (err)
8269 return err;
8270
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008271 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008272 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008273 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008274 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008275 return -EINVAL;
8276 }
8277
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008278 if (BPF_CLASS(insn->code) == BPF_STX &&
8279 ((BPF_MODE(insn->code) != BPF_MEM &&
8280 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008281 verbose(env, "BPF_STX uses reserved fields\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008282 return -EINVAL;
8283 }
8284
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008285 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008286 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008287 struct bpf_map *map;
8288 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008289 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008290
8291 if (i == insn_cnt - 1 || insn[1].code != 0 ||
8292 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
8293 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008294 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008295 return -EINVAL;
8296 }
8297
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008298 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008299 /* valid generic load 64-bit imm */
8300 goto next_insn;
8301
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008302 /* In final convert_pseudo_ld_imm64() step, this is
8303 * converted into regular 64-bit imm load insn.
8304 */
8305 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
8306 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
8307 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
8308 insn[1].imm != 0)) {
8309 verbose(env,
8310 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008311 return -EINVAL;
8312 }
8313
Daniel Borkmann20182392019-03-04 21:08:53 +01008314 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +01008315 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008316 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008317 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +01008318 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008319 return PTR_ERR(map);
8320 }
8321
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008322 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07008323 if (err) {
8324 fdput(f);
8325 return err;
8326 }
8327
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008328 aux = &env->insn_aux_data[i];
8329 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8330 addr = (unsigned long)map;
8331 } else {
8332 u32 off = insn[1].imm;
8333
8334 if (off >= BPF_MAX_VAR_OFF) {
8335 verbose(env, "direct value offset of %u is not allowed\n", off);
8336 fdput(f);
8337 return -EINVAL;
8338 }
8339
8340 if (!map->ops->map_direct_value_addr) {
8341 verbose(env, "no direct value access support for this map type\n");
8342 fdput(f);
8343 return -EINVAL;
8344 }
8345
8346 err = map->ops->map_direct_value_addr(map, &addr, off);
8347 if (err) {
8348 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
8349 map->value_size, off);
8350 fdput(f);
8351 return err;
8352 }
8353
8354 aux->map_off = off;
8355 addr += off;
8356 }
8357
8358 insn[0].imm = (u32)addr;
8359 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008360
8361 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008362 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008363 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008364 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008365 fdput(f);
8366 goto next_insn;
8367 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008368 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008369
8370 if (env->used_map_cnt >= MAX_USED_MAPS) {
8371 fdput(f);
8372 return -E2BIG;
8373 }
8374
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008375 /* hold the map. If the program is rejected by verifier,
8376 * the map will be released by release_maps() or it
8377 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -07008378 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008379 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -08008380 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008381
8382 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -07008383 env->used_maps[env->used_map_cnt++] = map;
8384
Roman Gushchinb741f162018-09-28 14:45:43 +00008385 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +01008386 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +00008387 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -07008388 fdput(f);
8389 return -EBUSY;
8390 }
8391
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008392 fdput(f);
8393next_insn:
8394 insn++;
8395 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +01008396 continue;
8397 }
8398
8399 /* Basic sanity check before we invest more work here. */
8400 if (!bpf_opcode_in_insntable(insn->code)) {
8401 verbose(env, "unknown opcode %02x\n", insn->code);
8402 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008403 }
8404 }
8405
8406 /* now all pseudo BPF_LD_IMM64 instructions load valid
8407 * 'struct bpf_map *' into a register instead of user map_fd.
8408 * These pointers will be used later by verifier to validate map access.
8409 */
8410 return 0;
8411}
8412
8413/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008414static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008415{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +01008416 __bpf_free_used_maps(env->prog->aux, env->used_maps,
8417 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008418}
8419
8420/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008421static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008422{
8423 struct bpf_insn *insn = env->prog->insnsi;
8424 int insn_cnt = env->prog->len;
8425 int i;
8426
8427 for (i = 0; i < insn_cnt; i++, insn++)
8428 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
8429 insn->src_reg = 0;
8430}
8431
Alexei Starovoitov80419022017-03-15 18:26:41 -07008432/* single env->prog->insni[off] instruction was replaced with the range
8433 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
8434 * [0, off) and [off, end) to new locations, so the patched range stays zero
8435 */
Jiong Wangb325fbc2019-05-24 23:25:13 +01008436static int adjust_insn_aux_data(struct bpf_verifier_env *env,
8437 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -07008438{
8439 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +01008440 struct bpf_insn *insn = new_prog->insnsi;
8441 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -08008442 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -07008443
Jiong Wangb325fbc2019-05-24 23:25:13 +01008444 /* aux info at OFF always needs adjustment, no matter fast path
8445 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
8446 * original insn at old prog.
8447 */
8448 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
8449
Alexei Starovoitov80419022017-03-15 18:26:41 -07008450 if (cnt == 1)
8451 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +01008452 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -07008453 new_data = vzalloc(array_size(prog_len,
8454 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -07008455 if (!new_data)
8456 return -ENOMEM;
8457 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
8458 memcpy(new_data + off + cnt - 1, old_data + off,
8459 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +01008460 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008461 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +01008462 new_data[i].zext_dst = insn_has_def32(env, insn + i);
8463 }
Alexei Starovoitov80419022017-03-15 18:26:41 -07008464 env->insn_aux_data = new_data;
8465 vfree(old_data);
8466 return 0;
8467}
8468
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008469static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
8470{
8471 int i;
8472
8473 if (len == 1)
8474 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -04008475 /* NOTE: fake 'exit' subprog should be updated as well. */
8476 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +00008477 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008478 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -04008479 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008480 }
8481}
8482
Alexei Starovoitov80419022017-03-15 18:26:41 -07008483static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
8484 const struct bpf_insn *patch, u32 len)
8485{
8486 struct bpf_prog *new_prog;
8487
8488 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -07008489 if (IS_ERR(new_prog)) {
8490 if (PTR_ERR(new_prog) == -ERANGE)
8491 verbose(env,
8492 "insn %d cannot be patched due to 16-bit range\n",
8493 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -07008494 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -07008495 }
Jiong Wangb325fbc2019-05-24 23:25:13 +01008496 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -07008497 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008498 adjust_subprog_starts(env, off, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -07008499 return new_prog;
8500}
8501
Jakub Kicinski52875a02019-01-22 22:45:20 -08008502static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
8503 u32 off, u32 cnt)
8504{
8505 int i, j;
8506
8507 /* find first prog starting at or after off (first to remove) */
8508 for (i = 0; i < env->subprog_cnt; i++)
8509 if (env->subprog_info[i].start >= off)
8510 break;
8511 /* find first prog starting at or after off + cnt (first to stay) */
8512 for (j = i; j < env->subprog_cnt; j++)
8513 if (env->subprog_info[j].start >= off + cnt)
8514 break;
8515 /* if j doesn't start exactly at off + cnt, we are just removing
8516 * the front of previous prog
8517 */
8518 if (env->subprog_info[j].start != off + cnt)
8519 j--;
8520
8521 if (j > i) {
8522 struct bpf_prog_aux *aux = env->prog->aux;
8523 int move;
8524
8525 /* move fake 'exit' subprog as well */
8526 move = env->subprog_cnt + 1 - j;
8527
8528 memmove(env->subprog_info + i,
8529 env->subprog_info + j,
8530 sizeof(*env->subprog_info) * move);
8531 env->subprog_cnt -= j - i;
8532
8533 /* remove func_info */
8534 if (aux->func_info) {
8535 move = aux->func_info_cnt - j;
8536
8537 memmove(aux->func_info + i,
8538 aux->func_info + j,
8539 sizeof(*aux->func_info) * move);
8540 aux->func_info_cnt -= j - i;
8541 /* func_info->insn_off is set after all code rewrites,
8542 * in adjust_btf_func() - no need to adjust
8543 */
8544 }
8545 } else {
8546 /* convert i from "first prog to remove" to "first to adjust" */
8547 if (env->subprog_info[i].start == off)
8548 i++;
8549 }
8550
8551 /* update fake 'exit' subprog as well */
8552 for (; i <= env->subprog_cnt; i++)
8553 env->subprog_info[i].start -= cnt;
8554
8555 return 0;
8556}
8557
8558static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
8559 u32 cnt)
8560{
8561 struct bpf_prog *prog = env->prog;
8562 u32 i, l_off, l_cnt, nr_linfo;
8563 struct bpf_line_info *linfo;
8564
8565 nr_linfo = prog->aux->nr_linfo;
8566 if (!nr_linfo)
8567 return 0;
8568
8569 linfo = prog->aux->linfo;
8570
8571 /* find first line info to remove, count lines to be removed */
8572 for (i = 0; i < nr_linfo; i++)
8573 if (linfo[i].insn_off >= off)
8574 break;
8575
8576 l_off = i;
8577 l_cnt = 0;
8578 for (; i < nr_linfo; i++)
8579 if (linfo[i].insn_off < off + cnt)
8580 l_cnt++;
8581 else
8582 break;
8583
8584 /* First live insn doesn't match first live linfo, it needs to "inherit"
8585 * last removed linfo. prog is already modified, so prog->len == off
8586 * means no live instructions after (tail of the program was removed).
8587 */
8588 if (prog->len != off && l_cnt &&
8589 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
8590 l_cnt--;
8591 linfo[--i].insn_off = off + cnt;
8592 }
8593
8594 /* remove the line info which refer to the removed instructions */
8595 if (l_cnt) {
8596 memmove(linfo + l_off, linfo + i,
8597 sizeof(*linfo) * (nr_linfo - i));
8598
8599 prog->aux->nr_linfo -= l_cnt;
8600 nr_linfo = prog->aux->nr_linfo;
8601 }
8602
8603 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
8604 for (i = l_off; i < nr_linfo; i++)
8605 linfo[i].insn_off -= cnt;
8606
8607 /* fix up all subprogs (incl. 'exit') which start >= off */
8608 for (i = 0; i <= env->subprog_cnt; i++)
8609 if (env->subprog_info[i].linfo_idx > l_off) {
8610 /* program may have started in the removed region but
8611 * may not be fully removed
8612 */
8613 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
8614 env->subprog_info[i].linfo_idx -= l_cnt;
8615 else
8616 env->subprog_info[i].linfo_idx = l_off;
8617 }
8618
8619 return 0;
8620}
8621
8622static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
8623{
8624 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8625 unsigned int orig_prog_len = env->prog->len;
8626 int err;
8627
Jakub Kicinski08ca90a2019-01-22 22:45:24 -08008628 if (bpf_prog_is_dev_bound(env->prog->aux))
8629 bpf_prog_offload_remove_insns(env, off, cnt);
8630
Jakub Kicinski52875a02019-01-22 22:45:20 -08008631 err = bpf_remove_insns(env->prog, off, cnt);
8632 if (err)
8633 return err;
8634
8635 err = adjust_subprog_starts_after_remove(env, off, cnt);
8636 if (err)
8637 return err;
8638
8639 err = bpf_adj_linfo_after_remove(env, off, cnt);
8640 if (err)
8641 return err;
8642
8643 memmove(aux_data + off, aux_data + off + cnt,
8644 sizeof(*aux_data) * (orig_prog_len - off - cnt));
8645
8646 return 0;
8647}
8648
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01008649/* The verifier does more data flow analysis than llvm and will not
8650 * explore branches that are dead at run time. Malicious programs can
8651 * have dead code too. Therefore replace all dead at-run-time code
8652 * with 'ja -1'.
8653 *
8654 * Just nops are not optimal, e.g. if they would sit at the end of the
8655 * program and through another bug we would manage to jump there, then
8656 * we'd execute beyond program memory otherwise. Returning exception
8657 * code also wouldn't work since we can have subprogs where the dead
8658 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -08008659 */
8660static void sanitize_dead_code(struct bpf_verifier_env *env)
8661{
8662 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01008663 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -08008664 struct bpf_insn *insn = env->prog->insnsi;
8665 const int insn_cnt = env->prog->len;
8666 int i;
8667
8668 for (i = 0; i < insn_cnt; i++) {
8669 if (aux_data[i].seen)
8670 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01008671 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -08008672 }
8673}
8674
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08008675static bool insn_is_cond_jump(u8 code)
8676{
8677 u8 op;
8678
Jiong Wang092ed092019-01-26 12:26:01 -05008679 if (BPF_CLASS(code) == BPF_JMP32)
8680 return true;
8681
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08008682 if (BPF_CLASS(code) != BPF_JMP)
8683 return false;
8684
8685 op = BPF_OP(code);
8686 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
8687}
8688
8689static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
8690{
8691 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8692 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8693 struct bpf_insn *insn = env->prog->insnsi;
8694 const int insn_cnt = env->prog->len;
8695 int i;
8696
8697 for (i = 0; i < insn_cnt; i++, insn++) {
8698 if (!insn_is_cond_jump(insn->code))
8699 continue;
8700
8701 if (!aux_data[i + 1].seen)
8702 ja.off = insn->off;
8703 else if (!aux_data[i + 1 + insn->off].seen)
8704 ja.off = 0;
8705 else
8706 continue;
8707
Jakub Kicinski08ca90a2019-01-22 22:45:24 -08008708 if (bpf_prog_is_dev_bound(env->prog->aux))
8709 bpf_prog_offload_replace_insn(env, i, &ja);
8710
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08008711 memcpy(insn, &ja, sizeof(ja));
8712 }
8713}
8714
Jakub Kicinski52875a02019-01-22 22:45:20 -08008715static int opt_remove_dead_code(struct bpf_verifier_env *env)
8716{
8717 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8718 int insn_cnt = env->prog->len;
8719 int i, err;
8720
8721 for (i = 0; i < insn_cnt; i++) {
8722 int j;
8723
8724 j = 0;
8725 while (i + j < insn_cnt && !aux_data[i + j].seen)
8726 j++;
8727 if (!j)
8728 continue;
8729
8730 err = verifier_remove_insns(env, i, j);
8731 if (err)
8732 return err;
8733 insn_cnt = env->prog->len;
8734 }
8735
8736 return 0;
8737}
8738
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -08008739static int opt_remove_nops(struct bpf_verifier_env *env)
8740{
8741 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8742 struct bpf_insn *insn = env->prog->insnsi;
8743 int insn_cnt = env->prog->len;
8744 int i, err;
8745
8746 for (i = 0; i < insn_cnt; i++) {
8747 if (memcmp(&insn[i], &ja, sizeof(ja)))
8748 continue;
8749
8750 err = verifier_remove_insns(env, i, 1);
8751 if (err)
8752 return err;
8753 insn_cnt--;
8754 i--;
8755 }
8756
8757 return 0;
8758}
8759
Jiong Wangd6c23082019-05-24 23:25:18 +01008760static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
8761 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008762{
Jiong Wangd6c23082019-05-24 23:25:18 +01008763 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008764 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +01008765 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008766 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008767 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +01008768 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008769
Jiong Wangd6c23082019-05-24 23:25:18 +01008770 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008771 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +01008772 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
8773 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
8774 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008775 for (i = 0; i < len; i++) {
8776 int adj_idx = i + delta;
8777 struct bpf_insn insn;
8778
Jiong Wangd6c23082019-05-24 23:25:18 +01008779 insn = insns[adj_idx];
8780 if (!aux[adj_idx].zext_dst) {
8781 u8 code, class;
8782 u32 imm_rnd;
8783
8784 if (!rnd_hi32)
8785 continue;
8786
8787 code = insn.code;
8788 class = BPF_CLASS(code);
8789 if (insn_no_def(&insn))
8790 continue;
8791
8792 /* NOTE: arg "reg" (the fourth one) is only used for
8793 * BPF_STX which has been ruled out in above
8794 * check, it is safe to pass NULL here.
8795 */
8796 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
8797 if (class == BPF_LD &&
8798 BPF_MODE(code) == BPF_IMM)
8799 i++;
8800 continue;
8801 }
8802
8803 /* ctx load could be transformed into wider load. */
8804 if (class == BPF_LDX &&
8805 aux[adj_idx].ptr_type == PTR_TO_CTX)
8806 continue;
8807
8808 imm_rnd = get_random_int();
8809 rnd_hi32_patch[0] = insn;
8810 rnd_hi32_patch[1].imm = imm_rnd;
8811 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
8812 patch = rnd_hi32_patch;
8813 patch_len = 4;
8814 goto apply_patch_buffer;
8815 }
8816
8817 if (!bpf_jit_needs_zext())
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008818 continue;
8819
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008820 zext_patch[0] = insn;
8821 zext_patch[1].dst_reg = insn.dst_reg;
8822 zext_patch[1].src_reg = insn.dst_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +01008823 patch = zext_patch;
8824 patch_len = 2;
8825apply_patch_buffer:
8826 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008827 if (!new_prog)
8828 return -ENOMEM;
8829 env->prog = new_prog;
8830 insns = new_prog->insnsi;
8831 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +01008832 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008833 }
8834
8835 return 0;
8836}
8837
Joe Stringerc64b7982018-10-02 13:35:33 -07008838/* convert load instructions that access fields of a context type into a
8839 * sequence of instructions that access fields of the underlying structure:
8840 * struct __sk_buff -> struct sk_buff
8841 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008842 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008843static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008844{
Jakub Kicinski00176a32017-10-16 16:40:54 -07008845 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +02008846 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01008847 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008848 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -08008849 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008850 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008851 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +02008852 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008853
Daniel Borkmannb09928b2018-10-24 22:05:49 +02008854 if (ops->gen_prologue || env->seen_direct_write) {
8855 if (!ops->gen_prologue) {
8856 verbose(env, "bpf verifier is misconfigured\n");
8857 return -EINVAL;
8858 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008859 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
8860 env->prog);
8861 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008862 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008863 return -EINVAL;
8864 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -07008865 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008866 if (!new_prog)
8867 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -07008868
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008869 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01008870 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008871 }
8872 }
8873
Joe Stringerc64b7982018-10-02 13:35:33 -07008874 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008875 return 0;
8876
Jakub Kicinski3df126f2016-09-21 11:43:56 +01008877 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008878
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008879 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -07008880 bpf_convert_ctx_access_t convert_ctx_access;
8881
Daniel Borkmann62c79892017-01-12 11:51:33 +01008882 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
8883 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
8884 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -07008885 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008886 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +01008887 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
8888 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
8889 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -07008890 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008891 type = BPF_WRITE;
8892 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008893 continue;
8894
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07008895 if (type == BPF_WRITE &&
8896 env->insn_aux_data[i + delta].sanitize_stack_off) {
8897 struct bpf_insn patch[] = {
8898 /* Sanitize suspicious stack slot with zero.
8899 * There are no memory dependencies for this store,
8900 * since it's only using frame pointer and immediate
8901 * constant of zero
8902 */
8903 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
8904 env->insn_aux_data[i + delta].sanitize_stack_off,
8905 0),
8906 /* the original STX instruction will immediately
8907 * overwrite the same stack slot with appropriate value
8908 */
8909 *insn,
8910 };
8911
8912 cnt = ARRAY_SIZE(patch);
8913 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
8914 if (!new_prog)
8915 return -ENOMEM;
8916
8917 delta += cnt - 1;
8918 env->prog = new_prog;
8919 insn = new_prog->insnsi + i + delta;
8920 continue;
8921 }
8922
Joe Stringerc64b7982018-10-02 13:35:33 -07008923 switch (env->insn_aux_data[i + delta].ptr_type) {
8924 case PTR_TO_CTX:
8925 if (!ops->convert_ctx_access)
8926 continue;
8927 convert_ctx_access = ops->convert_ctx_access;
8928 break;
8929 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08008930 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -07008931 convert_ctx_access = bpf_sock_convert_ctx_access;
8932 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08008933 case PTR_TO_TCP_SOCK:
8934 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
8935 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07008936 case PTR_TO_XDP_SOCK:
8937 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
8938 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -07008939 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008940 if (type == BPF_READ) {
8941 insn->code = BPF_LDX | BPF_PROBE_MEM |
8942 BPF_SIZE((insn)->code);
8943 env->prog->aux->num_exentries++;
8944 } else if (env->prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -07008945 verbose(env, "Writes through BTF pointers are not allowed\n");
8946 return -EINVAL;
8947 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -07008948 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -07008949 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008950 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -07008951 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008952
Yonghong Song31fd8582017-06-13 15:52:13 -07008953 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +02008954 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -07008955
8956 /* If the read access is a narrower load of the field,
8957 * convert to a 4/8-byte load, to minimum program type specific
8958 * convert_ctx_access changes. If conversion is successful,
8959 * we will apply proper mask to the result.
8960 */
Daniel Borkmannf96da092017-07-02 02:13:27 +02008961 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -08008962 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
8963 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -07008964 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02008965 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -07008966
Daniel Borkmannf96da092017-07-02 02:13:27 +02008967 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008968 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +02008969 return -EINVAL;
8970 }
8971
8972 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -07008973 if (ctx_field_size == 4)
8974 size_code = BPF_W;
8975 else if (ctx_field_size == 8)
8976 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +02008977
Daniel Borkmannbc231052018-06-02 23:06:39 +02008978 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -07008979 insn->code = BPF_LDX | BPF_MEM | size_code;
8980 }
Daniel Borkmannf96da092017-07-02 02:13:27 +02008981
8982 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -07008983 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
8984 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +02008985 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
8986 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008987 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008988 return -EINVAL;
8989 }
Daniel Borkmannf96da092017-07-02 02:13:27 +02008990
8991 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +02008992 u8 shift = bpf_ctx_narrow_access_offset(
8993 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -08008994 if (ctx_field_size <= 4) {
8995 if (shift)
8996 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
8997 insn->dst_reg,
8998 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -07008999 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +02009000 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -08009001 } else {
9002 if (shift)
9003 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
9004 insn->dst_reg,
9005 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -07009006 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +02009007 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -08009008 }
Yonghong Song31fd8582017-06-13 15:52:13 -07009009 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009010
Alexei Starovoitov80419022017-03-15 18:26:41 -07009011 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009012 if (!new_prog)
9013 return -ENOMEM;
9014
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009015 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009016
9017 /* keep walking new program and skip insns we just inserted */
9018 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009019 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009020 }
9021
9022 return 0;
9023}
9024
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009025static int jit_subprogs(struct bpf_verifier_env *env)
9026{
9027 struct bpf_prog *prog = env->prog, **func, *tmp;
9028 int i, j, subprog_start, subprog_end = 0, len, subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +01009029 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009030 void *old_bpf_func;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009031 int err;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009032
Jiong Wangf910cef2018-05-02 16:17:17 -04009033 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009034 return 0;
9035
Daniel Borkmann7105e822017-12-20 13:42:57 +01009036 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009037 if (insn->code != (BPF_JMP | BPF_CALL) ||
9038 insn->src_reg != BPF_PSEUDO_CALL)
9039 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009040 /* Upon error here we cannot fall back to interpreter but
9041 * need a hard reject of the program. Thus -EFAULT is
9042 * propagated in any case.
9043 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009044 subprog = find_subprog(env, i + insn->imm + 1);
9045 if (subprog < 0) {
9046 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
9047 i + insn->imm + 1);
9048 return -EFAULT;
9049 }
9050 /* temporarily remember subprog id inside insn instead of
9051 * aux_data, since next loop will split up all insns into funcs
9052 */
Jiong Wangf910cef2018-05-02 16:17:17 -04009053 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009054 /* remember original imm in case JIT fails and fallback
9055 * to interpreter will be needed
9056 */
9057 env->insn_aux_data[i].call_imm = insn->imm;
9058 /* point imm to __bpf_call_base+1 from JITs point of view */
9059 insn->imm = 1;
9060 }
9061
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009062 err = bpf_prog_alloc_jited_linfo(prog);
9063 if (err)
9064 goto out_undo_insn;
9065
9066 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -07009067 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009068 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009069 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009070
Jiong Wangf910cef2018-05-02 16:17:17 -04009071 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009072 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04009073 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009074
9075 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -08009076 /* BPF_PROG_RUN doesn't call subprogs directly,
9077 * hence main prog stats include the runtime of subprogs.
9078 * subprogs don't have IDs and not reachable via prog_get_next_id
9079 * func[i]->aux->stats will never be accessed and stays NULL
9080 */
9081 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009082 if (!func[i])
9083 goto out_free;
9084 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
9085 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +01009086 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009087 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +01009088 if (bpf_prog_calc_tag(func[i]))
9089 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009090 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009091 func[i]->aux->func_idx = i;
9092 /* the btf and func_info will be freed only at prog->aux */
9093 func[i]->aux->btf = prog->aux->btf;
9094 func[i]->aux->func_info = prog->aux->func_info;
9095
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009096 /* Use bpf_prog_F_tag to indicate functions in stack traces.
9097 * Long term would need debug info to populate names
9098 */
9099 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -04009100 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009101 func[i]->jit_requested = 1;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009102 func[i]->aux->linfo = prog->aux->linfo;
9103 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
9104 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
9105 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009106 func[i] = bpf_int_jit_compile(func[i]);
9107 if (!func[i]->jited) {
9108 err = -ENOTSUPP;
9109 goto out_free;
9110 }
9111 cond_resched();
9112 }
9113 /* at this point all bpf functions were successfully JITed
9114 * now populate all bpf_calls with correct addresses and
9115 * run last pass of JIT
9116 */
Jiong Wangf910cef2018-05-02 16:17:17 -04009117 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009118 insn = func[i]->insnsi;
9119 for (j = 0; j < func[i]->len; j++, insn++) {
9120 if (insn->code != (BPF_JMP | BPF_CALL) ||
9121 insn->src_reg != BPF_PSEUDO_CALL)
9122 continue;
9123 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +09009124 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
9125 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009126 }
Sandipan Das2162fed2018-05-24 12:26:45 +05309127
9128 /* we use the aux data to keep a list of the start addresses
9129 * of the JITed images for each function in the program
9130 *
9131 * for some architectures, such as powerpc64, the imm field
9132 * might not be large enough to hold the offset of the start
9133 * address of the callee's JITed image from __bpf_call_base
9134 *
9135 * in such cases, we can lookup the start address of a callee
9136 * by using its subprog id, available from the off field of
9137 * the call instruction, as an index for this list
9138 */
9139 func[i]->aux->func = func;
9140 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009141 }
Jiong Wangf910cef2018-05-02 16:17:17 -04009142 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009143 old_bpf_func = func[i]->bpf_func;
9144 tmp = bpf_int_jit_compile(func[i]);
9145 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
9146 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009147 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009148 goto out_free;
9149 }
9150 cond_resched();
9151 }
9152
9153 /* finally lock prog and jit images for all functions and
9154 * populate kallsysm
9155 */
Jiong Wangf910cef2018-05-02 16:17:17 -04009156 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009157 bpf_prog_lock_ro(func[i]);
9158 bpf_prog_kallsyms_add(func[i]);
9159 }
Daniel Borkmann7105e822017-12-20 13:42:57 +01009160
9161 /* Last step: make now unused interpreter insns from main
9162 * prog consistent for later dump requests, so they can
9163 * later look the same as if they were interpreted only.
9164 */
9165 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01009166 if (insn->code != (BPF_JMP | BPF_CALL) ||
9167 insn->src_reg != BPF_PSEUDO_CALL)
9168 continue;
9169 insn->off = env->insn_aux_data[i].call_imm;
9170 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +05309171 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +01009172 }
9173
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009174 prog->jited = 1;
9175 prog->bpf_func = func[0]->bpf_func;
9176 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -04009177 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009178 bpf_prog_free_unused_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009179 return 0;
9180out_free:
Jiong Wangf910cef2018-05-02 16:17:17 -04009181 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009182 if (func[i])
9183 bpf_jit_free(func[i]);
9184 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009185out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009186 /* cleanup main prog to be interpreted */
9187 prog->jit_requested = 0;
9188 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9189 if (insn->code != (BPF_JMP | BPF_CALL) ||
9190 insn->src_reg != BPF_PSEUDO_CALL)
9191 continue;
9192 insn->off = 0;
9193 insn->imm = env->insn_aux_data[i].call_imm;
9194 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009195 bpf_prog_free_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009196 return err;
9197}
9198
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009199static int fixup_call_args(struct bpf_verifier_env *env)
9200{
David S. Miller19d28fb2018-01-11 21:27:54 -05009201#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009202 struct bpf_prog *prog = env->prog;
9203 struct bpf_insn *insn = prog->insnsi;
9204 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -05009205#endif
Quentin Monnete4052d02018-10-07 12:56:58 +01009206 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009207
Quentin Monnete4052d02018-10-07 12:56:58 +01009208 if (env->prog->jit_requested &&
9209 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -05009210 err = jit_subprogs(env);
9211 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009212 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009213 if (err == -EFAULT)
9214 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -05009215 }
9216#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009217 for (i = 0; i < prog->len; i++, insn++) {
9218 if (insn->code != (BPF_JMP | BPF_CALL) ||
9219 insn->src_reg != BPF_PSEUDO_CALL)
9220 continue;
9221 depth = get_callee_stack_depth(env, insn, i);
9222 if (depth < 0)
9223 return depth;
9224 bpf_patch_call_args(insn, depth);
9225 }
David S. Miller19d28fb2018-01-11 21:27:54 -05009226 err = 0;
9227#endif
9228 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009229}
9230
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009231/* fixup insn->imm field of bpf_call instructions
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009232 * and inline eligible helpers as explicit sequence of BPF instructions
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009233 *
9234 * this function is called after eBPF program passed verification
9235 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009236static int fixup_bpf_calls(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009237{
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009238 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009239 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009240 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009241 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009242 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +02009243 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009244 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009245 struct bpf_insn insn_buf[16];
9246 struct bpf_prog *new_prog;
9247 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009248 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009249
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009250 for (i = 0; i < insn_cnt; i++, insn++) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +01009251 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
9252 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9253 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -08009254 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +01009255 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
9256 struct bpf_insn mask_and_div[] = {
9257 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9258 /* Rx div 0 -> 0 */
9259 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
9260 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
9261 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
9262 *insn,
9263 };
9264 struct bpf_insn mask_and_mod[] = {
9265 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9266 /* Rx mod 0 -> Rx */
9267 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
9268 *insn,
9269 };
9270 struct bpf_insn *patchlet;
9271
9272 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9273 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
9274 patchlet = mask_and_div + (is64 ? 1 : 0);
9275 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
9276 } else {
9277 patchlet = mask_and_mod + (is64 ? 1 : 0);
9278 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
9279 }
9280
9281 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -08009282 if (!new_prog)
9283 return -ENOMEM;
9284
9285 delta += cnt - 1;
9286 env->prog = prog = new_prog;
9287 insn = new_prog->insnsi + i + delta;
9288 continue;
9289 }
9290
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02009291 if (BPF_CLASS(insn->code) == BPF_LD &&
9292 (BPF_MODE(insn->code) == BPF_ABS ||
9293 BPF_MODE(insn->code) == BPF_IND)) {
9294 cnt = env->ops->gen_ld_abs(insn, insn_buf);
9295 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9296 verbose(env, "bpf verifier is misconfigured\n");
9297 return -EINVAL;
9298 }
9299
9300 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9301 if (!new_prog)
9302 return -ENOMEM;
9303
9304 delta += cnt - 1;
9305 env->prog = prog = new_prog;
9306 insn = new_prog->insnsi + i + delta;
9307 continue;
9308 }
9309
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009310 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
9311 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
9312 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
9313 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
9314 struct bpf_insn insn_buf[16];
9315 struct bpf_insn *patch = &insn_buf[0];
9316 bool issrc, isneg;
9317 u32 off_reg;
9318
9319 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +01009320 if (!aux->alu_state ||
9321 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009322 continue;
9323
9324 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
9325 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
9326 BPF_ALU_SANITIZE_SRC;
9327
9328 off_reg = issrc ? insn->src_reg : insn->dst_reg;
9329 if (isneg)
9330 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9331 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
9332 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
9333 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
9334 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
9335 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
9336 if (issrc) {
9337 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
9338 off_reg);
9339 insn->src_reg = BPF_REG_AX;
9340 } else {
9341 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
9342 BPF_REG_AX);
9343 }
9344 if (isneg)
9345 insn->code = insn->code == code_add ?
9346 code_sub : code_add;
9347 *patch++ = *insn;
9348 if (issrc && isneg)
9349 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9350 cnt = patch - insn_buf;
9351
9352 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9353 if (!new_prog)
9354 return -ENOMEM;
9355
9356 delta += cnt - 1;
9357 env->prog = prog = new_prog;
9358 insn = new_prog->insnsi + i + delta;
9359 continue;
9360 }
9361
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009362 if (insn->code != (BPF_JMP | BPF_CALL))
9363 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009364 if (insn->src_reg == BPF_PSEUDO_CALL)
9365 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009366
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009367 if (insn->imm == BPF_FUNC_get_route_realm)
9368 prog->dst_needed = 1;
9369 if (insn->imm == BPF_FUNC_get_prandom_u32)
9370 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -05009371 if (insn->imm == BPF_FUNC_override_return)
9372 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009373 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -04009374 /* If we tail call into other programs, we
9375 * cannot make any assumptions since they can
9376 * be replaced dynamically during runtime in
9377 * the program array.
9378 */
9379 prog->cb_access = 1;
Alexei Starovoitov80a58d02017-05-30 13:31:30 -07009380 env->prog->aux->stack_depth = MAX_BPF_STACK;
Jiong Wange6478152018-11-08 04:08:42 -05009381 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -04009382
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009383 /* mark bpf_tail_call as different opcode to avoid
9384 * conditional branch in the interpeter for every normal
9385 * call and to prevent accidental JITing by JIT compiler
9386 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009387 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009388 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -07009389 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -08009390
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009391 aux = &env->insn_aux_data[i + delta];
Daniel Borkmanncc52d912019-12-19 22:19:50 +01009392 if (env->allow_ptr_leaks && !expect_blinding &&
9393 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009394 !bpf_map_key_poisoned(aux) &&
9395 !bpf_map_ptr_poisoned(aux) &&
9396 !bpf_map_ptr_unpriv(aux)) {
9397 struct bpf_jit_poke_descriptor desc = {
9398 .reason = BPF_POKE_REASON_TAIL_CALL,
9399 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
9400 .tail_call.key = bpf_map_key_immediate(aux),
9401 };
9402
9403 ret = bpf_jit_add_poke_descriptor(prog, &desc);
9404 if (ret < 0) {
9405 verbose(env, "adding tail call poke descriptor failed\n");
9406 return ret;
9407 }
9408
9409 insn->imm = ret + 1;
9410 continue;
9411 }
9412
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009413 if (!bpf_map_ptr_unpriv(aux))
9414 continue;
9415
Alexei Starovoitovb2157392018-01-07 17:33:02 -08009416 /* instead of changing every JIT dealing with tail_call
9417 * emit two extra insns:
9418 * if (index >= max_entries) goto out;
9419 * index &= array->index_mask;
9420 * to avoid out-of-bounds cpu speculation
9421 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009422 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +00009423 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -08009424 return -EINVAL;
9425 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009426
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009427 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -08009428 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
9429 map_ptr->max_entries, 2);
9430 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
9431 container_of(map_ptr,
9432 struct bpf_array,
9433 map)->index_mask);
9434 insn_buf[2] = *insn;
9435 cnt = 3;
9436 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9437 if (!new_prog)
9438 return -ENOMEM;
9439
9440 delta += cnt - 1;
9441 env->prog = prog = new_prog;
9442 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009443 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009444 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009445
Daniel Borkmann89c63072017-08-19 03:12:45 +02009446 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +02009447 * and other inlining handlers are currently limited to 64 bit
9448 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +02009449 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -08009450 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02009451 (insn->imm == BPF_FUNC_map_lookup_elem ||
9452 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +02009453 insn->imm == BPF_FUNC_map_delete_elem ||
9454 insn->imm == BPF_FUNC_map_push_elem ||
9455 insn->imm == BPF_FUNC_map_pop_elem ||
9456 insn->imm == BPF_FUNC_map_peek_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009457 aux = &env->insn_aux_data[i + delta];
9458 if (bpf_map_ptr_poisoned(aux))
9459 goto patch_call_imm;
9460
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009461 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +02009462 ops = map_ptr->ops;
9463 if (insn->imm == BPF_FUNC_map_lookup_elem &&
9464 ops->map_gen_lookup) {
9465 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
9466 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9467 verbose(env, "bpf verifier is misconfigured\n");
9468 return -EINVAL;
9469 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009470
Daniel Borkmann09772d92018-06-02 23:06:35 +02009471 new_prog = bpf_patch_insn_data(env, i + delta,
9472 insn_buf, cnt);
9473 if (!new_prog)
9474 return -ENOMEM;
9475
9476 delta += cnt - 1;
9477 env->prog = prog = new_prog;
9478 insn = new_prog->insnsi + i + delta;
9479 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009480 }
9481
Daniel Borkmann09772d92018-06-02 23:06:35 +02009482 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
9483 (void *(*)(struct bpf_map *map, void *key))NULL));
9484 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
9485 (int (*)(struct bpf_map *map, void *key))NULL));
9486 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
9487 (int (*)(struct bpf_map *map, void *key, void *value,
9488 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +02009489 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
9490 (int (*)(struct bpf_map *map, void *value,
9491 u64 flags))NULL));
9492 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
9493 (int (*)(struct bpf_map *map, void *value))NULL));
9494 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
9495 (int (*)(struct bpf_map *map, void *value))NULL));
9496
Daniel Borkmann09772d92018-06-02 23:06:35 +02009497 switch (insn->imm) {
9498 case BPF_FUNC_map_lookup_elem:
9499 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
9500 __bpf_call_base;
9501 continue;
9502 case BPF_FUNC_map_update_elem:
9503 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
9504 __bpf_call_base;
9505 continue;
9506 case BPF_FUNC_map_delete_elem:
9507 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
9508 __bpf_call_base;
9509 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +02009510 case BPF_FUNC_map_push_elem:
9511 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
9512 __bpf_call_base;
9513 continue;
9514 case BPF_FUNC_map_pop_elem:
9515 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
9516 __bpf_call_base;
9517 continue;
9518 case BPF_FUNC_map_peek_elem:
9519 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
9520 __bpf_call_base;
9521 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +02009522 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009523
Daniel Borkmann09772d92018-06-02 23:06:35 +02009524 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009525 }
9526
Martin KaFai Lau5576b992020-01-22 15:36:46 -08009527 if (prog->jit_requested && BITS_PER_LONG == 64 &&
9528 insn->imm == BPF_FUNC_jiffies64) {
9529 struct bpf_insn ld_jiffies_addr[2] = {
9530 BPF_LD_IMM64(BPF_REG_0,
9531 (unsigned long)&jiffies),
9532 };
9533
9534 insn_buf[0] = ld_jiffies_addr[0];
9535 insn_buf[1] = ld_jiffies_addr[1];
9536 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
9537 BPF_REG_0, 0);
9538 cnt = 3;
9539
9540 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
9541 cnt);
9542 if (!new_prog)
9543 return -ENOMEM;
9544
9545 delta += cnt - 1;
9546 env->prog = prog = new_prog;
9547 insn = new_prog->insnsi + i + delta;
9548 continue;
9549 }
9550
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009551patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -07009552 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009553 /* all functions that have prototype and verifier allowed
9554 * programs to call them, must be real in-kernel functions
9555 */
9556 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009557 verbose(env,
9558 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009559 func_id_name(insn->imm), insn->imm);
9560 return -EFAULT;
9561 }
9562 insn->imm = fn->func - __bpf_call_base;
9563 }
9564
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009565 /* Since poke tab is now finalized, publish aux to tracker. */
9566 for (i = 0; i < prog->aux->size_poke_tab; i++) {
9567 map_ptr = prog->aux->poke_tab[i].tail_call.map;
9568 if (!map_ptr->ops->map_poke_track ||
9569 !map_ptr->ops->map_poke_untrack ||
9570 !map_ptr->ops->map_poke_run) {
9571 verbose(env, "bpf verifier is misconfigured\n");
9572 return -EINVAL;
9573 }
9574
9575 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
9576 if (ret < 0) {
9577 verbose(env, "tracking tail call prog failed\n");
9578 return ret;
9579 }
9580 }
9581
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009582 return 0;
9583}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009584
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009585static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009586{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009587 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009588 int i;
9589
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009590 sl = env->free_list;
9591 while (sl) {
9592 sln = sl->next;
9593 free_verifier_state(&sl->state, false);
9594 kfree(sl);
9595 sl = sln;
9596 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009597 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009598
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009599 if (!env->explored_states)
9600 return;
9601
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009602 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009603 sl = env->explored_states[i];
9604
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009605 while (sl) {
9606 sln = sl->next;
9607 free_verifier_state(&sl->state, false);
9608 kfree(sl);
9609 sl = sln;
9610 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009611 env->explored_states[i] = NULL;
9612 }
9613}
9614
9615/* The verifier is using insn_aux_data[] to store temporary data during
9616 * verification and to store information for passes that run after the
9617 * verification like dead code sanitization. do_check_common() for subprogram N
9618 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
9619 * temporary data after do_check_common() finds that subprogram N cannot be
9620 * verified independently. pass_cnt counts the number of times
9621 * do_check_common() was run and insn->aux->seen tells the pass number
9622 * insn_aux_data was touched. These variables are compared to clear temporary
9623 * data from failed pass. For testing and experiments do_check_common() can be
9624 * run multiple times even when prior attempt to verify is unsuccessful.
9625 */
9626static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
9627{
9628 struct bpf_insn *insn = env->prog->insnsi;
9629 struct bpf_insn_aux_data *aux;
9630 int i, class;
9631
9632 for (i = 0; i < env->prog->len; i++) {
9633 class = BPF_CLASS(insn[i].code);
9634 if (class != BPF_LDX && class != BPF_STX)
9635 continue;
9636 aux = &env->insn_aux_data[i];
9637 if (aux->seen != env->pass_cnt)
9638 continue;
9639 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
9640 }
9641}
9642
9643static int do_check_common(struct bpf_verifier_env *env, int subprog)
9644{
9645 struct bpf_verifier_state *state;
9646 struct bpf_reg_state *regs;
9647 int ret, i;
9648
9649 env->prev_linfo = NULL;
9650 env->pass_cnt++;
9651
9652 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
9653 if (!state)
9654 return -ENOMEM;
9655 state->curframe = 0;
9656 state->speculative = false;
9657 state->branches = 1;
9658 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
9659 if (!state->frame[0]) {
9660 kfree(state);
9661 return -ENOMEM;
9662 }
9663 env->cur_state = state;
9664 init_func_state(env, state->frame[0],
9665 BPF_MAIN_FUNC /* callsite */,
9666 0 /* frameno */,
9667 subprog);
9668
9669 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -08009670 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009671 ret = btf_prepare_func_args(env, subprog, regs);
9672 if (ret)
9673 goto out;
9674 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
9675 if (regs[i].type == PTR_TO_CTX)
9676 mark_reg_known_zero(env, regs, i);
9677 else if (regs[i].type == SCALAR_VALUE)
9678 mark_reg_unknown(env, regs, i);
9679 }
9680 } else {
9681 /* 1st arg to a function */
9682 regs[BPF_REG_1].type = PTR_TO_CTX;
9683 mark_reg_known_zero(env, regs, BPF_REG_1);
9684 ret = btf_check_func_arg_match(env, subprog, regs);
9685 if (ret == -EFAULT)
9686 /* unlikely verifier bug. abort.
9687 * ret == 0 and ret < 0 are sadly acceptable for
9688 * main() function due to backward compatibility.
9689 * Like socket filter program may be written as:
9690 * int bpf_prog(struct pt_regs *ctx)
9691 * and never dereference that ctx in the program.
9692 * 'struct pt_regs' is a type mismatch for socket
9693 * filter that should be using 'struct __sk_buff'.
9694 */
9695 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009696 }
9697
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009698 ret = do_check(env);
9699out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -08009700 /* check for NULL is necessary, since cur_state can be freed inside
9701 * do_check() under memory pressure.
9702 */
9703 if (env->cur_state) {
9704 free_verifier_state(env->cur_state, true);
9705 env->cur_state = NULL;
9706 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009707 while (!pop_stack(env, NULL, NULL));
9708 free_states(env);
9709 if (ret)
9710 /* clean aux data in case subprog was rejected */
9711 sanitize_insn_aux_data(env);
9712 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009713}
9714
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009715/* Verify all global functions in a BPF program one by one based on their BTF.
9716 * All global functions must pass verification. Otherwise the whole program is rejected.
9717 * Consider:
9718 * int bar(int);
9719 * int foo(int f)
9720 * {
9721 * return bar(f);
9722 * }
9723 * int bar(int b)
9724 * {
9725 * ...
9726 * }
9727 * foo() will be verified first for R1=any_scalar_value. During verification it
9728 * will be assumed that bar() already verified successfully and call to bar()
9729 * from foo() will be checked for type match only. Later bar() will be verified
9730 * independently to check that it's safe for R1=any_scalar_value.
9731 */
9732static int do_check_subprogs(struct bpf_verifier_env *env)
9733{
9734 struct bpf_prog_aux *aux = env->prog->aux;
9735 int i, ret;
9736
9737 if (!aux->func_info)
9738 return 0;
9739
9740 for (i = 1; i < env->subprog_cnt; i++) {
9741 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
9742 continue;
9743 env->insn_idx = env->subprog_info[i].start;
9744 WARN_ON_ONCE(env->insn_idx == 0);
9745 ret = do_check_common(env, i);
9746 if (ret) {
9747 return ret;
9748 } else if (env->log.level & BPF_LOG_LEVEL) {
9749 verbose(env,
9750 "Func#%d is safe for any args that match its prototype\n",
9751 i);
9752 }
9753 }
9754 return 0;
9755}
9756
9757static int do_check_main(struct bpf_verifier_env *env)
9758{
9759 int ret;
9760
9761 env->insn_idx = 0;
9762 ret = do_check_common(env, 0);
9763 if (!ret)
9764 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
9765 return ret;
9766}
9767
9768
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009769static void print_verification_stats(struct bpf_verifier_env *env)
9770{
9771 int i;
9772
9773 if (env->log.level & BPF_LOG_STATS) {
9774 verbose(env, "verification time %lld usec\n",
9775 div_u64(env->verification_time, 1000));
9776 verbose(env, "stack depth ");
9777 for (i = 0; i < env->subprog_cnt; i++) {
9778 u32 depth = env->subprog_info[i].stack_depth;
9779
9780 verbose(env, "%d", depth);
9781 if (i + 1 < env->subprog_cnt)
9782 verbose(env, "+");
9783 }
9784 verbose(env, "\n");
9785 }
9786 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
9787 "total_states %d peak_states %d mark_read %d\n",
9788 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
9789 env->max_states_per_insn, env->total_states,
9790 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -07009791}
9792
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009793static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
9794{
9795 const struct btf_type *t, *func_proto;
9796 const struct bpf_struct_ops *st_ops;
9797 const struct btf_member *member;
9798 struct bpf_prog *prog = env->prog;
9799 u32 btf_id, member_idx;
9800 const char *mname;
9801
9802 btf_id = prog->aux->attach_btf_id;
9803 st_ops = bpf_struct_ops_find(btf_id);
9804 if (!st_ops) {
9805 verbose(env, "attach_btf_id %u is not a supported struct\n",
9806 btf_id);
9807 return -ENOTSUPP;
9808 }
9809
9810 t = st_ops->type;
9811 member_idx = prog->expected_attach_type;
9812 if (member_idx >= btf_type_vlen(t)) {
9813 verbose(env, "attach to invalid member idx %u of struct %s\n",
9814 member_idx, st_ops->name);
9815 return -EINVAL;
9816 }
9817
9818 member = &btf_type_member(t)[member_idx];
9819 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
9820 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
9821 NULL);
9822 if (!func_proto) {
9823 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
9824 mname, member_idx, st_ops->name);
9825 return -EINVAL;
9826 }
9827
9828 if (st_ops->check_member) {
9829 int err = st_ops->check_member(t, member);
9830
9831 if (err) {
9832 verbose(env, "attach to unsupported member %s of struct %s\n",
9833 mname, st_ops->name);
9834 return err;
9835 }
9836 }
9837
9838 prog->aux->attach_func_proto = func_proto;
9839 prog->aux->attach_func_name = mname;
9840 env->ops = st_ops->verifier_ops;
9841
9842 return 0;
9843}
KP Singh6ba43b72020-03-04 20:18:50 +01009844#define SECURITY_PREFIX "security_"
9845
9846static int check_attach_modify_return(struct bpf_verifier_env *env)
9847{
9848 struct bpf_prog *prog = env->prog;
9849 unsigned long addr = (unsigned long) prog->aux->trampoline->func.addr;
9850
KP Singh6ba43b72020-03-04 20:18:50 +01009851 /* This is expected to be cleaned up in the future with the KRSI effort
9852 * introducing the LSM_HOOK macro for cleaning up lsm_hooks.h.
9853 */
KP Singh69191752020-03-05 21:49:55 +01009854 if (within_error_injection_list(addr) ||
9855 !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
9856 sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +01009857 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +01009858
9859 verbose(env, "fmod_ret attach_btf_id %u (%s) is not modifiable\n",
9860 prog->aux->attach_btf_id, prog->aux->attach_func_name);
9861
9862 return -EINVAL;
9863}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009864
Martin KaFai Lau38207292019-10-24 17:18:11 -07009865static int check_attach_btf_id(struct bpf_verifier_env *env)
9866{
9867 struct bpf_prog *prog = env->prog;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -08009868 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009869 struct bpf_prog *tgt_prog = prog->aux->linked_prog;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009870 u32 btf_id = prog->aux->attach_btf_id;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009871 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009872 int ret = 0, subprog = -1, i;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -08009873 struct bpf_trampoline *tr;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009874 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009875 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009876 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009877 struct btf *btf;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -08009878 long addr;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009879 u64 key;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009880
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009881 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
9882 return check_struct_ops_btf_id(env);
9883
KP Singh9e4e01d2020-03-29 01:43:52 +01009884 if (prog->type != BPF_PROG_TYPE_TRACING &&
9885 prog->type != BPF_PROG_TYPE_LSM &&
9886 !prog_extension)
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009887 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009888
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009889 if (!btf_id) {
9890 verbose(env, "Tracing programs must provide btf_id\n");
9891 return -EINVAL;
9892 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009893 btf = bpf_prog_get_target_btf(prog);
9894 if (!btf) {
9895 verbose(env,
9896 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
9897 return -EINVAL;
9898 }
9899 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009900 if (!t) {
9901 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
9902 return -EINVAL;
9903 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009904 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009905 if (!tname) {
9906 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
9907 return -EINVAL;
9908 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009909 if (tgt_prog) {
9910 struct bpf_prog_aux *aux = tgt_prog->aux;
9911
9912 for (i = 0; i < aux->func_info_cnt; i++)
9913 if (aux->func_info[i].type_id == btf_id) {
9914 subprog = i;
9915 break;
9916 }
9917 if (subprog == -1) {
9918 verbose(env, "Subprog %s doesn't exist\n", tname);
9919 return -EINVAL;
9920 }
9921 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -08009922 if (prog_extension) {
9923 if (conservative) {
9924 verbose(env,
9925 "Cannot replace static functions\n");
9926 return -EINVAL;
9927 }
9928 if (!prog->jit_requested) {
9929 verbose(env,
9930 "Extension programs should be JITed\n");
9931 return -EINVAL;
9932 }
9933 env->ops = bpf_verifier_ops[tgt_prog->type];
9934 }
9935 if (!tgt_prog->jited) {
9936 verbose(env, "Can attach to only JITed progs\n");
9937 return -EINVAL;
9938 }
9939 if (tgt_prog->type == prog->type) {
9940 /* Cannot fentry/fexit another fentry/fexit program.
9941 * Cannot attach program extension to another extension.
9942 * It's ok to attach fentry/fexit to extension program.
9943 */
9944 verbose(env, "Cannot recursively attach\n");
9945 return -EINVAL;
9946 }
9947 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
9948 prog_extension &&
9949 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
9950 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
9951 /* Program extensions can extend all program types
9952 * except fentry/fexit. The reason is the following.
9953 * The fentry/fexit programs are used for performance
9954 * analysis, stats and can be attached to any program
9955 * type except themselves. When extension program is
9956 * replacing XDP function it is necessary to allow
9957 * performance analysis of all functions. Both original
9958 * XDP program and its program extension. Hence
9959 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
9960 * allowed. If extending of fentry/fexit was allowed it
9961 * would be possible to create long call chain
9962 * fentry->extension->fentry->extension beyond
9963 * reasonable stack size. Hence extending fentry is not
9964 * allowed.
9965 */
9966 verbose(env, "Cannot extend fentry/fexit\n");
9967 return -EINVAL;
9968 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009969 key = ((u64)aux->id) << 32 | btf_id;
9970 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -08009971 if (prog_extension) {
9972 verbose(env, "Cannot replace kernel functions\n");
9973 return -EINVAL;
9974 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009975 key = btf_id;
9976 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009977
9978 switch (prog->expected_attach_type) {
9979 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009980 if (tgt_prog) {
9981 verbose(env,
9982 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
9983 return -EINVAL;
9984 }
Martin KaFai Lau38207292019-10-24 17:18:11 -07009985 if (!btf_type_is_typedef(t)) {
9986 verbose(env, "attach_btf_id %u is not a typedef\n",
9987 btf_id);
9988 return -EINVAL;
9989 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009990 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Martin KaFai Lau38207292019-10-24 17:18:11 -07009991 verbose(env, "attach_btf_id %u points to wrong type name %s\n",
9992 btf_id, tname);
9993 return -EINVAL;
9994 }
9995 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009996 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -07009997 if (!btf_type_is_ptr(t))
9998 /* should never happen in valid vmlinux build */
9999 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010000 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070010001 if (!btf_type_is_func_proto(t))
10002 /* should never happen in valid vmlinux build */
10003 return -EINVAL;
10004
10005 /* remember two read only pointers that are valid for
10006 * the life time of the kernel
10007 */
10008 prog->aux->attach_func_name = tname;
10009 prog->aux->attach_func_proto = t;
10010 prog->aux->attach_btf_trace = true;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070010011 return 0;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080010012 default:
10013 if (!prog_extension)
10014 return -EINVAL;
10015 /* fallthrough */
KP Singhae240822020-03-04 20:18:49 +010010016 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010010017 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010018 case BPF_TRACE_FENTRY:
10019 case BPF_TRACE_FEXIT:
KP Singh9e4e01d2020-03-29 01:43:52 +010010020 prog->aux->attach_func_name = tname;
10021 if (prog->type == BPF_PROG_TYPE_LSM) {
10022 ret = bpf_lsm_verify_prog(&env->log, prog);
10023 if (ret < 0)
10024 return ret;
10025 }
10026
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010027 if (!btf_type_is_func(t)) {
10028 verbose(env, "attach_btf_id %u is not a function\n",
10029 btf_id);
10030 return -EINVAL;
10031 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080010032 if (prog_extension &&
10033 btf_check_type_match(env, prog, btf, t))
10034 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010035 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010036 if (!btf_type_is_func_proto(t))
10037 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010038 tr = bpf_trampoline_lookup(key);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010039 if (!tr)
10040 return -ENOMEM;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010041 /* t is either vmlinux type or another program's type */
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010042 prog->aux->attach_func_proto = t;
10043 mutex_lock(&tr->mutex);
10044 if (tr->func.addr) {
10045 prog->aux->trampoline = tr;
10046 goto out;
10047 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010048 if (tgt_prog && conservative) {
10049 prog->aux->attach_func_proto = NULL;
10050 t = NULL;
10051 }
10052 ret = btf_distill_func_proto(&env->log, btf, t,
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010053 tname, &tr->func.model);
10054 if (ret < 0)
10055 goto out;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010056 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080010057 if (subprog == 0)
10058 addr = (long) tgt_prog->bpf_func;
10059 else
10060 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010061 } else {
10062 addr = kallsyms_lookup_name(tname);
10063 if (!addr) {
10064 verbose(env,
10065 "The address of function %s cannot be found\n",
10066 tname);
10067 ret = -ENOENT;
10068 goto out;
10069 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010070 }
10071 tr->func.addr = (void *)addr;
10072 prog->aux->trampoline = tr;
KP Singh6ba43b72020-03-04 20:18:50 +010010073
10074 if (prog->expected_attach_type == BPF_MODIFY_RETURN)
10075 ret = check_attach_modify_return(env);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010076out:
10077 mutex_unlock(&tr->mutex);
10078 if (ret)
10079 bpf_trampoline_put(tr);
10080 return ret;
Martin KaFai Lau38207292019-10-24 17:18:11 -070010081 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070010082}
10083
Yonghong Song838e9692018-11-19 15:29:11 -080010084int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
10085 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070010086{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010087 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010088 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070010089 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080010090 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010091 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070010092
Arnd Bergmanneba0c922017-11-02 12:05:52 +010010093 /* no program is valid */
10094 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
10095 return -EINVAL;
10096
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010097 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010098 * allocate/free it every time bpf_check() is called
10099 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010100 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010101 if (!env)
10102 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010103 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010104
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080010105 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070010106 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080010107 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010108 ret = -ENOMEM;
10109 if (!env->insn_aux_data)
10110 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080010111 for (i = 0; i < len; i++)
10112 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010113 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070010114 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070010115 is_priv = capable(CAP_SYS_ADMIN);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010116
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070010117 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
10118 mutex_lock(&bpf_verifier_lock);
10119 if (!btf_vmlinux)
10120 btf_vmlinux = btf_parse_vmlinux();
10121 mutex_unlock(&bpf_verifier_lock);
10122 }
10123
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010124 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070010125 if (!is_priv)
10126 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010127
10128 if (attr->log_level || attr->log_buf || attr->log_size) {
10129 /* user requested verbose verifier output
10130 * and supplied buffer to store the verification trace
10131 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070010132 log->level = attr->log_level;
10133 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
10134 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010135
10136 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070010137 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070010138 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010139 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010140 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010141 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020010142
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070010143 if (IS_ERR(btf_vmlinux)) {
10144 /* Either gcc or pahole or kernel are broken. */
10145 verbose(env, "in-kernel BTF is malformed\n");
10146 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070010147 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070010148 }
10149
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020010150 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
10151 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070010152 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080010153 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
10154 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010155
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010156 env->allow_ptr_leaks = is_priv;
10157
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070010158 if (is_priv)
10159 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
10160
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010161 ret = replace_map_fd_with_map_ptr(env);
10162 if (ret < 0)
10163 goto skip_full_check;
10164
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070010165 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Quentin Monneta40a2632018-11-09 13:03:31 +000010166 ret = bpf_prog_offload_verifier_prep(env->prog);
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070010167 if (ret)
10168 goto skip_full_check;
10169 }
10170
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010171 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010172 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010173 GFP_USER);
10174 ret = -ENOMEM;
10175 if (!env->explored_states)
10176 goto skip_full_check;
10177
Martin KaFai Laud9762e82018-12-13 10:41:48 -080010178 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010179 if (ret < 0)
10180 goto skip_full_check;
10181
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010182 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080010183 if (ret < 0)
10184 goto skip_full_check;
10185
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080010186 ret = check_attach_btf_id(env);
10187 if (ret)
10188 goto skip_full_check;
10189
Martin KaFai Laud9762e82018-12-13 10:41:48 -080010190 ret = check_cfg(env);
10191 if (ret < 0)
10192 goto skip_full_check;
10193
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010194 ret = do_check_subprogs(env);
10195 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010196
Quentin Monnetc941ce92018-10-07 12:56:47 +010010197 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
10198 ret = bpf_prog_offload_finalize(env);
10199
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010200skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010201 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010202
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010203 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080010204 ret = check_max_stack_depth(env);
10205
Jakub Kicinski9b38c402018-12-19 22:13:06 -080010206 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010207 if (is_priv) {
10208 if (ret == 0)
10209 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080010210 if (ret == 0)
10211 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080010212 if (ret == 0)
10213 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080010214 } else {
10215 if (ret == 0)
10216 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010217 }
10218
Jakub Kicinski9b38c402018-12-19 22:13:06 -080010219 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010220 /* program is valid, convert *(u32*)(ctx + off) accesses */
10221 ret = convert_ctx_accesses(env);
10222
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010223 if (ret == 0)
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010224 ret = fixup_bpf_calls(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010225
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010226 /* do 32-bit optimization after insn patching has done so those patched
10227 * insns could be handled correctly.
10228 */
Jiong Wangd6c23082019-05-24 23:25:18 +010010229 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
10230 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
10231 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
10232 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010233 }
10234
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010235 if (ret == 0)
10236 ret = fixup_call_args(env);
10237
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010238 env->verification_time = ktime_get_ns() - start_time;
10239 print_verification_stats(env);
10240
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010241 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010242 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010243 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010244 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010245 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010246 }
10247
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010248 if (ret == 0 && env->used_map_cnt) {
10249 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010250 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
10251 sizeof(env->used_maps[0]),
10252 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010253
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010254 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010255 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010256 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010257 }
10258
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010259 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010260 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010261 env->prog->aux->used_map_cnt = env->used_map_cnt;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010262
10263 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
10264 * bpf_ld_imm64 instructions
10265 */
10266 convert_pseudo_ld_imm64(env);
10267 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010268
Yonghong Songba64e7d2018-11-24 23:20:44 -080010269 if (ret == 0)
10270 adjust_btf_func(env);
10271
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010272err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010273 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010274 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070010275 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010276 */
10277 release_maps(env);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010278 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010279err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070010280 if (!is_priv)
10281 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010282 vfree(env->insn_aux_data);
10283err_free_env:
10284 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070010285 return ret;
10286}