blob: b558420330731f937eb1fce2471beb6eec268eac [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;
Yonghong Song849fa502018-04-28 22:28:09 -0700232 s64 msize_smax_value;
233 u64 msize_umax_value;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700234 int ref_obj_id;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800235 int func_id;
Alexei Starovoitova7658e12019-10-15 20:25:04 -0700236 u32 btf_id;
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200237};
238
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700239struct btf *btf_vmlinux;
240
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700241static DEFINE_MUTEX(bpf_verifier_lock);
242
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800243static const struct bpf_line_info *
244find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
245{
246 const struct bpf_line_info *linfo;
247 const struct bpf_prog *prog;
248 u32 i, nr_linfo;
249
250 prog = env->prog;
251 nr_linfo = prog->aux->nr_linfo;
252
253 if (!nr_linfo || insn_off >= prog->len)
254 return NULL;
255
256 linfo = prog->aux->linfo;
257 for (i = 1; i < nr_linfo; i++)
258 if (insn_off < linfo[i].insn_off)
259 break;
260
261 return &linfo[i - 1];
262}
263
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700264void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
265 va_list args)
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700266{
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700267 unsigned int n;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700268
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700269 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700270
271 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
272 "verifier log line truncated - local buffer too short\n");
273
274 n = min(log->len_total - log->len_used - 1, n);
275 log->kbuf[n] = '\0';
276
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700277 if (log->level == BPF_LOG_KERNEL) {
278 pr_err("BPF:%s\n", log->kbuf);
279 return;
280 }
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700281 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
282 log->len_used += n;
283 else
284 log->ubuf = NULL;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700285}
Jiri Olsaabe08842018-03-23 11:41:28 +0100286
287/* log_level controls verbosity level of eBPF verifier.
288 * bpf_verifier_log_write() is used to dump the verification trace to the log,
289 * so the user can figure out what's wrong with the program
Quentin Monnet430e68d2018-01-10 12:26:06 +0000290 */
Jiri Olsaabe08842018-03-23 11:41:28 +0100291__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
292 const char *fmt, ...)
293{
294 va_list args;
295
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700296 if (!bpf_verifier_log_needed(&env->log))
297 return;
298
Jiri Olsaabe08842018-03-23 11:41:28 +0100299 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700300 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100301 va_end(args);
302}
303EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
304
305__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
306{
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700307 struct bpf_verifier_env *env = private_data;
Jiri Olsaabe08842018-03-23 11:41:28 +0100308 va_list args;
309
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700310 if (!bpf_verifier_log_needed(&env->log))
311 return;
312
Jiri Olsaabe08842018-03-23 11:41:28 +0100313 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700314 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100315 va_end(args);
316}
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700317
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700318__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
319 const char *fmt, ...)
320{
321 va_list args;
322
323 if (!bpf_verifier_log_needed(log))
324 return;
325
326 va_start(args, fmt);
327 bpf_verifier_vlog(log, fmt, args);
328 va_end(args);
329}
330
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800331static const char *ltrim(const char *s)
332{
333 while (isspace(*s))
334 s++;
335
336 return s;
337}
338
339__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
340 u32 insn_off,
341 const char *prefix_fmt, ...)
342{
343 const struct bpf_line_info *linfo;
344
345 if (!bpf_verifier_log_needed(&env->log))
346 return;
347
348 linfo = find_linfo(env, insn_off);
349 if (!linfo || linfo == env->prev_linfo)
350 return;
351
352 if (prefix_fmt) {
353 va_list args;
354
355 va_start(args, prefix_fmt);
356 bpf_verifier_vlog(&env->log, prefix_fmt, args);
357 va_end(args);
358 }
359
360 verbose(env, "%s\n",
361 ltrim(btf_name_by_offset(env->prog->aux->btf,
362 linfo->line_off)));
363
364 env->prev_linfo = linfo;
365}
366
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200367static bool type_is_pkt_pointer(enum bpf_reg_type type)
368{
369 return type == PTR_TO_PACKET ||
370 type == PTR_TO_PACKET_META;
371}
372
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800373static bool type_is_sk_pointer(enum bpf_reg_type type)
374{
375 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800376 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700377 type == PTR_TO_TCP_SOCK ||
378 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800379}
380
Joe Stringer840b9612018-10-02 13:35:32 -0700381static bool reg_type_may_be_null(enum bpf_reg_type type)
382{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700383 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800384 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800385 type == PTR_TO_SOCK_COMMON_OR_NULL ||
386 type == PTR_TO_TCP_SOCK_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700387}
388
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800389static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
390{
391 return reg->type == PTR_TO_MAP_VALUE &&
392 map_value_has_spin_lock(reg->map_ptr);
393}
394
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700395static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
396{
397 return type == PTR_TO_SOCKET ||
398 type == PTR_TO_SOCKET_OR_NULL ||
399 type == PTR_TO_TCP_SOCK ||
400 type == PTR_TO_TCP_SOCK_OR_NULL;
401}
402
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700403static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700404{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700405 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700406}
407
408/* Determine whether the function releases some resources allocated by another
409 * function call. The first reference type argument will be assumed to be
410 * released by release_reference().
411 */
412static bool is_release_function(enum bpf_func_id func_id)
413{
Joe Stringer6acc9b42018-10-02 13:35:36 -0700414 return func_id == BPF_FUNC_sk_release;
Joe Stringer840b9612018-10-02 13:35:32 -0700415}
416
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800417static bool is_acquire_function(enum bpf_func_id func_id)
418{
419 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800420 func_id == BPF_FUNC_sk_lookup_udp ||
421 func_id == BPF_FUNC_skc_lookup_tcp;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800422}
423
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700424static bool is_ptr_cast_function(enum bpf_func_id func_id)
425{
426 return func_id == BPF_FUNC_tcp_sock ||
427 func_id == BPF_FUNC_sk_fullsock;
428}
429
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700430/* string representation of 'enum bpf_reg_type' */
431static const char * const reg_type_str[] = {
432 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100433 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700434 [PTR_TO_CTX] = "ctx",
435 [CONST_PTR_TO_MAP] = "map_ptr",
436 [PTR_TO_MAP_VALUE] = "map_value",
437 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700438 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700439 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200440 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700441 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700442 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700443 [PTR_TO_SOCKET] = "sock",
444 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800445 [PTR_TO_SOCK_COMMON] = "sock_common",
446 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800447 [PTR_TO_TCP_SOCK] = "tcp_sock",
448 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700449 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700450 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700451 [PTR_TO_BTF_ID] = "ptr_",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700452};
453
Edward Cree8efea212018-08-22 20:02:44 +0100454static char slot_type_char[] = {
455 [STACK_INVALID] = '?',
456 [STACK_SPILL] = 'r',
457 [STACK_MISC] = 'm',
458 [STACK_ZERO] = '0',
459};
460
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800461static void print_liveness(struct bpf_verifier_env *env,
462 enum bpf_reg_liveness live)
463{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800464 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800465 verbose(env, "_");
466 if (live & REG_LIVE_READ)
467 verbose(env, "r");
468 if (live & REG_LIVE_WRITTEN)
469 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800470 if (live & REG_LIVE_DONE)
471 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800472}
473
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800474static struct bpf_func_state *func(struct bpf_verifier_env *env,
475 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700476{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800477 struct bpf_verifier_state *cur = env->cur_state;
478
479 return cur->frame[reg->frameno];
480}
481
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700482const char *kernel_type_name(u32 id)
483{
484 return btf_name_by_offset(btf_vmlinux,
485 btf_type_by_id(btf_vmlinux, id)->name_off);
486}
487
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800488static void print_verifier_state(struct bpf_verifier_env *env,
489 const struct bpf_func_state *state)
490{
491 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700492 enum bpf_reg_type t;
493 int i;
494
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800495 if (state->frameno)
496 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700497 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700498 reg = &state->regs[i];
499 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700500 if (t == NOT_INIT)
501 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800502 verbose(env, " R%d", i);
503 print_liveness(env, reg->live);
504 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700505 if (t == SCALAR_VALUE && reg->precise)
506 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100507 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
508 tnum_is_const(reg->var_off)) {
509 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700510 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100511 } else {
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700512 if (t == PTR_TO_BTF_ID)
513 verbose(env, "%s", kernel_type_name(reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700514 verbose(env, "(id=%d", reg->id);
515 if (reg_type_may_be_refcounted_or_null(t))
516 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100517 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700518 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200519 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700520 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100521 else if (t == CONST_PTR_TO_MAP ||
522 t == PTR_TO_MAP_VALUE ||
523 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700524 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100525 reg->map_ptr->key_size,
526 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100527 if (tnum_is_const(reg->var_off)) {
528 /* Typically an immediate SCALAR_VALUE, but
529 * could be a pointer whose offset is too big
530 * for reg->off
531 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700532 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100533 } else {
534 if (reg->smin_value != reg->umin_value &&
535 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700536 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100537 (long long)reg->smin_value);
538 if (reg->smax_value != reg->umax_value &&
539 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700540 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100541 (long long)reg->smax_value);
542 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700543 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100544 (unsigned long long)reg->umin_value);
545 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700546 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100547 (unsigned long long)reg->umax_value);
548 if (!tnum_is_unknown(reg->var_off)) {
549 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100550
Edward Cree7d1238f2017-08-07 15:26:56 +0100551 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700552 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100553 }
Edward Creef1174f72017-08-07 15:26:19 +0100554 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700555 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100556 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700557 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700558 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100559 char types_buf[BPF_REG_SIZE + 1];
560 bool valid = false;
561 int j;
562
563 for (j = 0; j < BPF_REG_SIZE; j++) {
564 if (state->stack[i].slot_type[j] != STACK_INVALID)
565 valid = true;
566 types_buf[j] = slot_type_char[
567 state->stack[i].slot_type[j]];
568 }
569 types_buf[BPF_REG_SIZE] = 0;
570 if (!valid)
571 continue;
572 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
573 print_liveness(env, state->stack[i].spilled_ptr.live);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700574 if (state->stack[i].slot_type[0] == STACK_SPILL) {
575 reg = &state->stack[i].spilled_ptr;
576 t = reg->type;
577 verbose(env, "=%s", reg_type_str[t]);
578 if (t == SCALAR_VALUE && reg->precise)
579 verbose(env, "P");
580 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
581 verbose(env, "%lld", reg->var_off.value + reg->off);
582 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100583 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700584 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700585 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700586 if (state->acquired_refs && state->refs[0].id) {
587 verbose(env, " refs=%d", state->refs[0].id);
588 for (i = 1; i < state->acquired_refs; i++)
589 if (state->refs[i].id)
590 verbose(env, ",%d", state->refs[i].id);
591 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700592 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700593}
594
Joe Stringer84dbf352018-10-02 13:35:34 -0700595#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
596static int copy_##NAME##_state(struct bpf_func_state *dst, \
597 const struct bpf_func_state *src) \
598{ \
599 if (!src->FIELD) \
600 return 0; \
601 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
602 /* internal bug, make state invalid to reject the program */ \
603 memset(dst, 0, sizeof(*dst)); \
604 return -EFAULT; \
605 } \
606 memcpy(dst->FIELD, src->FIELD, \
607 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
608 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700609}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700610/* copy_reference_state() */
611COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700612/* copy_stack_state() */
613COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
614#undef COPY_STATE_FN
615
616#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
617static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
618 bool copy_old) \
619{ \
620 u32 old_size = state->COUNT; \
621 struct bpf_##NAME##_state *new_##FIELD; \
622 int slot = size / SIZE; \
623 \
624 if (size <= old_size || !size) { \
625 if (copy_old) \
626 return 0; \
627 state->COUNT = slot * SIZE; \
628 if (!size && old_size) { \
629 kfree(state->FIELD); \
630 state->FIELD = NULL; \
631 } \
632 return 0; \
633 } \
634 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
635 GFP_KERNEL); \
636 if (!new_##FIELD) \
637 return -ENOMEM; \
638 if (copy_old) { \
639 if (state->FIELD) \
640 memcpy(new_##FIELD, state->FIELD, \
641 sizeof(*new_##FIELD) * (old_size / SIZE)); \
642 memset(new_##FIELD + old_size / SIZE, 0, \
643 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
644 } \
645 state->COUNT = slot * SIZE; \
646 kfree(state->FIELD); \
647 state->FIELD = new_##FIELD; \
648 return 0; \
649}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700650/* realloc_reference_state() */
651REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700652/* realloc_stack_state() */
653REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
654#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700655
656/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
657 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800658 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700659 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
660 * which realloc_stack_state() copies over. It points to previous
661 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700662 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700663static int realloc_func_state(struct bpf_func_state *state, int stack_size,
664 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700665{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700666 int err = realloc_reference_state(state, refs_size, copy_old);
667 if (err)
668 return err;
669 return realloc_stack_state(state, stack_size, copy_old);
670}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700671
Joe Stringerfd978bf72018-10-02 13:35:35 -0700672/* Acquire a pointer id from the env and update the state->refs to include
673 * this new pointer reference.
674 * On success, returns a valid pointer id to associate with the register
675 * On failure, returns a negative errno.
676 */
677static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
678{
679 struct bpf_func_state *state = cur_func(env);
680 int new_ofs = state->acquired_refs;
681 int id, err;
682
683 err = realloc_reference_state(state, state->acquired_refs + 1, true);
684 if (err)
685 return err;
686 id = ++env->id_gen;
687 state->refs[new_ofs].id = id;
688 state->refs[new_ofs].insn_idx = insn_idx;
689
690 return id;
691}
692
693/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800694static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700695{
696 int i, last_idx;
697
Joe Stringerfd978bf72018-10-02 13:35:35 -0700698 last_idx = state->acquired_refs - 1;
699 for (i = 0; i < state->acquired_refs; i++) {
700 if (state->refs[i].id == ptr_id) {
701 if (last_idx && i != last_idx)
702 memcpy(&state->refs[i], &state->refs[last_idx],
703 sizeof(*state->refs));
704 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
705 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700706 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700707 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700708 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800709 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700710}
711
712static int transfer_reference_state(struct bpf_func_state *dst,
713 struct bpf_func_state *src)
714{
715 int err = realloc_reference_state(dst, src->acquired_refs, false);
716 if (err)
717 return err;
718 err = copy_reference_state(dst, src);
719 if (err)
720 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700721 return 0;
722}
723
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800724static void free_func_state(struct bpf_func_state *state)
725{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800726 if (!state)
727 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700728 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800729 kfree(state->stack);
730 kfree(state);
731}
732
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700733static void clear_jmp_history(struct bpf_verifier_state *state)
734{
735 kfree(state->jmp_history);
736 state->jmp_history = NULL;
737 state->jmp_history_cnt = 0;
738}
739
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700740static void free_verifier_state(struct bpf_verifier_state *state,
741 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700742{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800743 int i;
744
745 for (i = 0; i <= state->curframe; i++) {
746 free_func_state(state->frame[i]);
747 state->frame[i] = NULL;
748 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700749 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700750 if (free_self)
751 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700752}
753
754/* copy verifier state from src to dst growing dst stack space
755 * when necessary to accommodate larger src stack
756 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800757static int copy_func_state(struct bpf_func_state *dst,
758 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700759{
760 int err;
761
Joe Stringerfd978bf72018-10-02 13:35:35 -0700762 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
763 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700764 if (err)
765 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700766 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
767 err = copy_reference_state(dst, src);
768 if (err)
769 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700770 return copy_stack_state(dst, src);
771}
772
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800773static int copy_verifier_state(struct bpf_verifier_state *dst_state,
774 const struct bpf_verifier_state *src)
775{
776 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700777 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800778 int i, err;
779
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700780 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
781 kfree(dst_state->jmp_history);
782 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
783 if (!dst_state->jmp_history)
784 return -ENOMEM;
785 }
786 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
787 dst_state->jmp_history_cnt = src->jmp_history_cnt;
788
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800789 /* if dst has more stack frames then src frame, free them */
790 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
791 free_func_state(dst_state->frame[i]);
792 dst_state->frame[i] = NULL;
793 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100794 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800795 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800796 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700797 dst_state->branches = src->branches;
798 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700799 dst_state->first_insn_idx = src->first_insn_idx;
800 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800801 for (i = 0; i <= src->curframe; i++) {
802 dst = dst_state->frame[i];
803 if (!dst) {
804 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
805 if (!dst)
806 return -ENOMEM;
807 dst_state->frame[i] = dst;
808 }
809 err = copy_func_state(dst, src->frame[i]);
810 if (err)
811 return err;
812 }
813 return 0;
814}
815
Alexei Starovoitov25897262019-06-15 12:12:20 -0700816static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
817{
818 while (st) {
819 u32 br = --st->branches;
820
821 /* WARN_ON(br > 1) technically makes sense here,
822 * but see comment in push_stack(), hence:
823 */
824 WARN_ONCE((int)br < 0,
825 "BUG update_branch_counts:branches_to_explore=%d\n",
826 br);
827 if (br)
828 break;
829 st = st->parent;
830 }
831}
832
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700833static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
834 int *insn_idx)
835{
836 struct bpf_verifier_state *cur = env->cur_state;
837 struct bpf_verifier_stack_elem *elem, *head = env->head;
838 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700839
840 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700841 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700842
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700843 if (cur) {
844 err = copy_verifier_state(cur, &head->st);
845 if (err)
846 return err;
847 }
848 if (insn_idx)
849 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700850 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700851 *prev_insn_idx = head->prev_insn_idx;
852 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700853 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700854 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700855 env->head = elem;
856 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700857 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700858}
859
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100860static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100861 int insn_idx, int prev_insn_idx,
862 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700863{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700864 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100865 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700866 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700867
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700868 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700869 if (!elem)
870 goto err;
871
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700872 elem->insn_idx = insn_idx;
873 elem->prev_insn_idx = prev_insn_idx;
874 elem->next = env->head;
875 env->head = elem;
876 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700877 err = copy_verifier_state(&elem->st, cur);
878 if (err)
879 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100880 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700881 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
882 verbose(env, "The sequence of %d jumps is too complex.\n",
883 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700884 goto err;
885 }
Alexei Starovoitov25897262019-06-15 12:12:20 -0700886 if (elem->st.parent) {
887 ++elem->st.parent->branches;
888 /* WARN_ON(branches > 2) technically makes sense here,
889 * but
890 * 1. speculative states will bump 'branches' for non-branch
891 * instructions
892 * 2. is_state_visited() heuristics may decide not to create
893 * a new state for a sequence of branches and all such current
894 * and cloned states will be pointing to a single parent state
895 * which might have large 'branches' count.
896 */
897 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700898 return &elem->st;
899err:
Alexei Starovoitov58963512018-01-08 07:51:17 -0800900 free_verifier_state(env->cur_state, true);
901 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700902 /* pop all elements and return */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700903 while (!pop_stack(env, NULL, NULL));
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700904 return NULL;
905}
906
907#define CALLER_SAVED_REGS 6
908static const int caller_saved[CALLER_SAVED_REGS] = {
909 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
910};
911
Daniel Borkmannf54c7892019-12-22 23:37:40 +0100912static void __mark_reg_not_init(const struct bpf_verifier_env *env,
913 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +0100914
Edward Creeb03c9f92017-08-07 15:26:36 +0100915/* Mark the unknown part of a register (variable offset or scalar value) as
916 * known to have the value @imm.
917 */
918static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
919{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -0700920 /* Clear id, off, and union(map_ptr, range) */
921 memset(((u8 *)reg) + sizeof(reg->type), 0,
922 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
Edward Creeb03c9f92017-08-07 15:26:36 +0100923 reg->var_off = tnum_const(imm);
924 reg->smin_value = (s64)imm;
925 reg->smax_value = (s64)imm;
926 reg->umin_value = imm;
927 reg->umax_value = imm;
928}
929
Edward Creef1174f72017-08-07 15:26:19 +0100930/* Mark the 'variable offset' part of a register as zero. This should be
931 * used only on registers holding a pointer type.
932 */
933static void __mark_reg_known_zero(struct bpf_reg_state *reg)
934{
Edward Creeb03c9f92017-08-07 15:26:36 +0100935 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +0100936}
937
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -0800938static void __mark_reg_const_zero(struct bpf_reg_state *reg)
939{
940 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -0800941 reg->type = SCALAR_VALUE;
942}
943
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700944static void mark_reg_known_zero(struct bpf_verifier_env *env,
945 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +0100946{
947 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700948 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +0100949 /* Something bad happened, let's kill all regs */
950 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +0100951 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +0100952 return;
953 }
954 __mark_reg_known_zero(regs + regno);
955}
956
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200957static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
958{
959 return type_is_pkt_pointer(reg->type);
960}
961
962static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
963{
964 return reg_is_pkt_pointer(reg) ||
965 reg->type == PTR_TO_PACKET_END;
966}
967
968/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
969static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
970 enum bpf_reg_type which)
971{
972 /* The register can already have a range from prior markings.
973 * This is fine as long as it hasn't been advanced from its
974 * origin.
975 */
976 return reg->type == which &&
977 reg->id == 0 &&
978 reg->off == 0 &&
979 tnum_equals_const(reg->var_off, 0);
980}
981
Edward Creeb03c9f92017-08-07 15:26:36 +0100982/* Attempts to improve min/max values based on var_off information */
983static void __update_reg_bounds(struct bpf_reg_state *reg)
984{
985 /* min signed is max(sign bit) | min(other bits) */
986 reg->smin_value = max_t(s64, reg->smin_value,
987 reg->var_off.value | (reg->var_off.mask & S64_MIN));
988 /* max signed is min(sign bit) | max(other bits) */
989 reg->smax_value = min_t(s64, reg->smax_value,
990 reg->var_off.value | (reg->var_off.mask & S64_MAX));
991 reg->umin_value = max(reg->umin_value, reg->var_off.value);
992 reg->umax_value = min(reg->umax_value,
993 reg->var_off.value | reg->var_off.mask);
994}
995
996/* Uses signed min/max values to inform unsigned, and vice-versa */
997static void __reg_deduce_bounds(struct bpf_reg_state *reg)
998{
999 /* Learn sign from signed bounds.
1000 * If we cannot cross the sign boundary, then signed and unsigned bounds
1001 * are the same, so combine. This works even in the negative case, e.g.
1002 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1003 */
1004 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1005 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1006 reg->umin_value);
1007 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1008 reg->umax_value);
1009 return;
1010 }
1011 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1012 * boundary, so we must be careful.
1013 */
1014 if ((s64)reg->umax_value >= 0) {
1015 /* Positive. We can't learn anything from the smin, but smax
1016 * is positive, hence safe.
1017 */
1018 reg->smin_value = reg->umin_value;
1019 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1020 reg->umax_value);
1021 } else if ((s64)reg->umin_value < 0) {
1022 /* Negative. We can't learn anything from the smax, but smin
1023 * is negative, hence safe.
1024 */
1025 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1026 reg->umin_value);
1027 reg->smax_value = reg->umax_value;
1028 }
1029}
1030
1031/* Attempts to improve var_off based on unsigned min/max information */
1032static void __reg_bound_offset(struct bpf_reg_state *reg)
1033{
1034 reg->var_off = tnum_intersect(reg->var_off,
1035 tnum_range(reg->umin_value,
1036 reg->umax_value));
1037}
1038
1039/* Reset the min/max bounds of a register */
1040static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1041{
1042 reg->smin_value = S64_MIN;
1043 reg->smax_value = S64_MAX;
1044 reg->umin_value = 0;
1045 reg->umax_value = U64_MAX;
1046}
1047
Edward Creef1174f72017-08-07 15:26:19 +01001048/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001049static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1050 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001051{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001052 /*
1053 * Clear type, id, off, and union(map_ptr, range) and
1054 * padding between 'type' and union
1055 */
1056 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001057 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001058 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001059 reg->frameno = 0;
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001060 reg->precise = env->subprog_cnt > 1 || !env->allow_ptr_leaks ?
1061 true : false;
Edward Creeb03c9f92017-08-07 15:26:36 +01001062 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001063}
1064
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001065static void mark_reg_unknown(struct bpf_verifier_env *env,
1066 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001067{
1068 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001069 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001070 /* Something bad happened, let's kill all regs except FP */
1071 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001072 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001073 return;
1074 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001075 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001076}
1077
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001078static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1079 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001080{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001081 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001082 reg->type = NOT_INIT;
1083}
1084
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001085static void mark_reg_not_init(struct bpf_verifier_env *env,
1086 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001087{
Edward Creef1174f72017-08-07 15:26:19 +01001088 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001089 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001090 /* Something bad happened, let's kill all regs except FP */
1091 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001092 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001093 return;
1094 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001095 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001096}
1097
Jiong Wang5327ed32019-05-24 23:25:12 +01001098#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001099static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001100 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001101{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001102 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001103 int i;
1104
Edward Creedc503a82017-08-15 20:34:35 +01001105 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001106 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001107 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001108 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001109 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001110 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001111
1112 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001113 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001114 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001115 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001116}
1117
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001118#define BPF_MAIN_FUNC (-1)
1119static void init_func_state(struct bpf_verifier_env *env,
1120 struct bpf_func_state *state,
1121 int callsite, int frameno, int subprogno)
1122{
1123 state->callsite = callsite;
1124 state->frameno = frameno;
1125 state->subprogno = subprogno;
1126 init_reg_state(env, state);
1127}
1128
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001129enum reg_arg_type {
1130 SRC_OP, /* register is used as source operand */
1131 DST_OP, /* register is used as destination operand */
1132 DST_OP_NO_MARK /* same as above, check only, don't mark */
1133};
1134
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001135static int cmp_subprogs(const void *a, const void *b)
1136{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001137 return ((struct bpf_subprog_info *)a)->start -
1138 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001139}
1140
1141static int find_subprog(struct bpf_verifier_env *env, int off)
1142{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001143 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001144
Jiong Wang9c8105b2018-05-02 16:17:18 -04001145 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1146 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001147 if (!p)
1148 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001149 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001150
1151}
1152
1153static int add_subprog(struct bpf_verifier_env *env, int off)
1154{
1155 int insn_cnt = env->prog->len;
1156 int ret;
1157
1158 if (off >= insn_cnt || off < 0) {
1159 verbose(env, "call to invalid destination\n");
1160 return -EINVAL;
1161 }
1162 ret = find_subprog(env, off);
1163 if (ret >= 0)
1164 return 0;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001165 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001166 verbose(env, "too many subprograms\n");
1167 return -E2BIG;
1168 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04001169 env->subprog_info[env->subprog_cnt++].start = off;
1170 sort(env->subprog_info, env->subprog_cnt,
1171 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001172 return 0;
1173}
1174
1175static int check_subprogs(struct bpf_verifier_env *env)
1176{
1177 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001178 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001179 struct bpf_insn *insn = env->prog->insnsi;
1180 int insn_cnt = env->prog->len;
1181
Jiong Wangf910cef2018-05-02 16:17:17 -04001182 /* Add entry function. */
1183 ret = add_subprog(env, 0);
1184 if (ret < 0)
1185 return ret;
1186
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001187 /* determine subprog starts. The end is one before the next starts */
1188 for (i = 0; i < insn_cnt; i++) {
1189 if (insn[i].code != (BPF_JMP | BPF_CALL))
1190 continue;
1191 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1192 continue;
1193 if (!env->allow_ptr_leaks) {
1194 verbose(env, "function calls to other bpf functions are allowed for root only\n");
1195 return -EPERM;
1196 }
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001197 ret = add_subprog(env, i + insn[i].imm + 1);
1198 if (ret < 0)
1199 return ret;
1200 }
1201
Jiong Wang4cb3d992018-05-02 16:17:19 -04001202 /* Add a fake 'exit' subprog which could simplify subprog iteration
1203 * logic. 'subprog_cnt' should not be increased.
1204 */
1205 subprog[env->subprog_cnt].start = insn_cnt;
1206
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001207 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001208 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001209 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001210
1211 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001212 subprog_start = subprog[cur_subprog].start;
1213 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001214 for (i = 0; i < insn_cnt; i++) {
1215 u8 code = insn[i].code;
1216
Jiong Wang092ed092019-01-26 12:26:01 -05001217 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001218 goto next;
1219 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1220 goto next;
1221 off = i + insn[i].off + 1;
1222 if (off < subprog_start || off >= subprog_end) {
1223 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1224 return -EINVAL;
1225 }
1226next:
1227 if (i == subprog_end - 1) {
1228 /* to avoid fall-through from one subprog into another
1229 * the last insn of the subprog should be either exit
1230 * or unconditional jump back
1231 */
1232 if (code != (BPF_JMP | BPF_EXIT) &&
1233 code != (BPF_JMP | BPF_JA)) {
1234 verbose(env, "last insn is not an exit or jmp\n");
1235 return -EINVAL;
1236 }
1237 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001238 cur_subprog++;
1239 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001240 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001241 }
1242 }
1243 return 0;
1244}
1245
Edward Cree679c7822018-08-22 20:02:19 +01001246/* Parentage chain of this register (or stack slot) should take care of all
1247 * issues like callee-saved registers, stack slot allocation time, etc.
1248 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001249static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001250 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001251 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001252{
1253 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001254 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001255
1256 while (parent) {
1257 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001258 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001259 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001260 if (parent->live & REG_LIVE_DONE) {
1261 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1262 reg_type_str[parent->type],
1263 parent->var_off.value, parent->off);
1264 return -EFAULT;
1265 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001266 /* The first condition is more likely to be true than the
1267 * second, checked it first.
1268 */
1269 if ((parent->live & REG_LIVE_READ) == flag ||
1270 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001271 /* The parentage chain never changes and
1272 * this parent was already marked as LIVE_READ.
1273 * There is no need to keep walking the chain again and
1274 * keep re-marking all parents as LIVE_READ.
1275 * This case happens when the same register is read
1276 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001277 * Also, if parent has the stronger REG_LIVE_READ64 set,
1278 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001279 */
1280 break;
Edward Creedc503a82017-08-15 20:34:35 +01001281 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001282 parent->live |= flag;
1283 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1284 if (flag == REG_LIVE_READ64)
1285 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001286 state = parent;
1287 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001288 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001289 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001290 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001291
1292 if (env->longest_mark_read_walk < cnt)
1293 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001294 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001295}
1296
Jiong Wang5327ed32019-05-24 23:25:12 +01001297/* This function is supposed to be used by the following 32-bit optimization
1298 * code only. It returns TRUE if the source or destination register operates
1299 * on 64-bit, otherwise return FALSE.
1300 */
1301static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1302 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1303{
1304 u8 code, class, op;
1305
1306 code = insn->code;
1307 class = BPF_CLASS(code);
1308 op = BPF_OP(code);
1309 if (class == BPF_JMP) {
1310 /* BPF_EXIT for "main" will reach here. Return TRUE
1311 * conservatively.
1312 */
1313 if (op == BPF_EXIT)
1314 return true;
1315 if (op == BPF_CALL) {
1316 /* BPF to BPF call will reach here because of marking
1317 * caller saved clobber with DST_OP_NO_MARK for which we
1318 * don't care the register def because they are anyway
1319 * marked as NOT_INIT already.
1320 */
1321 if (insn->src_reg == BPF_PSEUDO_CALL)
1322 return false;
1323 /* Helper call will reach here because of arg type
1324 * check, conservatively return TRUE.
1325 */
1326 if (t == SRC_OP)
1327 return true;
1328
1329 return false;
1330 }
1331 }
1332
1333 if (class == BPF_ALU64 || class == BPF_JMP ||
1334 /* BPF_END always use BPF_ALU class. */
1335 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1336 return true;
1337
1338 if (class == BPF_ALU || class == BPF_JMP32)
1339 return false;
1340
1341 if (class == BPF_LDX) {
1342 if (t != SRC_OP)
1343 return BPF_SIZE(code) == BPF_DW;
1344 /* LDX source must be ptr. */
1345 return true;
1346 }
1347
1348 if (class == BPF_STX) {
1349 if (reg->type != SCALAR_VALUE)
1350 return true;
1351 return BPF_SIZE(code) == BPF_DW;
1352 }
1353
1354 if (class == BPF_LD) {
1355 u8 mode = BPF_MODE(code);
1356
1357 /* LD_IMM64 */
1358 if (mode == BPF_IMM)
1359 return true;
1360
1361 /* Both LD_IND and LD_ABS return 32-bit data. */
1362 if (t != SRC_OP)
1363 return false;
1364
1365 /* Implicit ctx ptr. */
1366 if (regno == BPF_REG_6)
1367 return true;
1368
1369 /* Explicit source could be any width. */
1370 return true;
1371 }
1372
1373 if (class == BPF_ST)
1374 /* The only source register for BPF_ST is a ptr. */
1375 return true;
1376
1377 /* Conservatively return true at default. */
1378 return true;
1379}
1380
Jiong Wangb325fbc2019-05-24 23:25:13 +01001381/* Return TRUE if INSN doesn't have explicit value define. */
1382static bool insn_no_def(struct bpf_insn *insn)
1383{
1384 u8 class = BPF_CLASS(insn->code);
1385
1386 return (class == BPF_JMP || class == BPF_JMP32 ||
1387 class == BPF_STX || class == BPF_ST);
1388}
1389
1390/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1391static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1392{
1393 if (insn_no_def(insn))
1394 return false;
1395
1396 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1397}
1398
Jiong Wang5327ed32019-05-24 23:25:12 +01001399static void mark_insn_zext(struct bpf_verifier_env *env,
1400 struct bpf_reg_state *reg)
1401{
1402 s32 def_idx = reg->subreg_def;
1403
1404 if (def_idx == DEF_NOT_SUBREG)
1405 return;
1406
1407 env->insn_aux_data[def_idx - 1].zext_dst = true;
1408 /* The dst will be zero extended, so won't be sub-register anymore. */
1409 reg->subreg_def = DEF_NOT_SUBREG;
1410}
1411
Edward Creedc503a82017-08-15 20:34:35 +01001412static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001413 enum reg_arg_type t)
1414{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001415 struct bpf_verifier_state *vstate = env->cur_state;
1416 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01001417 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01001418 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01001419 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01001420
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001421 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001422 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001423 return -EINVAL;
1424 }
1425
Jiong Wangc342dc12019-04-12 22:59:37 +01001426 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01001427 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001428 if (t == SRC_OP) {
1429 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01001430 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001431 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001432 return -EACCES;
1433 }
Edward Cree679c7822018-08-22 20:02:19 +01001434 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01001435 if (regno == BPF_REG_FP)
1436 return 0;
1437
Jiong Wang5327ed32019-05-24 23:25:12 +01001438 if (rw64)
1439 mark_insn_zext(env, reg);
1440
1441 return mark_reg_read(env, reg, reg->parent,
1442 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001443 } else {
1444 /* check whether register used as dest operand can be written to */
1445 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001446 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001447 return -EACCES;
1448 }
Jiong Wangc342dc12019-04-12 22:59:37 +01001449 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01001450 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001451 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001452 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001453 }
1454 return 0;
1455}
1456
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001457/* for any branch, call, exit record the history of jmps in the given state */
1458static int push_jmp_history(struct bpf_verifier_env *env,
1459 struct bpf_verifier_state *cur)
1460{
1461 u32 cnt = cur->jmp_history_cnt;
1462 struct bpf_idx_pair *p;
1463
1464 cnt++;
1465 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1466 if (!p)
1467 return -ENOMEM;
1468 p[cnt - 1].idx = env->insn_idx;
1469 p[cnt - 1].prev_idx = env->prev_insn_idx;
1470 cur->jmp_history = p;
1471 cur->jmp_history_cnt = cnt;
1472 return 0;
1473}
1474
1475/* Backtrack one insn at a time. If idx is not at the top of recorded
1476 * history then previous instruction came from straight line execution.
1477 */
1478static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1479 u32 *history)
1480{
1481 u32 cnt = *history;
1482
1483 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1484 i = st->jmp_history[cnt - 1].prev_idx;
1485 (*history)--;
1486 } else {
1487 i--;
1488 }
1489 return i;
1490}
1491
1492/* For given verifier state backtrack_insn() is called from the last insn to
1493 * the first insn. Its purpose is to compute a bitmask of registers and
1494 * stack slots that needs precision in the parent verifier state.
1495 */
1496static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1497 u32 *reg_mask, u64 *stack_mask)
1498{
1499 const struct bpf_insn_cbs cbs = {
1500 .cb_print = verbose,
1501 .private_data = env,
1502 };
1503 struct bpf_insn *insn = env->prog->insnsi + idx;
1504 u8 class = BPF_CLASS(insn->code);
1505 u8 opcode = BPF_OP(insn->code);
1506 u8 mode = BPF_MODE(insn->code);
1507 u32 dreg = 1u << insn->dst_reg;
1508 u32 sreg = 1u << insn->src_reg;
1509 u32 spi;
1510
1511 if (insn->code == 0)
1512 return 0;
1513 if (env->log.level & BPF_LOG_LEVEL) {
1514 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1515 verbose(env, "%d: ", idx);
1516 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1517 }
1518
1519 if (class == BPF_ALU || class == BPF_ALU64) {
1520 if (!(*reg_mask & dreg))
1521 return 0;
1522 if (opcode == BPF_MOV) {
1523 if (BPF_SRC(insn->code) == BPF_X) {
1524 /* dreg = sreg
1525 * dreg needs precision after this insn
1526 * sreg needs precision before this insn
1527 */
1528 *reg_mask &= ~dreg;
1529 *reg_mask |= sreg;
1530 } else {
1531 /* dreg = K
1532 * dreg needs precision after this insn.
1533 * Corresponding register is already marked
1534 * as precise=true in this verifier state.
1535 * No further markings in parent are necessary
1536 */
1537 *reg_mask &= ~dreg;
1538 }
1539 } else {
1540 if (BPF_SRC(insn->code) == BPF_X) {
1541 /* dreg += sreg
1542 * both dreg and sreg need precision
1543 * before this insn
1544 */
1545 *reg_mask |= sreg;
1546 } /* else dreg += K
1547 * dreg still needs precision before this insn
1548 */
1549 }
1550 } else if (class == BPF_LDX) {
1551 if (!(*reg_mask & dreg))
1552 return 0;
1553 *reg_mask &= ~dreg;
1554
1555 /* scalars can only be spilled into stack w/o losing precision.
1556 * Load from any other memory can be zero extended.
1557 * The desire to keep that precision is already indicated
1558 * by 'precise' mark in corresponding register of this state.
1559 * No further tracking necessary.
1560 */
1561 if (insn->src_reg != BPF_REG_FP)
1562 return 0;
1563 if (BPF_SIZE(insn->code) != BPF_DW)
1564 return 0;
1565
1566 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1567 * that [fp - off] slot contains scalar that needs to be
1568 * tracked with precision
1569 */
1570 spi = (-insn->off - 1) / BPF_REG_SIZE;
1571 if (spi >= 64) {
1572 verbose(env, "BUG spi %d\n", spi);
1573 WARN_ONCE(1, "verifier backtracking bug");
1574 return -EFAULT;
1575 }
1576 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001577 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001578 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001579 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001580 * to access memory. It means backtracking
1581 * encountered a case of pointer subtraction.
1582 */
1583 return -ENOTSUPP;
1584 /* scalars can only be spilled into stack */
1585 if (insn->dst_reg != BPF_REG_FP)
1586 return 0;
1587 if (BPF_SIZE(insn->code) != BPF_DW)
1588 return 0;
1589 spi = (-insn->off - 1) / BPF_REG_SIZE;
1590 if (spi >= 64) {
1591 verbose(env, "BUG spi %d\n", spi);
1592 WARN_ONCE(1, "verifier backtracking bug");
1593 return -EFAULT;
1594 }
1595 if (!(*stack_mask & (1ull << spi)))
1596 return 0;
1597 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001598 if (class == BPF_STX)
1599 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001600 } else if (class == BPF_JMP || class == BPF_JMP32) {
1601 if (opcode == BPF_CALL) {
1602 if (insn->src_reg == BPF_PSEUDO_CALL)
1603 return -ENOTSUPP;
1604 /* regular helper call sets R0 */
1605 *reg_mask &= ~1;
1606 if (*reg_mask & 0x3f) {
1607 /* if backtracing was looking for registers R1-R5
1608 * they should have been found already.
1609 */
1610 verbose(env, "BUG regs %x\n", *reg_mask);
1611 WARN_ONCE(1, "verifier backtracking bug");
1612 return -EFAULT;
1613 }
1614 } else if (opcode == BPF_EXIT) {
1615 return -ENOTSUPP;
1616 }
1617 } else if (class == BPF_LD) {
1618 if (!(*reg_mask & dreg))
1619 return 0;
1620 *reg_mask &= ~dreg;
1621 /* It's ld_imm64 or ld_abs or ld_ind.
1622 * For ld_imm64 no further tracking of precision
1623 * into parent is necessary
1624 */
1625 if (mode == BPF_IND || mode == BPF_ABS)
1626 /* to be analyzed */
1627 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001628 }
1629 return 0;
1630}
1631
1632/* the scalar precision tracking algorithm:
1633 * . at the start all registers have precise=false.
1634 * . scalar ranges are tracked as normal through alu and jmp insns.
1635 * . once precise value of the scalar register is used in:
1636 * . ptr + scalar alu
1637 * . if (scalar cond K|scalar)
1638 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1639 * backtrack through the verifier states and mark all registers and
1640 * stack slots with spilled constants that these scalar regisers
1641 * should be precise.
1642 * . during state pruning two registers (or spilled stack slots)
1643 * are equivalent if both are not precise.
1644 *
1645 * Note the verifier cannot simply walk register parentage chain,
1646 * since many different registers and stack slots could have been
1647 * used to compute single precise scalar.
1648 *
1649 * The approach of starting with precise=true for all registers and then
1650 * backtrack to mark a register as not precise when the verifier detects
1651 * that program doesn't care about specific value (e.g., when helper
1652 * takes register as ARG_ANYTHING parameter) is not safe.
1653 *
1654 * It's ok to walk single parentage chain of the verifier states.
1655 * It's possible that this backtracking will go all the way till 1st insn.
1656 * All other branches will be explored for needing precision later.
1657 *
1658 * The backtracking needs to deal with cases like:
1659 * 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)
1660 * r9 -= r8
1661 * r5 = r9
1662 * if r5 > 0x79f goto pc+7
1663 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1664 * r5 += 1
1665 * ...
1666 * call bpf_perf_event_output#25
1667 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1668 *
1669 * and this case:
1670 * r6 = 1
1671 * call foo // uses callee's r6 inside to compute r0
1672 * r0 += r6
1673 * if r0 == 0 goto
1674 *
1675 * to track above reg_mask/stack_mask needs to be independent for each frame.
1676 *
1677 * Also if parent's curframe > frame where backtracking started,
1678 * the verifier need to mark registers in both frames, otherwise callees
1679 * may incorrectly prune callers. This is similar to
1680 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1681 *
1682 * For now backtracking falls back into conservative marking.
1683 */
1684static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1685 struct bpf_verifier_state *st)
1686{
1687 struct bpf_func_state *func;
1688 struct bpf_reg_state *reg;
1689 int i, j;
1690
1691 /* big hammer: mark all scalars precise in this path.
1692 * pop_stack may still get !precise scalars.
1693 */
1694 for (; st; st = st->parent)
1695 for (i = 0; i <= st->curframe; i++) {
1696 func = st->frame[i];
1697 for (j = 0; j < BPF_REG_FP; j++) {
1698 reg = &func->regs[j];
1699 if (reg->type != SCALAR_VALUE)
1700 continue;
1701 reg->precise = true;
1702 }
1703 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1704 if (func->stack[j].slot_type[0] != STACK_SPILL)
1705 continue;
1706 reg = &func->stack[j].spilled_ptr;
1707 if (reg->type != SCALAR_VALUE)
1708 continue;
1709 reg->precise = true;
1710 }
1711 }
1712}
1713
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001714static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1715 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001716{
1717 struct bpf_verifier_state *st = env->cur_state;
1718 int first_idx = st->first_insn_idx;
1719 int last_idx = env->insn_idx;
1720 struct bpf_func_state *func;
1721 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001722 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
1723 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001724 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001725 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001726 int i, err;
1727
1728 if (!env->allow_ptr_leaks)
1729 /* backtracking is root only for now */
1730 return 0;
1731
1732 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001733 if (regno >= 0) {
1734 reg = &func->regs[regno];
1735 if (reg->type != SCALAR_VALUE) {
1736 WARN_ONCE(1, "backtracing misuse");
1737 return -EFAULT;
1738 }
1739 if (!reg->precise)
1740 new_marks = true;
1741 else
1742 reg_mask = 0;
1743 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001744 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001745
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001746 while (spi >= 0) {
1747 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
1748 stack_mask = 0;
1749 break;
1750 }
1751 reg = &func->stack[spi].spilled_ptr;
1752 if (reg->type != SCALAR_VALUE) {
1753 stack_mask = 0;
1754 break;
1755 }
1756 if (!reg->precise)
1757 new_marks = true;
1758 else
1759 stack_mask = 0;
1760 reg->precise = true;
1761 break;
1762 }
1763
1764 if (!new_marks)
1765 return 0;
1766 if (!reg_mask && !stack_mask)
1767 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001768 for (;;) {
1769 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001770 u32 history = st->jmp_history_cnt;
1771
1772 if (env->log.level & BPF_LOG_LEVEL)
1773 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
1774 for (i = last_idx;;) {
1775 if (skip_first) {
1776 err = 0;
1777 skip_first = false;
1778 } else {
1779 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
1780 }
1781 if (err == -ENOTSUPP) {
1782 mark_all_scalars_precise(env, st);
1783 return 0;
1784 } else if (err) {
1785 return err;
1786 }
1787 if (!reg_mask && !stack_mask)
1788 /* Found assignment(s) into tracked register in this state.
1789 * Since this state is already marked, just return.
1790 * Nothing to be tracked further in the parent state.
1791 */
1792 return 0;
1793 if (i == first_idx)
1794 break;
1795 i = get_prev_insn_idx(st, i, &history);
1796 if (i >= env->prog->len) {
1797 /* This can happen if backtracking reached insn 0
1798 * and there are still reg_mask or stack_mask
1799 * to backtrack.
1800 * It means the backtracking missed the spot where
1801 * particular register was initialized with a constant.
1802 */
1803 verbose(env, "BUG backtracking idx %d\n", i);
1804 WARN_ONCE(1, "verifier backtracking bug");
1805 return -EFAULT;
1806 }
1807 }
1808 st = st->parent;
1809 if (!st)
1810 break;
1811
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001812 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001813 func = st->frame[st->curframe];
1814 bitmap_from_u64(mask, reg_mask);
1815 for_each_set_bit(i, mask, 32) {
1816 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001817 if (reg->type != SCALAR_VALUE) {
1818 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001819 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001820 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001821 if (!reg->precise)
1822 new_marks = true;
1823 reg->precise = true;
1824 }
1825
1826 bitmap_from_u64(mask, stack_mask);
1827 for_each_set_bit(i, mask, 64) {
1828 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07001829 /* the sequence of instructions:
1830 * 2: (bf) r3 = r10
1831 * 3: (7b) *(u64 *)(r3 -8) = r0
1832 * 4: (79) r4 = *(u64 *)(r10 -8)
1833 * doesn't contain jmps. It's backtracked
1834 * as a single block.
1835 * During backtracking insn 3 is not recognized as
1836 * stack access, so at the end of backtracking
1837 * stack slot fp-8 is still marked in stack_mask.
1838 * However the parent state may not have accessed
1839 * fp-8 and it's "unallocated" stack space.
1840 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001841 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07001842 mark_all_scalars_precise(env, st);
1843 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001844 }
1845
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001846 if (func->stack[i].slot_type[0] != STACK_SPILL) {
1847 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001848 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001849 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001850 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001851 if (reg->type != SCALAR_VALUE) {
1852 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001853 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001854 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001855 if (!reg->precise)
1856 new_marks = true;
1857 reg->precise = true;
1858 }
1859 if (env->log.level & BPF_LOG_LEVEL) {
1860 print_verifier_state(env, func);
1861 verbose(env, "parent %s regs=%x stack=%llx marks\n",
1862 new_marks ? "didn't have" : "already had",
1863 reg_mask, stack_mask);
1864 }
1865
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001866 if (!reg_mask && !stack_mask)
1867 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001868 if (!new_marks)
1869 break;
1870
1871 last_idx = st->last_insn_idx;
1872 first_idx = st->first_insn_idx;
1873 }
1874 return 0;
1875}
1876
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07001877static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
1878{
1879 return __mark_chain_precision(env, regno, -1);
1880}
1881
1882static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
1883{
1884 return __mark_chain_precision(env, -1, spi);
1885}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001886
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07001887static bool is_spillable_regtype(enum bpf_reg_type type)
1888{
1889 switch (type) {
1890 case PTR_TO_MAP_VALUE:
1891 case PTR_TO_MAP_VALUE_OR_NULL:
1892 case PTR_TO_STACK:
1893 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07001894 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001895 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07001896 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07001897 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07001898 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07001899 case PTR_TO_SOCKET:
1900 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08001901 case PTR_TO_SOCK_COMMON:
1902 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08001903 case PTR_TO_TCP_SOCK:
1904 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07001905 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08001906 case PTR_TO_BTF_ID:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07001907 return true;
1908 default:
1909 return false;
1910 }
1911}
1912
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001913/* Does this register contain a constant zero? */
1914static bool register_is_null(struct bpf_reg_state *reg)
1915{
1916 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1917}
1918
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001919static bool register_is_const(struct bpf_reg_state *reg)
1920{
1921 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
1922}
1923
1924static void save_register_state(struct bpf_func_state *state,
1925 int spi, struct bpf_reg_state *reg)
1926{
1927 int i;
1928
1929 state->stack[spi].spilled_ptr = *reg;
1930 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1931
1932 for (i = 0; i < BPF_REG_SIZE; i++)
1933 state->stack[spi].slot_type[i] = STACK_SPILL;
1934}
1935
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001936/* check_stack_read/write functions track spill/fill of registers,
1937 * stack boundary and alignment are checked in check_mem_access()
1938 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001939static int check_stack_write(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001940 struct bpf_func_state *state, /* func where register points to */
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07001941 int off, int size, int value_regno, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001942{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001943 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001944 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001945 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001946 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001947
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001948 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07001949 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001950 if (err)
1951 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07001952 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1953 * so it's aligned access and [off, off + size) are within stack limits
1954 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001955 if (!env->allow_ptr_leaks &&
1956 state->stack[spi].slot_type[0] == STACK_SPILL &&
1957 size != BPF_REG_SIZE) {
1958 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1959 return -EACCES;
1960 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001961
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001962 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001963 if (value_regno >= 0)
1964 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001965
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001966 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
1967 !register_is_null(reg) && env->allow_ptr_leaks) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001968 if (dst_reg != BPF_REG_FP) {
1969 /* The backtracking logic can only recognize explicit
1970 * stack slot address like [fp - 8]. Other spill of
1971 * scalar via different register has to be conervative.
1972 * Backtrack from here and mark all registers as precise
1973 * that contributed into 'reg' being a constant.
1974 */
1975 err = mark_chain_precision(env, value_regno);
1976 if (err)
1977 return err;
1978 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001979 save_register_state(state, spi, reg);
1980 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001981 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07001982 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001983 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001984 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001985 return -EACCES;
1986 }
1987
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001988 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001989 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1990 return -EINVAL;
1991 }
1992
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001993 if (!env->allow_ptr_leaks) {
1994 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001995
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07001996 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
1997 register_is_const(&state->stack[spi].spilled_ptr))
1998 sanitize = true;
1999 for (i = 0; i < BPF_REG_SIZE; i++)
2000 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2001 sanitize = true;
2002 break;
2003 }
2004 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002005 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2006 int soff = (-spi - 1) * BPF_REG_SIZE;
2007
2008 /* detected reuse of integer stack slot with a pointer
2009 * which means either llvm is reusing stack slot or
2010 * an attacker is trying to exploit CVE-2018-3639
2011 * (speculative store bypass)
2012 * Have to sanitize that slot with preemptive
2013 * store of zero.
2014 */
2015 if (*poff && *poff != soff) {
2016 /* disallow programs where single insn stores
2017 * into two different stack slots, since verifier
2018 * cannot sanitize them
2019 */
2020 verbose(env,
2021 "insn %d cannot access two stack slots fp%d and fp%d",
2022 insn_idx, *poff, soff);
2023 return -EINVAL;
2024 }
2025 *poff = soff;
2026 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002027 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002028 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002029 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002030 u8 type = STACK_MISC;
2031
Edward Cree679c7822018-08-22 20:02:19 +01002032 /* regular write of data into stack destroys any spilled ptr */
2033 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002034 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2035 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2036 for (i = 0; i < BPF_REG_SIZE; i++)
2037 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002038
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002039 /* only mark the slot as written if all 8 bytes were written
2040 * otherwise read propagation may incorrectly stop too soon
2041 * when stack slots are partially written.
2042 * This heuristic means that read propagation will be
2043 * conservative, since it will add reg_live_read marks
2044 * to stack slots all the way to first state when programs
2045 * writes+reads less than 8 bytes
2046 */
2047 if (size == BPF_REG_SIZE)
2048 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2049
2050 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002051 if (reg && register_is_null(reg)) {
2052 /* backtracking doesn't work for STACK_ZERO yet. */
2053 err = mark_chain_precision(env, value_regno);
2054 if (err)
2055 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002056 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002057 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002058
Jiong Wang0bae2d42018-12-15 03:34:40 -05002059 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002060 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002061 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002062 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002063 }
2064 return 0;
2065}
2066
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002067static int check_stack_read(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002068 struct bpf_func_state *reg_state /* func where register points to */,
2069 int off, int size, int value_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002070{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002071 struct bpf_verifier_state *vstate = env->cur_state;
2072 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002073 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002074 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002075 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002076
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002077 if (reg_state->allocated_stack <= slot) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002078 verbose(env, "invalid read from stack off %d+0 size %d\n",
2079 off, size);
2080 return -EACCES;
2081 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002082 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002083 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002084
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002085 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002086 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002087 if (reg->type != SCALAR_VALUE) {
2088 verbose_linfo(env, env->insn_idx, "; ");
2089 verbose(env, "invalid size of register fill\n");
2090 return -EACCES;
2091 }
2092 if (value_regno >= 0) {
2093 mark_reg_unknown(env, state->regs, value_regno);
2094 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2095 }
2096 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2097 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002098 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002099 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002100 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002101 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002102 return -EACCES;
2103 }
2104 }
2105
Edward Creedc503a82017-08-15 20:34:35 +01002106 if (value_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002107 /* restore register state from stack */
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002108 state->regs[value_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002109 /* mark reg as written since spilled pointer state likely
2110 * has its liveness marks cleared by is_state_visited()
2111 * which resets stack/reg liveness for state transitions
2112 */
2113 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
Edward Creedc503a82017-08-15 20:34:35 +01002114 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002115 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002116 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002117 int zeros = 0;
2118
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002119 for (i = 0; i < size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002120 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2121 continue;
2122 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2123 zeros++;
2124 continue;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002125 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002126 verbose(env, "invalid read from stack off %d+%d size %d\n",
2127 off, i, size);
2128 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002129 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002130 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002131 if (value_regno >= 0) {
2132 if (zeros == size) {
2133 /* any size read into register is zero extended,
2134 * so the whole register == const_zero
2135 */
2136 __mark_reg_const_zero(&state->regs[value_regno]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002137 /* backtracking doesn't support STACK_ZERO yet,
2138 * so mark it precise here, so that later
2139 * backtracking can stop here.
2140 * Backtracking may not need this if this register
2141 * doesn't participate in pointer adjustment.
2142 * Forward propagation of precise flag is not
2143 * necessary either. This mark is only to stop
2144 * backtracking. Any register that contributed
2145 * to const 0 was marked precise before spill.
2146 */
2147 state->regs[value_regno].precise = true;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002148 } else {
2149 /* have read misc data from the stack */
2150 mark_reg_unknown(env, state->regs, value_regno);
2151 }
2152 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2153 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002154 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002155 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002156}
2157
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002158static int check_stack_access(struct bpf_verifier_env *env,
2159 const struct bpf_reg_state *reg,
2160 int off, int size)
2161{
2162 /* Stack accesses must be at a fixed offset, so that we
2163 * can determine what type of data were returned. See
2164 * check_stack_read().
2165 */
2166 if (!tnum_is_const(reg->var_off)) {
2167 char tn_buf[48];
2168
2169 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrey Ignatov1fbd20f2019-04-03 23:22:43 -07002170 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002171 tn_buf, off, size);
2172 return -EACCES;
2173 }
2174
2175 if (off >= 0 || off < -MAX_BPF_STACK) {
2176 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2177 return -EACCES;
2178 }
2179
2180 return 0;
2181}
2182
Daniel Borkmann591fe982019-04-09 23:20:05 +02002183static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2184 int off, int size, enum bpf_access_type type)
2185{
2186 struct bpf_reg_state *regs = cur_regs(env);
2187 struct bpf_map *map = regs[regno].map_ptr;
2188 u32 cap = bpf_map_flags_to_cap(map);
2189
2190 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2191 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2192 map->value_size, off, size);
2193 return -EACCES;
2194 }
2195
2196 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2197 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2198 map->value_size, off, size);
2199 return -EACCES;
2200 }
2201
2202 return 0;
2203}
2204
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002205/* check read/write into map element returned by bpf_map_lookup_elem() */
Edward Creef1174f72017-08-07 15:26:19 +01002206static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002207 int size, bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002208{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002209 struct bpf_reg_state *regs = cur_regs(env);
2210 struct bpf_map *map = regs[regno].map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002211
Yonghong Song9fd29c02017-11-12 14:49:09 -08002212 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2213 off + size > map->value_size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002214 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002215 map->value_size, off, size);
2216 return -EACCES;
2217 }
2218 return 0;
2219}
2220
Edward Creef1174f72017-08-07 15:26:19 +01002221/* check read/write into a map element with possible variable offset */
2222static int check_map_access(struct bpf_verifier_env *env, u32 regno,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002223 int off, int size, bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002224{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002225 struct bpf_verifier_state *vstate = env->cur_state;
2226 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002227 struct bpf_reg_state *reg = &state->regs[regno];
2228 int err;
2229
Edward Creef1174f72017-08-07 15:26:19 +01002230 /* We may have adjusted the register to this map value, so we
2231 * need to try adding each of min_value and max_value to off
2232 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002233 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002234 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002235 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002236
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002237 /* The minimum value is only important with signed
2238 * comparisons where we can't assume the floor of a
2239 * value is 0. If we are using signed variables for our
2240 * index'es we need to make sure that whatever we use
2241 * will have a set floor within our range.
2242 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002243 if (reg->smin_value < 0 &&
2244 (reg->smin_value == S64_MIN ||
2245 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2246 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002247 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 -08002248 regno);
2249 return -EACCES;
2250 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08002251 err = __check_map_access(env, regno, reg->smin_value + off, size,
2252 zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002253 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002254 verbose(env, "R%d min value is outside of the array range\n",
2255 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002256 return err;
2257 }
2258
Edward Creeb03c9f92017-08-07 15:26:36 +01002259 /* If we haven't set a max value then we need to bail since we can't be
2260 * sure we won't do bad things.
2261 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002262 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002263 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002264 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 -08002265 regno);
2266 return -EACCES;
2267 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08002268 err = __check_map_access(env, regno, reg->umax_value + off, size,
2269 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01002270 if (err)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002271 verbose(env, "R%d max value is outside of the array range\n",
2272 regno);
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002273
2274 if (map_value_has_spin_lock(reg->map_ptr)) {
2275 u32 lock = reg->map_ptr->spin_lock_off;
2276
2277 /* if any part of struct bpf_spin_lock can be touched by
2278 * load/store reject this program.
2279 * To check that [x1, x2) overlaps with [y1, y2)
2280 * it is sufficient to check x1 < y2 && y1 < x2.
2281 */
2282 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2283 lock < reg->umax_value + off + size) {
2284 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2285 return -EACCES;
2286 }
2287 }
Edward Creef1174f72017-08-07 15:26:19 +01002288 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002289}
2290
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002291#define MAX_PACKET_OFF 0xffff
2292
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01002293static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002294 const struct bpf_call_arg_meta *meta,
2295 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002296{
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002297 switch (env->prog->type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002298 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002299 case BPF_PROG_TYPE_LWT_IN:
2300 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01002301 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07002302 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002303 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02002304 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002305 if (t == BPF_WRITE)
2306 return false;
Alexander Alemayhu7e57fbb2017-02-14 00:02:35 +01002307 /* fallthrough */
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002308
2309 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002310 case BPF_PROG_TYPE_SCHED_CLS:
2311 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002312 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002313 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07002314 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07002315 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02002316 if (meta)
2317 return meta->pkt_access;
2318
2319 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002320 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07002321
2322 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2323 if (t == BPF_WRITE)
2324 env->seen_direct_write = true;
2325
2326 return true;
2327
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002328 default:
2329 return false;
2330 }
2331}
2332
Edward Creef1174f72017-08-07 15:26:19 +01002333static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002334 int off, int size, bool zero_size_allowed)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002335{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002336 struct bpf_reg_state *regs = cur_regs(env);
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01002337 struct bpf_reg_state *reg = &regs[regno];
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002338
Yonghong Song9fd29c02017-11-12 14:49:09 -08002339 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2340 (u64)off + size > reg->range) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002341 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 -07002342 off, size, regno, reg->id, reg->off, reg->range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002343 return -EACCES;
2344 }
2345 return 0;
2346}
2347
Edward Creef1174f72017-08-07 15:26:19 +01002348static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08002349 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01002350{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002351 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01002352 struct bpf_reg_state *reg = &regs[regno];
2353 int err;
2354
2355 /* We may have added a variable offset to the packet pointer; but any
2356 * reg->range we have comes after that. We are only checking the fixed
2357 * offset.
2358 */
2359
2360 /* We don't allow negative numbers, because we aren't tracking enough
2361 * detail to prove they're safe.
2362 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002363 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002364 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 +01002365 regno);
2366 return -EACCES;
2367 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08002368 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01002369 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002370 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01002371 return err;
2372 }
Jiong Wange6478152018-11-08 04:08:42 -05002373
2374 /* __check_packet_access has made sure "off + size - 1" is within u16.
2375 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2376 * otherwise find_good_pkt_pointers would have refused to set range info
2377 * that __check_packet_access would have rejected this pkt access.
2378 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2379 */
2380 env->prog->aux->max_pkt_offset =
2381 max_t(u32, env->prog->aux->max_pkt_offset,
2382 off + reg->umax_value + size - 1);
2383
Edward Creef1174f72017-08-07 15:26:19 +01002384 return err;
2385}
2386
2387/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07002388static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002389 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2390 u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002391{
Daniel Borkmannf96da092017-07-02 02:13:27 +02002392 struct bpf_insn_access_aux info = {
2393 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002394 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02002395 };
Yonghong Song31fd8582017-06-13 15:52:13 -07002396
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07002397 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07002398 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02002399 /* A non zero info.ctx_field_size indicates that this field is a
2400 * candidate for later verifier transformation to load the whole
2401 * field and then apply a mask when accessed with a narrower
2402 * access than actual ctx access size. A zero info.ctx_field_size
2403 * will only allow for whole field access and rejects any other
2404 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07002405 */
Yonghong Song23994632017-06-22 15:07:39 -07002406 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07002407
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002408 if (*reg_type == PTR_TO_BTF_ID)
2409 *btf_id = info.btf_id;
2410 else
2411 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002412 /* remember the offset of last byte accessed in ctx */
2413 if (env->prog->aux->max_ctx_offset < off + size)
2414 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002415 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07002416 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002417
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002418 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002419 return -EACCES;
2420}
2421
Petar Penkovd58e4682018-09-14 07:46:18 -07002422static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2423 int size)
2424{
2425 if (size < 0 || off < 0 ||
2426 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2427 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2428 off, size);
2429 return -EACCES;
2430 }
2431 return 0;
2432}
2433
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002434static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2435 u32 regno, int off, int size,
2436 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07002437{
2438 struct bpf_reg_state *regs = cur_regs(env);
2439 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002440 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002441 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07002442
2443 if (reg->smin_value < 0) {
2444 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2445 regno);
2446 return -EACCES;
2447 }
2448
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002449 switch (reg->type) {
2450 case PTR_TO_SOCK_COMMON:
2451 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2452 break;
2453 case PTR_TO_SOCKET:
2454 valid = bpf_sock_is_valid_access(off, size, t, &info);
2455 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002456 case PTR_TO_TCP_SOCK:
2457 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2458 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002459 case PTR_TO_XDP_SOCK:
2460 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2461 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002462 default:
2463 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07002464 }
2465
Martin KaFai Lau5f456642019-02-08 22:25:54 -08002466
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002467 if (valid) {
2468 env->insn_aux_data[insn_idx].ctx_field_size =
2469 info.ctx_field_size;
2470 return 0;
2471 }
2472
2473 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2474 regno, reg_type_str[reg->type], off, size);
2475
2476 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07002477}
2478
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002479static bool __is_pointer_value(bool allow_ptr_leaks,
2480 const struct bpf_reg_state *reg)
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002481{
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002482 if (allow_ptr_leaks)
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002483 return false;
2484
Edward Creef1174f72017-08-07 15:26:19 +01002485 return reg->type != SCALAR_VALUE;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002486}
2487
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002488static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2489{
2490 return cur_regs(env) + regno;
2491}
2492
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002493static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2494{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002495 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02002496}
2497
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002498static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2499{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002500 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002501
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002502 return reg->type == PTR_TO_CTX;
2503}
2504
2505static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2506{
2507 const struct bpf_reg_state *reg = reg_state(env, regno);
2508
2509 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01002510}
2511
Daniel Borkmannca369602018-02-23 22:29:05 +01002512static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2513{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02002514 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01002515
2516 return type_is_pkt_pointer(reg->type);
2517}
2518
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02002519static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2520{
2521 const struct bpf_reg_state *reg = reg_state(env, regno);
2522
2523 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2524 return reg->type == PTR_TO_FLOW_KEYS;
2525}
2526
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002527static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2528 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07002529 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002530{
Edward Creef1174f72017-08-07 15:26:19 +01002531 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07002532 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07002533
2534 /* Byte size accesses are always allowed. */
2535 if (!strict || size == 1)
2536 return 0;
2537
David S. Millere4eda882017-05-22 12:27:07 -04002538 /* For platforms that do not have a Kconfig enabling
2539 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2540 * NET_IP_ALIGN is universally set to '2'. And on platforms
2541 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2542 * to this code only in strict mode where we want to emulate
2543 * the NET_IP_ALIGN==2 checking. Therefore use an
2544 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07002545 */
David S. Millere4eda882017-05-22 12:27:07 -04002546 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01002547
2548 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2549 if (!tnum_is_aligned(reg_off, size)) {
2550 char tn_buf[48];
2551
2552 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002553 verbose(env,
2554 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002555 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002556 return -EACCES;
2557 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002558
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002559 return 0;
2560}
2561
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002562static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2563 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01002564 const char *pointer_desc,
2565 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002566{
Edward Creef1174f72017-08-07 15:26:19 +01002567 struct tnum reg_off;
2568
2569 /* Byte size accesses are always allowed. */
2570 if (!strict || size == 1)
2571 return 0;
2572
2573 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2574 if (!tnum_is_aligned(reg_off, size)) {
2575 char tn_buf[48];
2576
2577 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002578 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01002579 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002580 return -EACCES;
2581 }
2582
2583 return 0;
2584}
2585
David S. Millere07b98d2017-05-10 11:38:07 -07002586static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01002587 const struct bpf_reg_state *reg, int off,
2588 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002589{
Daniel Borkmannca369602018-02-23 22:29:05 +01002590 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01002591 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07002592
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002593 switch (reg->type) {
2594 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002595 case PTR_TO_PACKET_META:
2596 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2597 * right in front, treat it the very same way.
2598 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002599 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07002600 case PTR_TO_FLOW_KEYS:
2601 pointer_desc = "flow keys ";
2602 break;
Edward Creef1174f72017-08-07 15:26:19 +01002603 case PTR_TO_MAP_VALUE:
2604 pointer_desc = "value ";
2605 break;
2606 case PTR_TO_CTX:
2607 pointer_desc = "context ";
2608 break;
2609 case PTR_TO_STACK:
2610 pointer_desc = "stack ";
Jann Horna5ec6ae2017-12-18 20:11:58 -08002611 /* The stack spill tracking logic in check_stack_write()
2612 * and check_stack_read() relies on stack accesses being
2613 * aligned.
2614 */
2615 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01002616 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07002617 case PTR_TO_SOCKET:
2618 pointer_desc = "sock ";
2619 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002620 case PTR_TO_SOCK_COMMON:
2621 pointer_desc = "sock_common ";
2622 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002623 case PTR_TO_TCP_SOCK:
2624 pointer_desc = "tcp_sock ";
2625 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002626 case PTR_TO_XDP_SOCK:
2627 pointer_desc = "xdp_sock ";
2628 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002629 default:
Edward Creef1174f72017-08-07 15:26:19 +01002630 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002631 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002632 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2633 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02002634}
2635
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002636static int update_stack_depth(struct bpf_verifier_env *env,
2637 const struct bpf_func_state *func,
2638 int off)
2639{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002640 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002641
2642 if (stack >= -off)
2643 return 0;
2644
2645 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04002646 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002647 return 0;
2648}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002649
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002650/* starting from main bpf function walk all instructions of the function
2651 * and recursively walk all callees that given function can call.
2652 * Ignore jump and exit insns.
2653 * Since recursion is prevented by check_cfg() this algorithm
2654 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2655 */
2656static int check_max_stack_depth(struct bpf_verifier_env *env)
2657{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002658 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2659 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002660 struct bpf_insn *insn = env->prog->insnsi;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002661 int ret_insn[MAX_CALL_FRAMES];
2662 int ret_prog[MAX_CALL_FRAMES];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002663
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002664process_func:
2665 /* round up to 32-bytes, since this is granularity
2666 * of interpreter stack size
2667 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04002668 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002669 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002670 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002671 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002672 return -EACCES;
2673 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002674continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04002675 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002676 for (; i < subprog_end; i++) {
2677 if (insn[i].code != (BPF_JMP | BPF_CALL))
2678 continue;
2679 if (insn[i].src_reg != BPF_PSEUDO_CALL)
2680 continue;
2681 /* remember insn and function to return to */
2682 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04002683 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002684
2685 /* find the callee */
2686 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04002687 idx = find_subprog(env, i);
2688 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002689 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2690 i);
2691 return -EFAULT;
2692 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002693 frame++;
2694 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01002695 verbose(env, "the call stack of %d frames is too deep !\n",
2696 frame);
2697 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002698 }
2699 goto process_func;
2700 }
2701 /* end of for() loop means the last insn of the 'subprog'
2702 * was reached. Doesn't matter whether it was JA or EXIT
2703 */
2704 if (frame == 0)
2705 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04002706 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002707 frame--;
2708 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04002709 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08002710 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002711}
2712
David S. Miller19d28fb2018-01-11 21:27:54 -05002713#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08002714static int get_callee_stack_depth(struct bpf_verifier_env *env,
2715 const struct bpf_insn *insn, int idx)
2716{
2717 int start = idx + insn->imm + 1, subprog;
2718
2719 subprog = find_subprog(env, start);
2720 if (subprog < 0) {
2721 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2722 start);
2723 return -EFAULT;
2724 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04002725 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08002726}
David S. Miller19d28fb2018-01-11 21:27:54 -05002727#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08002728
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08002729int check_ctx_reg(struct bpf_verifier_env *env,
2730 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02002731{
2732 /* Access to ctx or passing it to a helper is only allowed in
2733 * its original, unmodified form.
2734 */
2735
2736 if (reg->off) {
2737 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
2738 regno, reg->off);
2739 return -EACCES;
2740 }
2741
2742 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2743 char tn_buf[48];
2744
2745 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2746 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
2747 return -EACCES;
2748 }
2749
2750 return 0;
2751}
2752
Matt Mullins9df1c282019-04-26 11:49:47 -07002753static int check_tp_buffer_access(struct bpf_verifier_env *env,
2754 const struct bpf_reg_state *reg,
2755 int regno, int off, int size)
2756{
2757 if (off < 0) {
2758 verbose(env,
2759 "R%d invalid tracepoint buffer access: off=%d, size=%d",
2760 regno, off, size);
2761 return -EACCES;
2762 }
2763 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2764 char tn_buf[48];
2765
2766 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2767 verbose(env,
2768 "R%d invalid variable buffer offset: off=%d, var_off=%s",
2769 regno, off, tn_buf);
2770 return -EACCES;
2771 }
2772 if (off + size > env->prog->aux->max_tp_access)
2773 env->prog->aux->max_tp_access = off + size;
2774
2775 return 0;
2776}
2777
2778
Jann Horn0c17d1d2017-12-18 20:11:55 -08002779/* truncate register to smaller size (in bytes)
2780 * must be called with size < BPF_REG_SIZE
2781 */
2782static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
2783{
2784 u64 mask;
2785
2786 /* clear high bits in bit representation */
2787 reg->var_off = tnum_cast(reg->var_off, size);
2788
2789 /* fix arithmetic bounds */
2790 mask = ((u64)1 << (size * 8)) - 1;
2791 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
2792 reg->umin_value &= mask;
2793 reg->umax_value &= mask;
2794 } else {
2795 reg->umin_value = 0;
2796 reg->umax_value = mask;
2797 }
2798 reg->smin_value = reg->umin_value;
2799 reg->smax_value = reg->umax_value;
2800}
2801
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07002802static bool bpf_map_is_rdonly(const struct bpf_map *map)
2803{
2804 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
2805}
2806
2807static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
2808{
2809 void *ptr;
2810 u64 addr;
2811 int err;
2812
2813 err = map->ops->map_direct_value_addr(map, &addr, off);
2814 if (err)
2815 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07002816 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07002817
2818 switch (size) {
2819 case sizeof(u8):
2820 *val = (u64)*(u8 *)ptr;
2821 break;
2822 case sizeof(u16):
2823 *val = (u64)*(u16 *)ptr;
2824 break;
2825 case sizeof(u32):
2826 *val = (u64)*(u32 *)ptr;
2827 break;
2828 case sizeof(u64):
2829 *val = *(u64 *)ptr;
2830 break;
2831 default:
2832 return -EINVAL;
2833 }
2834 return 0;
2835}
2836
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002837static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
2838 struct bpf_reg_state *regs,
2839 int regno, int off, int size,
2840 enum bpf_access_type atype,
2841 int value_regno)
2842{
2843 struct bpf_reg_state *reg = regs + regno;
2844 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
2845 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
2846 u32 btf_id;
2847 int ret;
2848
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002849 if (off < 0) {
2850 verbose(env,
2851 "R%d is ptr_%s invalid negative access: off=%d\n",
2852 regno, tname, off);
2853 return -EACCES;
2854 }
2855 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2856 char tn_buf[48];
2857
2858 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2859 verbose(env,
2860 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
2861 regno, tname, off, tn_buf);
2862 return -EACCES;
2863 }
2864
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08002865 if (env->ops->btf_struct_access) {
2866 ret = env->ops->btf_struct_access(&env->log, t, off, size,
2867 atype, &btf_id);
2868 } else {
2869 if (atype != BPF_READ) {
2870 verbose(env, "only read is supported\n");
2871 return -EACCES;
2872 }
2873
2874 ret = btf_struct_access(&env->log, t, off, size, atype,
2875 &btf_id);
2876 }
2877
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002878 if (ret < 0)
2879 return ret;
2880
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08002881 if (atype == BPF_READ) {
2882 if (ret == SCALAR_VALUE) {
2883 mark_reg_unknown(env, regs, value_regno);
2884 return 0;
2885 }
2886 mark_reg_known_zero(env, regs, value_regno);
2887 regs[value_regno].type = PTR_TO_BTF_ID;
2888 regs[value_regno].btf_id = btf_id;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002889 }
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08002890
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002891 return 0;
2892}
2893
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002894/* check whether memory at (regno + off) is accessible for t = (read | write)
2895 * if t==write, value_regno is a register which value is stored into memory
2896 * if t==read, value_regno is a register which will receive the value from memory
2897 * if t==write && value_regno==-1, some unknown value is stored into memory
2898 * if t==read && value_regno==-1, don't care what we read from memory
2899 */
Daniel Borkmannca369602018-02-23 22:29:05 +01002900static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
2901 int off, int bpf_size, enum bpf_access_type t,
2902 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002903{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002904 struct bpf_reg_state *regs = cur_regs(env);
2905 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002906 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002907 int size, err = 0;
2908
2909 size = bpf_size_to_bytes(bpf_size);
2910 if (size < 0)
2911 return size;
2912
Edward Creef1174f72017-08-07 15:26:19 +01002913 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01002914 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002915 if (err)
2916 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002917
Edward Creef1174f72017-08-07 15:26:19 +01002918 /* for access checks, reg->off is just part of off */
2919 off += reg->off;
2920
2921 if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002922 if (t == BPF_WRITE && value_regno >= 0 &&
2923 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002924 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002925 return -EACCES;
2926 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02002927 err = check_map_access_type(env, regno, off, size, t);
2928 if (err)
2929 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08002930 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07002931 if (!err && t == BPF_READ && value_regno >= 0) {
2932 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002933
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07002934 /* if map is read-only, track its contents as scalars */
2935 if (tnum_is_const(reg->var_off) &&
2936 bpf_map_is_rdonly(map) &&
2937 map->ops->map_direct_value_addr) {
2938 int map_off = off + reg->var_off.value;
2939 u64 val = 0;
2940
2941 err = bpf_map_direct_read(map, map_off, size,
2942 &val);
2943 if (err)
2944 return err;
2945
2946 regs[value_regno].type = SCALAR_VALUE;
2947 __mark_reg_known(&regs[value_regno], val);
2948 } else {
2949 mark_reg_unknown(env, regs, value_regno);
2950 }
2951 }
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07002952 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01002953 enum bpf_reg_type reg_type = SCALAR_VALUE;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002954 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07002955
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002956 if (t == BPF_WRITE && value_regno >= 0 &&
2957 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002958 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002959 return -EACCES;
2960 }
Edward Creef1174f72017-08-07 15:26:19 +01002961
Daniel Borkmann58990d12018-06-07 17:40:03 +02002962 err = check_ctx_reg(env, reg, regno);
2963 if (err < 0)
2964 return err;
2965
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002966 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
2967 if (err)
2968 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002969 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01002970 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002971 * PTR_TO_PACKET[_META,_END]. In the latter
2972 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01002973 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002974 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002975 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002976 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002977 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002978 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002979 if (reg_type_may_be_null(reg_type))
2980 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01002981 /* A load of ctx field could have different
2982 * actual load size with the one encoded in the
2983 * insn. When the dst is PTR, it is for sure not
2984 * a sub-register.
2985 */
2986 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07002987 if (reg_type == PTR_TO_BTF_ID)
2988 regs[value_regno].btf_id = btf_id;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002989 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002990 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002991 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002992
Edward Creef1174f72017-08-07 15:26:19 +01002993 } else if (reg->type == PTR_TO_STACK) {
Edward Creef1174f72017-08-07 15:26:19 +01002994 off += reg->var_off.value;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002995 err = check_stack_access(env, reg, off, size);
2996 if (err)
2997 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07002998
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002999 state = func(env, reg);
3000 err = update_stack_depth(env, state, off);
3001 if (err)
3002 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003003
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003004 if (t == BPF_WRITE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003005 err = check_stack_write(env, state, off, size,
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07003006 value_regno, insn_idx);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003007 else
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003008 err = check_stack_read(env, state, off, size,
3009 value_regno);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003010 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003011 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003012 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003013 return -EACCES;
3014 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003015 if (t == BPF_WRITE && value_regno >= 0 &&
3016 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003017 verbose(env, "R%d leaks addr into packet\n",
3018 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003019 return -EACCES;
3020 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08003021 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003022 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003023 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07003024 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3025 if (t == BPF_WRITE && value_regno >= 0 &&
3026 is_pointer_value(env, value_regno)) {
3027 verbose(env, "R%d leaks addr into flow keys\n",
3028 value_regno);
3029 return -EACCES;
3030 }
3031
3032 err = check_flow_keys_access(env, off, size);
3033 if (!err && t == BPF_READ && value_regno >= 0)
3034 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003035 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07003036 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003037 verbose(env, "R%d cannot write into %s\n",
3038 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07003039 return -EACCES;
3040 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003041 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07003042 if (!err && value_regno >= 0)
3043 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07003044 } else if (reg->type == PTR_TO_TP_BUFFER) {
3045 err = check_tp_buffer_access(env, reg, regno, off, size);
3046 if (!err && t == BPF_READ && value_regno >= 0)
3047 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003048 } else if (reg->type == PTR_TO_BTF_ID) {
3049 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3050 value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003051 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003052 verbose(env, "R%d invalid mem access '%s'\n", regno,
3053 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003054 return -EACCES;
3055 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003056
Edward Creef1174f72017-08-07 15:26:19 +01003057 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003058 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01003059 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08003060 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003061 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003062 return err;
3063}
3064
Yonghong Song31fd8582017-06-13 15:52:13 -07003065static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003066{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003067 int err;
3068
3069 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3070 insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003071 verbose(env, "BPF_XADD uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003072 return -EINVAL;
3073 }
3074
3075 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003076 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003077 if (err)
3078 return err;
3079
3080 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01003081 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003082 if (err)
3083 return err;
3084
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003085 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003086 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02003087 return -EACCES;
3088 }
3089
Daniel Borkmannca369602018-02-23 22:29:05 +01003090 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003091 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003092 is_flow_key_reg(env, insn->dst_reg) ||
3093 is_sk_reg(env, insn->dst_reg)) {
Daniel Borkmannca369602018-02-23 22:29:05 +01003094 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003095 insn->dst_reg,
3096 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003097 return -EACCES;
3098 }
3099
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003100 /* check whether atomic_add can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003101 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003102 BPF_SIZE(insn->code), BPF_READ, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003103 if (err)
3104 return err;
3105
3106 /* check whether atomic_add can write into the same memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07003107 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Daniel Borkmannca369602018-02-23 22:29:05 +01003108 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003109}
3110
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003111static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3112 int off, int access_size,
3113 bool zero_size_allowed)
3114{
3115 struct bpf_reg_state *reg = reg_state(env, regno);
3116
3117 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3118 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3119 if (tnum_is_const(reg->var_off)) {
3120 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3121 regno, off, access_size);
3122 } else {
3123 char tn_buf[48];
3124
3125 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3126 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3127 regno, tn_buf, access_size);
3128 }
3129 return -EACCES;
3130 }
3131 return 0;
3132}
3133
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003134/* when register 'regno' is passed into function that will read 'access_size'
3135 * bytes from that pointer, make sure that it's within stack boundary
Edward Creef1174f72017-08-07 15:26:19 +01003136 * and all elements of stack are initialized.
3137 * Unlike most pointer bounds-checking functions, this one doesn't take an
3138 * 'off' argument, so it has to add in reg->off itself.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003139 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003140static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
Daniel Borkmann435faee12016-04-13 00:10:51 +02003141 int access_size, bool zero_size_allowed,
3142 struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003143{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003144 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003145 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003146 int err, min_off, max_off, i, j, slot, spi;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003147
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003148 if (reg->type != PTR_TO_STACK) {
Edward Creef1174f72017-08-07 15:26:19 +01003149 /* Allow zero-byte read from NULL, regardless of pointer type */
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003150 if (zero_size_allowed && access_size == 0 &&
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003151 register_is_null(reg))
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003152 return 0;
3153
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003154 verbose(env, "R%d type=%s expected=%s\n", regno,
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003155 reg_type_str[reg->type],
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003156 reg_type_str[PTR_TO_STACK]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003157 return -EACCES;
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003158 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003159
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003160 if (tnum_is_const(reg->var_off)) {
3161 min_off = max_off = reg->var_off.value + reg->off;
3162 err = __check_stack_boundary(env, regno, min_off, access_size,
3163 zero_size_allowed);
3164 if (err)
3165 return err;
3166 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07003167 /* Variable offset is prohibited for unprivileged mode for
3168 * simplicity since it requires corresponding support in
3169 * Spectre masking for stack ALU.
3170 * See also retrieve_ptr_limit().
3171 */
3172 if (!env->allow_ptr_leaks) {
3173 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01003174
Andrey Ignatov088ec262019-04-03 23:22:39 -07003175 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3176 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3177 regno, tn_buf);
3178 return -EACCES;
3179 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07003180 /* Only initialized buffer on stack is allowed to be accessed
3181 * with variable offset. With uninitialized buffer it's hard to
3182 * guarantee that whole memory is marked as initialized on
3183 * helper return since specific bounds are unknown what may
3184 * cause uninitialized stack leaking.
3185 */
3186 if (meta && meta->raw_mode)
3187 meta = NULL;
3188
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003189 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3190 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3191 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3192 regno);
3193 return -EACCES;
3194 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003195 min_off = reg->smin_value + reg->off;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003196 max_off = reg->smax_value + reg->off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003197 err = __check_stack_boundary(env, regno, min_off, access_size,
3198 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003199 if (err) {
3200 verbose(env, "R%d min value is outside of stack bound\n",
3201 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003202 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003203 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003204 err = __check_stack_boundary(env, regno, max_off, access_size,
3205 zero_size_allowed);
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003206 if (err) {
3207 verbose(env, "R%d max value is outside of stack bound\n",
3208 regno);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003209 return err;
Andrey Ignatov107c26a72019-04-03 23:22:41 -07003210 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003211 }
3212
Daniel Borkmann435faee12016-04-13 00:10:51 +02003213 if (meta && meta->raw_mode) {
3214 meta->access_size = access_size;
3215 meta->regno = regno;
3216 return 0;
3217 }
3218
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003219 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003220 u8 *stype;
3221
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003222 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003223 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003224 if (state->allocated_stack <= slot)
3225 goto err;
3226 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3227 if (*stype == STACK_MISC)
3228 goto mark;
3229 if (*stype == STACK_ZERO) {
3230 /* helper can write anything into the stack */
3231 *stype = STACK_MISC;
3232 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003233 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003234 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3235 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003236 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003237 for (j = 0; j < BPF_REG_SIZE; j++)
3238 state->stack[spi].slot_type[j] = STACK_MISC;
3239 goto mark;
3240 }
3241
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003242err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003243 if (tnum_is_const(reg->var_off)) {
3244 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3245 min_off, i - min_off, access_size);
3246 } else {
3247 char tn_buf[48];
3248
3249 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3250 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3251 tn_buf, i - min_off, access_size);
3252 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003253 return -EACCES;
3254mark:
3255 /* reading any byte out of 8-byte 'spill_slot' will cause
3256 * the whole slot to be marked as 'read'
3257 */
Edward Cree679c7822018-08-22 20:02:19 +01003258 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01003259 state->stack[spi].spilled_ptr.parent,
3260 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003261 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07003262 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003263}
3264
Gianluca Borello06c1c042017-01-09 10:19:49 -08003265static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3266 int access_size, bool zero_size_allowed,
3267 struct bpf_call_arg_meta *meta)
3268{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003269 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08003270
Edward Creef1174f72017-08-07 15:26:19 +01003271 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08003272 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003273 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08003274 return check_packet_access(env, regno, reg->off, access_size,
3275 zero_size_allowed);
Gianluca Borello06c1c042017-01-09 10:19:49 -08003276 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02003277 if (check_map_access_type(env, regno, reg->off, access_size,
3278 meta && meta->raw_mode ? BPF_WRITE :
3279 BPF_READ))
3280 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003281 return check_map_access(env, regno, reg->off, access_size,
3282 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01003283 default: /* scalar_value|ptr_to_stack or invalid ptr */
Gianluca Borello06c1c042017-01-09 10:19:49 -08003284 return check_stack_boundary(env, regno, access_size,
3285 zero_size_allowed, meta);
3286 }
3287}
3288
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003289/* Implementation details:
3290 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3291 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3292 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3293 * value_or_null->value transition, since the verifier only cares about
3294 * the range of access to valid map value pointer and doesn't care about actual
3295 * address of the map element.
3296 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3297 * reg->id > 0 after value_or_null->value transition. By doing so
3298 * two bpf_map_lookups will be considered two different pointers that
3299 * point to different bpf_spin_locks.
3300 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3301 * dead-locks.
3302 * Since only one bpf_spin_lock is allowed the checks are simpler than
3303 * reg_is_refcounted() logic. The verifier needs to remember only
3304 * one spin_lock instead of array of acquired_refs.
3305 * cur_state->active_spin_lock remembers which map value element got locked
3306 * and clears it after bpf_spin_unlock.
3307 */
3308static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3309 bool is_lock)
3310{
3311 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3312 struct bpf_verifier_state *cur = env->cur_state;
3313 bool is_const = tnum_is_const(reg->var_off);
3314 struct bpf_map *map = reg->map_ptr;
3315 u64 val = reg->var_off.value;
3316
3317 if (reg->type != PTR_TO_MAP_VALUE) {
3318 verbose(env, "R%d is not a pointer to map_value\n", regno);
3319 return -EINVAL;
3320 }
3321 if (!is_const) {
3322 verbose(env,
3323 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3324 regno);
3325 return -EINVAL;
3326 }
3327 if (!map->btf) {
3328 verbose(env,
3329 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3330 map->name);
3331 return -EINVAL;
3332 }
3333 if (!map_value_has_spin_lock(map)) {
3334 if (map->spin_lock_off == -E2BIG)
3335 verbose(env,
3336 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3337 map->name);
3338 else if (map->spin_lock_off == -ENOENT)
3339 verbose(env,
3340 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3341 map->name);
3342 else
3343 verbose(env,
3344 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3345 map->name);
3346 return -EINVAL;
3347 }
3348 if (map->spin_lock_off != val + reg->off) {
3349 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3350 val + reg->off);
3351 return -EINVAL;
3352 }
3353 if (is_lock) {
3354 if (cur->active_spin_lock) {
3355 verbose(env,
3356 "Locking two bpf_spin_locks are not allowed\n");
3357 return -EINVAL;
3358 }
3359 cur->active_spin_lock = reg->id;
3360 } else {
3361 if (!cur->active_spin_lock) {
3362 verbose(env, "bpf_spin_unlock without taking a lock\n");
3363 return -EINVAL;
3364 }
3365 if (cur->active_spin_lock != reg->id) {
3366 verbose(env, "bpf_spin_unlock of different lock\n");
3367 return -EINVAL;
3368 }
3369 cur->active_spin_lock = 0;
3370 }
3371 return 0;
3372}
3373
Daniel Borkmann90133412018-01-20 01:24:29 +01003374static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3375{
3376 return type == ARG_PTR_TO_MEM ||
3377 type == ARG_PTR_TO_MEM_OR_NULL ||
3378 type == ARG_PTR_TO_UNINIT_MEM;
3379}
3380
3381static bool arg_type_is_mem_size(enum bpf_arg_type type)
3382{
3383 return type == ARG_CONST_SIZE ||
3384 type == ARG_CONST_SIZE_OR_ZERO;
3385}
3386
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003387static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3388{
3389 return type == ARG_PTR_TO_INT ||
3390 type == ARG_PTR_TO_LONG;
3391}
3392
3393static int int_ptr_type_to_size(enum bpf_arg_type type)
3394{
3395 if (type == ARG_PTR_TO_INT)
3396 return sizeof(u32);
3397 else if (type == ARG_PTR_TO_LONG)
3398 return sizeof(u64);
3399
3400 return -EINVAL;
3401}
3402
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003403static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
Daniel Borkmann33ff9822016-04-13 00:10:50 +02003404 enum bpf_arg_type arg_type,
3405 struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003406{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003407 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003408 enum bpf_reg_type expected_type, type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003409 int err = 0;
3410
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003411 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003412 return 0;
3413
Edward Creedc503a82017-08-15 20:34:35 +01003414 err = check_reg_arg(env, regno, SRC_OP);
3415 if (err)
3416 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003417
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003418 if (arg_type == ARG_ANYTHING) {
3419 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003420 verbose(env, "R%d leaks addr into helper function\n",
3421 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003422 return -EACCES;
3423 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003424 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003425 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01003426
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003427 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003428 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003429 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003430 return -EACCES;
3431 }
3432
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003433 if (arg_type == ARG_PTR_TO_MAP_KEY ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003434 arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003435 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3436 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003437 expected_type = PTR_TO_STACK;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003438 if (register_is_null(reg) &&
3439 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
3440 /* final test in check_stack_boundary() */;
3441 else if (!type_is_pkt_pointer(type) &&
3442 type != PTR_TO_MAP_VALUE &&
3443 type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003444 goto err_type;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003445 } else if (arg_type == ARG_CONST_SIZE ||
3446 arg_type == ARG_CONST_SIZE_OR_ZERO) {
Edward Creef1174f72017-08-07 15:26:19 +01003447 expected_type = SCALAR_VALUE;
3448 if (type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003449 goto err_type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003450 } else if (arg_type == ARG_CONST_MAP_PTR) {
3451 expected_type = CONST_PTR_TO_MAP;
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003452 if (type != expected_type)
3453 goto err_type;
Daniel Borkmannf3189032020-03-27 16:58:52 +01003454 } else if (arg_type == ARG_PTR_TO_CTX ||
3455 arg_type == ARG_PTR_TO_CTX_OR_NULL) {
Alexei Starovoitov608cd712015-03-26 19:53:57 -07003456 expected_type = PTR_TO_CTX;
Daniel Borkmannf3189032020-03-27 16:58:52 +01003457 if (!(register_is_null(reg) &&
3458 arg_type == ARG_PTR_TO_CTX_OR_NULL)) {
3459 if (type != expected_type)
3460 goto err_type;
3461 err = check_ctx_reg(env, reg, regno);
3462 if (err < 0)
3463 return err;
3464 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003465 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
3466 expected_type = PTR_TO_SOCK_COMMON;
3467 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3468 if (!type_is_sk_pointer(type))
3469 goto err_type;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003470 if (reg->ref_obj_id) {
3471 if (meta->ref_obj_id) {
3472 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3473 regno, reg->ref_obj_id,
3474 meta->ref_obj_id);
3475 return -EFAULT;
3476 }
3477 meta->ref_obj_id = reg->ref_obj_id;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003478 }
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003479 } else if (arg_type == ARG_PTR_TO_SOCKET) {
3480 expected_type = PTR_TO_SOCKET;
3481 if (type != expected_type)
3482 goto err_type;
Alexei Starovoitova7658e12019-10-15 20:25:04 -07003483 } else if (arg_type == ARG_PTR_TO_BTF_ID) {
3484 expected_type = PTR_TO_BTF_ID;
3485 if (type != expected_type)
3486 goto err_type;
3487 if (reg->btf_id != meta->btf_id) {
3488 verbose(env, "Helper has type %s got %s in R%d\n",
3489 kernel_type_name(meta->btf_id),
3490 kernel_type_name(reg->btf_id), regno);
3491
3492 return -EACCES;
3493 }
3494 if (!tnum_is_const(reg->var_off) || reg->var_off.value || reg->off) {
3495 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
3496 regno);
3497 return -EACCES;
3498 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003499 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
3500 if (meta->func_id == BPF_FUNC_spin_lock) {
3501 if (process_spin_lock(env, regno, true))
3502 return -EACCES;
3503 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
3504 if (process_spin_lock(env, regno, false))
3505 return -EACCES;
3506 } else {
3507 verbose(env, "verifier internal error\n");
3508 return -EFAULT;
3509 }
Daniel Borkmann90133412018-01-20 01:24:29 +01003510 } else if (arg_type_is_mem_ptr(arg_type)) {
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003511 expected_type = PTR_TO_STACK;
3512 /* One exception here. In case function allows for NULL to be
Edward Creef1174f72017-08-07 15:26:19 +01003513 * passed in as argument, it's a SCALAR_VALUE type. Final test
Daniel Borkmann8e2fe1d92016-02-19 23:05:22 +01003514 * happens during stack boundary checking.
3515 */
Alexei Starovoitov914cb782017-11-30 21:31:40 -08003516 if (register_is_null(reg) &&
Gianluca Borellodb1ac492017-11-22 18:32:53 +00003517 arg_type == ARG_PTR_TO_MEM_OR_NULL)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003518 /* final test in check_stack_boundary() */;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003519 else if (!type_is_pkt_pointer(type) &&
3520 type != PTR_TO_MAP_VALUE &&
Edward Creef1174f72017-08-07 15:26:19 +01003521 type != expected_type)
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003522 goto err_type;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003523 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003524 } else if (arg_type_is_int_ptr(arg_type)) {
3525 expected_type = PTR_TO_STACK;
3526 if (!type_is_pkt_pointer(type) &&
3527 type != PTR_TO_MAP_VALUE &&
3528 type != expected_type)
3529 goto err_type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003530 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003531 verbose(env, "unsupported arg_type %d\n", arg_type);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003532 return -EFAULT;
3533 }
3534
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003535 if (arg_type == ARG_CONST_MAP_PTR) {
3536 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02003537 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003538 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
3539 /* bpf_map_xxx(..., map_ptr, ..., key) call:
3540 * check that [key, key + map->key_size) are within
3541 * stack limits and initialized
3542 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02003543 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003544 /* in function declaration map_ptr must come before
3545 * map_key, so that it's verified and known before
3546 * we have to check map_key here. Otherwise it means
3547 * that kernel subsystem misconfigured verifier
3548 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003549 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003550 return -EACCES;
3551 }
Paul Chaignond71962f2018-04-24 15:07:54 +02003552 err = check_helper_mem_access(env, regno,
3553 meta->map_ptr->key_size, false,
3554 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003555 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003556 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
3557 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003558 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003559 /* bpf_map_xxx(..., map_ptr, ..., value) call:
3560 * check [value, value + map->value_size) validity
3561 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02003562 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003563 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003564 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003565 return -EACCES;
3566 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003567 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02003568 err = check_helper_mem_access(env, regno,
3569 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02003570 meta);
Daniel Borkmann90133412018-01-20 01:24:29 +01003571 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003572 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003573
Yonghong Song849fa502018-04-28 22:28:09 -07003574 /* remember the mem_size which may be used later
3575 * to refine return values.
3576 */
3577 meta->msize_smax_value = reg->smax_value;
3578 meta->msize_umax_value = reg->umax_value;
3579
Edward Creef1174f72017-08-07 15:26:19 +01003580 /* The register is SCALAR_VALUE; the access check
3581 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08003582 */
Edward Creef1174f72017-08-07 15:26:19 +01003583 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08003584 /* For unprivileged variable accesses, disable raw
3585 * mode so that the program is required to
3586 * initialize all the memory that the helper could
3587 * just partially fill up.
3588 */
3589 meta = NULL;
3590
Edward Creeb03c9f92017-08-07 15:26:36 +01003591 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003592 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01003593 regno);
3594 return -EACCES;
3595 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08003596
Edward Creeb03c9f92017-08-07 15:26:36 +01003597 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01003598 err = check_helper_mem_access(env, regno - 1, 0,
3599 zero_size_allowed,
3600 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08003601 if (err)
3602 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08003603 }
Edward Creef1174f72017-08-07 15:26:19 +01003604
Edward Creeb03c9f92017-08-07 15:26:36 +01003605 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003606 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01003607 regno);
3608 return -EACCES;
3609 }
3610 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01003611 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01003612 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07003613 if (!err)
3614 err = mark_chain_precision(env, regno);
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07003615 } else if (arg_type_is_int_ptr(arg_type)) {
3616 int size = int_ptr_type_to_size(arg_type);
3617
3618 err = check_helper_mem_access(env, regno, size, false, meta);
3619 if (err)
3620 return err;
3621 err = check_ptr_alignment(env, reg, 0, size, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003622 }
3623
3624 return err;
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003625err_type:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003626 verbose(env, "R%d type=%s expected=%s\n", regno,
Alexei Starovoitov6841de82016-08-11 18:17:16 -07003627 reg_type_str[type], reg_type_str[expected_type]);
3628 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003629}
3630
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003631static int check_map_func_compatibility(struct bpf_verifier_env *env,
3632 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00003633{
Kaixu Xia35578d72015-08-06 07:02:35 +00003634 if (!map)
3635 return 0;
3636
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003637 /* We need a two way check, first is from map perspective ... */
3638 switch (map->map_type) {
3639 case BPF_MAP_TYPE_PROG_ARRAY:
3640 if (func_id != BPF_FUNC_tail_call)
3641 goto error;
3642 break;
3643 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
3644 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07003645 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07003646 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00003647 func_id != BPF_FUNC_perf_event_read_value &&
3648 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003649 goto error;
3650 break;
3651 case BPF_MAP_TYPE_STACK_TRACE:
3652 if (func_id != BPF_FUNC_get_stackid)
3653 goto error;
3654 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07003655 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04003656 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07003657 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07003658 goto error;
3659 break;
Roman Gushchincd339432018-08-02 14:27:24 -07003660 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00003661 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07003662 if (func_id != BPF_FUNC_get_local_storage)
3663 goto error;
3664 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07003665 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02003666 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02003667 if (func_id != BPF_FUNC_redirect_map &&
3668 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07003669 goto error;
3670 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02003671 /* Restrict bpf side of cpumap and xskmap, open when use-cases
3672 * appear.
3673 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02003674 case BPF_MAP_TYPE_CPUMAP:
3675 if (func_id != BPF_FUNC_redirect_map)
3676 goto error;
3677 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003678 case BPF_MAP_TYPE_XSKMAP:
3679 if (func_id != BPF_FUNC_redirect_map &&
3680 func_id != BPF_FUNC_map_lookup_elem)
3681 goto error;
3682 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07003683 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07003684 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07003685 if (func_id != BPF_FUNC_map_lookup_elem)
3686 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07003687 break;
John Fastabend174a79f2017-08-15 22:32:47 -07003688 case BPF_MAP_TYPE_SOCKMAP:
3689 if (func_id != BPF_FUNC_sk_redirect_map &&
3690 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07003691 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00003692 func_id != BPF_FUNC_msg_redirect_map &&
3693 func_id != BPF_FUNC_sk_select_reuseport)
John Fastabend174a79f2017-08-15 22:32:47 -07003694 goto error;
3695 break;
John Fastabend81110382018-05-14 10:00:17 -07003696 case BPF_MAP_TYPE_SOCKHASH:
3697 if (func_id != BPF_FUNC_sk_redirect_hash &&
3698 func_id != BPF_FUNC_sock_hash_update &&
3699 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00003700 func_id != BPF_FUNC_msg_redirect_hash &&
3701 func_id != BPF_FUNC_sk_select_reuseport)
John Fastabend81110382018-05-14 10:00:17 -07003702 goto error;
3703 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003704 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
3705 if (func_id != BPF_FUNC_sk_select_reuseport)
3706 goto error;
3707 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02003708 case BPF_MAP_TYPE_QUEUE:
3709 case BPF_MAP_TYPE_STACK:
3710 if (func_id != BPF_FUNC_map_peek_elem &&
3711 func_id != BPF_FUNC_map_pop_elem &&
3712 func_id != BPF_FUNC_map_push_elem)
3713 goto error;
3714 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003715 case BPF_MAP_TYPE_SK_STORAGE:
3716 if (func_id != BPF_FUNC_sk_storage_get &&
3717 func_id != BPF_FUNC_sk_storage_delete)
3718 goto error;
3719 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003720 default:
3721 break;
3722 }
3723
3724 /* ... and second from the function itself. */
3725 switch (func_id) {
3726 case BPF_FUNC_tail_call:
3727 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
3728 goto error;
Jiong Wangf910cef2018-05-02 16:17:17 -04003729 if (env->subprog_cnt > 1) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003730 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
3731 return -EINVAL;
3732 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003733 break;
3734 case BPF_FUNC_perf_event_read:
3735 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07003736 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07003737 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00003738 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003739 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
3740 goto error;
3741 break;
3742 case BPF_FUNC_get_stackid:
3743 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
3744 goto error;
3745 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07003746 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02003747 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07003748 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
3749 goto error;
3750 break;
John Fastabend97f91a72017-07-17 09:29:18 -07003751 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02003752 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02003753 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02003754 map->map_type != BPF_MAP_TYPE_CPUMAP &&
3755 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07003756 goto error;
3757 break;
John Fastabend174a79f2017-08-15 22:32:47 -07003758 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07003759 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07003760 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07003761 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
3762 goto error;
3763 break;
John Fastabend81110382018-05-14 10:00:17 -07003764 case BPF_FUNC_sk_redirect_hash:
3765 case BPF_FUNC_msg_redirect_hash:
3766 case BPF_FUNC_sock_hash_update:
3767 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07003768 goto error;
3769 break;
Roman Gushchincd339432018-08-02 14:27:24 -07003770 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00003771 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
3772 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07003773 goto error;
3774 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003775 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00003776 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
3777 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
3778 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003779 goto error;
3780 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02003781 case BPF_FUNC_map_peek_elem:
3782 case BPF_FUNC_map_pop_elem:
3783 case BPF_FUNC_map_push_elem:
3784 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
3785 map->map_type != BPF_MAP_TYPE_STACK)
3786 goto error;
3787 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07003788 case BPF_FUNC_sk_storage_get:
3789 case BPF_FUNC_sk_storage_delete:
3790 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
3791 goto error;
3792 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003793 default:
3794 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00003795 }
3796
3797 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003798error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003799 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02003800 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07003801 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00003802}
3803
Daniel Borkmann90133412018-01-20 01:24:29 +01003804static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003805{
3806 int count = 0;
3807
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003808 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003809 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003810 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003811 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003812 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003813 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003814 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003815 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08003816 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02003817 count++;
3818
Daniel Borkmann90133412018-01-20 01:24:29 +01003819 /* We only support one arg being in raw mode at the moment,
3820 * which is sufficient for the helper functions we have
3821 * right now.
3822 */
3823 return count <= 1;
3824}
3825
3826static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
3827 enum bpf_arg_type arg_next)
3828{
3829 return (arg_type_is_mem_ptr(arg_curr) &&
3830 !arg_type_is_mem_size(arg_next)) ||
3831 (!arg_type_is_mem_ptr(arg_curr) &&
3832 arg_type_is_mem_size(arg_next));
3833}
3834
3835static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
3836{
3837 /* bpf_xxx(..., buf, len) call will access 'len'
3838 * bytes from memory 'buf'. Both arg types need
3839 * to be paired, so make sure there's no buggy
3840 * helper function specification.
3841 */
3842 if (arg_type_is_mem_size(fn->arg1_type) ||
3843 arg_type_is_mem_ptr(fn->arg5_type) ||
3844 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
3845 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
3846 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
3847 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
3848 return false;
3849
3850 return true;
3851}
3852
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003853static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07003854{
3855 int count = 0;
3856
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003857 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003858 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003859 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003860 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003861 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003862 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003863 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003864 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003865 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07003866 count++;
3867
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003868 /* A reference acquiring function cannot acquire
3869 * another refcounted ptr.
3870 */
3871 if (is_acquire_function(func_id) && count)
3872 return false;
3873
Joe Stringerfd978bf72018-10-02 13:35:35 -07003874 /* We only support one arg being unreferenced at the moment,
3875 * which is sufficient for the helper functions we have right now.
3876 */
3877 return count <= 1;
3878}
3879
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003880static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01003881{
3882 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07003883 check_arg_pair_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003884 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02003885}
3886
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003887/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
3888 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01003889 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003890static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
3891 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003892{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003893 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003894 int i;
3895
3896 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003897 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003898 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003899
Joe Stringerf3709f62018-10-02 13:35:29 -07003900 bpf_for_each_spilled_reg(i, state, reg) {
3901 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003902 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003903 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003904 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003905 }
3906}
3907
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003908static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
3909{
3910 struct bpf_verifier_state *vstate = env->cur_state;
3911 int i;
3912
3913 for (i = 0; i <= vstate->curframe; i++)
3914 __clear_all_pkt_pointers(env, vstate->frame[i]);
3915}
3916
Joe Stringerfd978bf72018-10-02 13:35:35 -07003917static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003918 struct bpf_func_state *state,
3919 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07003920{
3921 struct bpf_reg_state *regs = state->regs, *reg;
3922 int i;
3923
3924 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003925 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07003926 mark_reg_unknown(env, regs, i);
3927
3928 bpf_for_each_spilled_reg(i, state, reg) {
3929 if (!reg)
3930 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003931 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01003932 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07003933 }
3934}
3935
3936/* The pointer with the specified id has released its reference to kernel
3937 * resources. Identify all copies of the same pointer and clear the reference.
3938 */
3939static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003940 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07003941{
3942 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003943 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003944 int i;
3945
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003946 err = release_reference_state(cur_func(env), ref_obj_id);
3947 if (err)
3948 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003949
Martin KaFai Lau1b986582019-03-12 10:23:02 -07003950 for (i = 0; i <= vstate->curframe; i++)
3951 release_reg_references(env, vstate->frame[i], ref_obj_id);
3952
3953 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003954}
3955
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003956static void clear_caller_saved_regs(struct bpf_verifier_env *env,
3957 struct bpf_reg_state *regs)
3958{
3959 int i;
3960
3961 /* after the call registers r0 - r5 were scratched */
3962 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3963 mark_reg_not_init(env, regs, caller_saved[i]);
3964 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3965 }
3966}
3967
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003968static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
3969 int *insn_idx)
3970{
3971 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003972 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003973 struct bpf_func_state *caller, *callee;
Joe Stringerfd978bf72018-10-02 13:35:35 -07003974 int i, err, subprog, target_insn;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003975 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003976
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08003977 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003978 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08003979 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003980 return -E2BIG;
3981 }
3982
3983 target_insn = *insn_idx + insn->imm;
3984 subprog = find_subprog(env, target_insn + 1);
3985 if (subprog < 0) {
3986 verbose(env, "verifier bug. No program starts at insn %d\n",
3987 target_insn + 1);
3988 return -EFAULT;
3989 }
3990
3991 caller = state->frame[state->curframe];
3992 if (state->frame[state->curframe + 1]) {
3993 verbose(env, "verifier bug. Frame %d already allocated\n",
3994 state->curframe + 1);
3995 return -EFAULT;
3996 }
3997
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003998 func_info_aux = env->prog->aux->func_info_aux;
3999 if (func_info_aux)
4000 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4001 err = btf_check_func_arg_match(env, subprog, caller->regs);
4002 if (err == -EFAULT)
4003 return err;
4004 if (is_global) {
4005 if (err) {
4006 verbose(env, "Caller passes invalid args into func#%d\n",
4007 subprog);
4008 return err;
4009 } else {
4010 if (env->log.level & BPF_LOG_LEVEL)
4011 verbose(env,
4012 "Func#%d is global and valid. Skipping.\n",
4013 subprog);
4014 clear_caller_saved_regs(env, caller->regs);
4015
4016 /* All global functions return SCALAR_VALUE */
4017 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4018
4019 /* continue with next insn after call */
4020 return 0;
4021 }
4022 }
4023
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004024 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4025 if (!callee)
4026 return -ENOMEM;
4027 state->frame[state->curframe + 1] = callee;
4028
4029 /* callee cannot access r0, r6 - r9 for reading and has to write
4030 * into its own stack before reading from it.
4031 * callee can read/write into caller's stack
4032 */
4033 init_func_state(env, callee,
4034 /* remember the callsite, it will be used by bpf_exit */
4035 *insn_idx /* callsite */,
4036 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04004037 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004038
Joe Stringerfd978bf72018-10-02 13:35:35 -07004039 /* Transfer references to the callee */
4040 err = transfer_reference_state(callee, caller);
4041 if (err)
4042 return err;
4043
Edward Cree679c7822018-08-22 20:02:19 +01004044 /* copy r1 - r5 args that callee can access. The copy includes parent
4045 * pointers, which connects us up to the liveness chain
4046 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004047 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4048 callee->regs[i] = caller->regs[i];
4049
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004050 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004051
4052 /* only increment it after check_reg_arg() finished */
4053 state->curframe++;
4054
4055 /* and go analyze first insn of the callee */
4056 *insn_idx = target_insn;
4057
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004058 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004059 verbose(env, "caller:\n");
4060 print_verifier_state(env, caller);
4061 verbose(env, "callee:\n");
4062 print_verifier_state(env, callee);
4063 }
4064 return 0;
4065}
4066
4067static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4068{
4069 struct bpf_verifier_state *state = env->cur_state;
4070 struct bpf_func_state *caller, *callee;
4071 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07004072 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004073
4074 callee = state->frame[state->curframe];
4075 r0 = &callee->regs[BPF_REG_0];
4076 if (r0->type == PTR_TO_STACK) {
4077 /* technically it's ok to return caller's stack pointer
4078 * (or caller's caller's pointer) back to the caller,
4079 * since these pointers are valid. Only current stack
4080 * pointer will be invalid as soon as function exits,
4081 * but let's be conservative
4082 */
4083 verbose(env, "cannot return stack pointer to the caller\n");
4084 return -EINVAL;
4085 }
4086
4087 state->curframe--;
4088 caller = state->frame[state->curframe];
4089 /* return to the caller whatever r0 had in the callee */
4090 caller->regs[BPF_REG_0] = *r0;
4091
Joe Stringerfd978bf72018-10-02 13:35:35 -07004092 /* Transfer references to the caller */
4093 err = transfer_reference_state(caller, callee);
4094 if (err)
4095 return err;
4096
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004097 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07004098 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004099 verbose(env, "returning from callee:\n");
4100 print_verifier_state(env, callee);
4101 verbose(env, "to caller at %d:\n", *insn_idx);
4102 print_verifier_state(env, caller);
4103 }
4104 /* clear everything in the callee */
4105 free_func_state(callee);
4106 state->frame[state->curframe + 1] = NULL;
4107 return 0;
4108}
4109
Yonghong Song849fa502018-04-28 22:28:09 -07004110static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4111 int func_id,
4112 struct bpf_call_arg_meta *meta)
4113{
4114 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4115
4116 if (ret_type != RET_INTEGER ||
4117 (func_id != BPF_FUNC_get_stack &&
4118 func_id != BPF_FUNC_probe_read_str))
4119 return;
4120
4121 ret_reg->smax_value = meta->msize_smax_value;
4122 ret_reg->umax_value = meta->msize_umax_value;
4123 __reg_deduce_bounds(ret_reg);
4124 __reg_bound_offset(ret_reg);
4125}
4126
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004127static int
4128record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4129 int func_id, int insn_idx)
4130{
4131 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02004132 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004133
4134 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02004135 func_id != BPF_FUNC_map_lookup_elem &&
4136 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004137 func_id != BPF_FUNC_map_delete_elem &&
4138 func_id != BPF_FUNC_map_push_elem &&
4139 func_id != BPF_FUNC_map_pop_elem &&
4140 func_id != BPF_FUNC_map_peek_elem)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004141 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02004142
Daniel Borkmann591fe982019-04-09 23:20:05 +02004143 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004144 verbose(env, "kernel subsystem misconfigured verifier\n");
4145 return -EINVAL;
4146 }
4147
Daniel Borkmann591fe982019-04-09 23:20:05 +02004148 /* In case of read-only, some additional restrictions
4149 * need to be applied in order to prevent altering the
4150 * state of the map from program side.
4151 */
4152 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4153 (func_id == BPF_FUNC_map_delete_elem ||
4154 func_id == BPF_FUNC_map_update_elem ||
4155 func_id == BPF_FUNC_map_push_elem ||
4156 func_id == BPF_FUNC_map_pop_elem)) {
4157 verbose(env, "write into map forbidden\n");
4158 return -EACCES;
4159 }
4160
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004161 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004162 bpf_map_ptr_store(aux, meta->map_ptr,
4163 meta->map_ptr->unpriv_array);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004164 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004165 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
4166 meta->map_ptr->unpriv_array);
4167 return 0;
4168}
4169
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004170static int
4171record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4172 int func_id, int insn_idx)
4173{
4174 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4175 struct bpf_reg_state *regs = cur_regs(env), *reg;
4176 struct bpf_map *map = meta->map_ptr;
4177 struct tnum range;
4178 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004179 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004180
4181 if (func_id != BPF_FUNC_tail_call)
4182 return 0;
4183 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4184 verbose(env, "kernel subsystem misconfigured verifier\n");
4185 return -EINVAL;
4186 }
4187
4188 range = tnum_range(0, map->max_entries - 1);
4189 reg = &regs[BPF_REG_3];
4190
4191 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4192 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4193 return 0;
4194 }
4195
Daniel Borkmanncc52d912019-12-19 22:19:50 +01004196 err = mark_chain_precision(env, BPF_REG_3);
4197 if (err)
4198 return err;
4199
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004200 val = reg->var_off.value;
4201 if (bpf_map_key_unseen(aux))
4202 bpf_map_key_store(aux, val);
4203 else if (!bpf_map_key_poisoned(aux) &&
4204 bpf_map_key_immediate(aux) != val)
4205 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4206 return 0;
4207}
4208
Joe Stringerfd978bf72018-10-02 13:35:35 -07004209static int check_reference_leak(struct bpf_verifier_env *env)
4210{
4211 struct bpf_func_state *state = cur_func(env);
4212 int i;
4213
4214 for (i = 0; i < state->acquired_refs; i++) {
4215 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4216 state->refs[i].id, state->refs[i].insn_idx);
4217 }
4218 return state->acquired_refs ? -EINVAL : 0;
4219}
4220
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004221static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004222{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004223 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004224 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004225 struct bpf_call_arg_meta meta;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004226 bool changes_data;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004227 int i, err;
4228
4229 /* find function prototype */
4230 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004231 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4232 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004233 return -EINVAL;
4234 }
4235
Jakub Kicinski00176a32017-10-16 16:40:54 -07004236 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07004237 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004238 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004239 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4240 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004241 return -EINVAL;
4242 }
4243
4244 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01004245 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02004246 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004247 return -EINVAL;
4248 }
4249
Daniel Borkmann04514d12017-12-14 21:07:25 +01004250 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08004251 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01004252 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4253 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4254 func_id_name(func_id), func_id);
4255 return -EINVAL;
4256 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004257
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004258 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02004259 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004260
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004261 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004262 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004263 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004264 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004265 return err;
4266 }
4267
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004268 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004269 /* check args */
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004270 for (i = 0; i < 5; i++) {
Alexei Starovoitov9cc31b32019-11-14 10:57:14 -08004271 err = btf_resolve_helper_id(&env->log, fn, i);
4272 if (err > 0)
4273 meta.btf_id = err;
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004274 err = check_func_arg(env, BPF_REG_1 + i, fn->arg_type[i], &meta);
4275 if (err)
4276 return err;
4277 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004278
Daniel Borkmannc93552c2018-05-24 02:32:53 +02004279 err = record_func_map(env, &meta, func_id, insn_idx);
4280 if (err)
4281 return err;
4282
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01004283 err = record_func_key(env, &meta, func_id, insn_idx);
4284 if (err)
4285 return err;
4286
Daniel Borkmann435faee12016-04-13 00:10:51 +02004287 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4288 * is inferred from register state.
4289 */
4290 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01004291 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4292 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02004293 if (err)
4294 return err;
4295 }
4296
Joe Stringerfd978bf72018-10-02 13:35:35 -07004297 if (func_id == BPF_FUNC_tail_call) {
4298 err = check_reference_leak(env);
4299 if (err) {
4300 verbose(env, "tail_call would lead to reference leak\n");
4301 return err;
4302 }
4303 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004304 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004305 if (err) {
4306 verbose(env, "func %s#%d reference has not been acquired before\n",
4307 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07004308 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004309 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07004310 }
4311
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004312 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07004313
4314 /* check that flags argument in get_local_storage(map, flags) is 0,
4315 * this is required because get_local_storage() can't return an error.
4316 */
4317 if (func_id == BPF_FUNC_get_local_storage &&
4318 !register_is_null(&regs[BPF_REG_2])) {
4319 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4320 return -EINVAL;
4321 }
4322
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004323 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01004324 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004325 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01004326 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4327 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004328
Jiong Wang5327ed32019-05-24 23:25:12 +01004329 /* helper call returns 64-bit value. */
4330 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4331
Edward Creedc503a82017-08-15 20:34:35 +01004332 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004333 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01004334 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004335 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004336 } else if (fn->ret_type == RET_VOID) {
4337 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07004338 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4339 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01004340 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004341 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004342 /* remember map_ptr, so that check_map_access()
4343 * can check 'value_size' boundary of memory access
4344 * to map element returned from bpf_map_lookup_elem()
4345 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004346 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004347 verbose(env,
4348 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004349 return -EINVAL;
4350 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004351 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01004352 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4353 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08004354 if (map_value_has_spin_lock(meta.map_ptr))
4355 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01004356 } else {
4357 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4358 regs[BPF_REG_0].id = ++env->id_gen;
4359 }
Joe Stringerc64b7982018-10-02 13:35:33 -07004360 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4361 mark_reg_known_zero(env, regs, BPF_REG_0);
4362 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08004363 regs[BPF_REG_0].id = ++env->id_gen;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08004364 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4365 mark_reg_known_zero(env, regs, BPF_REG_0);
4366 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4367 regs[BPF_REG_0].id = ++env->id_gen;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08004368 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4369 mark_reg_known_zero(env, regs, BPF_REG_0);
4370 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4371 regs[BPF_REG_0].id = ++env->id_gen;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004372 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004373 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02004374 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004375 return -EINVAL;
4376 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07004377
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08004378 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004379 /* For release_reference() */
4380 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08004381 } else if (is_acquire_function(func_id)) {
4382 int id = acquire_reference_state(env, insn_idx);
4383
4384 if (id < 0)
4385 return id;
4386 /* For mark_ptr_or_null_reg() */
4387 regs[BPF_REG_0].id = id;
4388 /* For release_reference() */
4389 regs[BPF_REG_0].ref_obj_id = id;
4390 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07004391
Yonghong Song849fa502018-04-28 22:28:09 -07004392 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
4393
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004394 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00004395 if (err)
4396 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07004397
Yonghong Songc195651e2018-04-28 22:28:08 -07004398 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
4399 const char *err_str;
4400
4401#ifdef CONFIG_PERF_EVENTS
4402 err = get_callchain_buffers(sysctl_perf_event_max_stack);
4403 err_str = "cannot get callchain buffer for func %s#%d\n";
4404#else
4405 err = -ENOTSUPP;
4406 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4407#endif
4408 if (err) {
4409 verbose(env, err_str, func_id_name(func_id), func_id);
4410 return err;
4411 }
4412
4413 env->prog->has_callchain_buf = true;
4414 }
4415
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004416 if (changes_data)
4417 clear_all_pkt_pointers(env);
4418 return 0;
4419}
4420
Edward Creeb03c9f92017-08-07 15:26:36 +01004421static bool signed_add_overflows(s64 a, s64 b)
4422{
4423 /* Do the add in u64, where overflow is well-defined */
4424 s64 res = (s64)((u64)a + (u64)b);
4425
4426 if (b < 0)
4427 return res > a;
4428 return res < a;
4429}
4430
4431static bool signed_sub_overflows(s64 a, s64 b)
4432{
4433 /* Do the sub in u64, where overflow is well-defined */
4434 s64 res = (s64)((u64)a - (u64)b);
4435
4436 if (b < 0)
4437 return res < a;
4438 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07004439}
4440
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08004441static bool check_reg_sane_offset(struct bpf_verifier_env *env,
4442 const struct bpf_reg_state *reg,
4443 enum bpf_reg_type type)
4444{
4445 bool known = tnum_is_const(reg->var_off);
4446 s64 val = reg->var_off.value;
4447 s64 smin = reg->smin_value;
4448
4449 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
4450 verbose(env, "math between %s pointer and %lld is not allowed\n",
4451 reg_type_str[type], val);
4452 return false;
4453 }
4454
4455 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
4456 verbose(env, "%s pointer offset %d is not allowed\n",
4457 reg_type_str[type], reg->off);
4458 return false;
4459 }
4460
4461 if (smin == S64_MIN) {
4462 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
4463 reg_type_str[type]);
4464 return false;
4465 }
4466
4467 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
4468 verbose(env, "value %lld makes %s pointer be out of bounds\n",
4469 smin, reg_type_str[type]);
4470 return false;
4471 }
4472
4473 return true;
4474}
4475
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004476static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
4477{
4478 return &env->insn_aux_data[env->insn_idx];
4479}
4480
4481static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
4482 u32 *ptr_limit, u8 opcode, bool off_is_neg)
4483{
4484 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
4485 (opcode == BPF_SUB && !off_is_neg);
4486 u32 off;
4487
4488 switch (ptr_reg->type) {
4489 case PTR_TO_STACK:
Andrey Ignatov088ec262019-04-03 23:22:39 -07004490 /* Indirect variable offset stack access is prohibited in
4491 * unprivileged mode so it's not handled here.
4492 */
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004493 off = ptr_reg->off + ptr_reg->var_off.value;
4494 if (mask_to_left)
4495 *ptr_limit = MAX_BPF_STACK + off;
4496 else
4497 *ptr_limit = -off;
4498 return 0;
4499 case PTR_TO_MAP_VALUE:
4500 if (mask_to_left) {
4501 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
4502 } else {
4503 off = ptr_reg->smin_value + ptr_reg->off;
4504 *ptr_limit = ptr_reg->map_ptr->value_size - off;
4505 }
4506 return 0;
4507 default:
4508 return -EINVAL;
4509 }
4510}
4511
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01004512static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
4513 const struct bpf_insn *insn)
4514{
4515 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
4516}
4517
4518static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
4519 u32 alu_state, u32 alu_limit)
4520{
4521 /* If we arrived here from different branches with different
4522 * state or limits to sanitize, then this won't work.
4523 */
4524 if (aux->alu_state &&
4525 (aux->alu_state != alu_state ||
4526 aux->alu_limit != alu_limit))
4527 return -EACCES;
4528
4529 /* Corresponding fixup done in fixup_bpf_calls(). */
4530 aux->alu_state = alu_state;
4531 aux->alu_limit = alu_limit;
4532 return 0;
4533}
4534
4535static int sanitize_val_alu(struct bpf_verifier_env *env,
4536 struct bpf_insn *insn)
4537{
4538 struct bpf_insn_aux_data *aux = cur_aux(env);
4539
4540 if (can_skip_alu_sanitation(env, insn))
4541 return 0;
4542
4543 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
4544}
4545
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004546static int sanitize_ptr_alu(struct bpf_verifier_env *env,
4547 struct bpf_insn *insn,
4548 const struct bpf_reg_state *ptr_reg,
4549 struct bpf_reg_state *dst_reg,
4550 bool off_is_neg)
4551{
4552 struct bpf_verifier_state *vstate = env->cur_state;
4553 struct bpf_insn_aux_data *aux = cur_aux(env);
4554 bool ptr_is_dst_reg = ptr_reg == dst_reg;
4555 u8 opcode = BPF_OP(insn->code);
4556 u32 alu_state, alu_limit;
4557 struct bpf_reg_state tmp;
4558 bool ret;
4559
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01004560 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004561 return 0;
4562
4563 /* We already marked aux for masking from non-speculative
4564 * paths, thus we got here in the first place. We only care
4565 * to explore bad access from here.
4566 */
4567 if (vstate->speculative)
4568 goto do_sim;
4569
4570 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
4571 alu_state |= ptr_is_dst_reg ?
4572 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
4573
4574 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
4575 return 0;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01004576 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004577 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004578do_sim:
4579 /* Simulate and find potential out-of-bounds access under
4580 * speculative execution from truncation as a result of
4581 * masking when off was not within expected range. If off
4582 * sits in dst, then we temporarily need to move ptr there
4583 * to simulate dst (== 0) +/-= ptr. Needed, for example,
4584 * for cases where we use K-based arithmetic in one direction
4585 * and truncated reg-based in the other in order to explore
4586 * bad access.
4587 */
4588 if (!ptr_is_dst_reg) {
4589 tmp = *dst_reg;
4590 *dst_reg = *ptr_reg;
4591 }
4592 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08004593 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004594 *dst_reg = tmp;
4595 return !ret ? -EFAULT : 0;
4596}
4597
Edward Creef1174f72017-08-07 15:26:19 +01004598/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01004599 * Caller should also handle BPF_MOV case separately.
4600 * If we return -EACCES, caller may want to try again treating pointer as a
4601 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
4602 */
4603static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
4604 struct bpf_insn *insn,
4605 const struct bpf_reg_state *ptr_reg,
4606 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04004607{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004608 struct bpf_verifier_state *vstate = env->cur_state;
4609 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4610 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01004611 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01004612 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
4613 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
4614 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
4615 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01004616 u32 dst = insn->dst_reg, src = insn->src_reg;
Josef Bacik48461132016-09-28 10:54:32 -04004617 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004618 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04004619
Edward Creef1174f72017-08-07 15:26:19 +01004620 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04004621
Daniel Borkmann6f161012018-01-18 01:15:21 +01004622 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
4623 smin_val > smax_val || umin_val > umax_val) {
4624 /* Taint dst register if offset had invalid bounds derived from
4625 * e.g. dead branches.
4626 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01004627 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01004628 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04004629 }
4630
Edward Creef1174f72017-08-07 15:26:19 +01004631 if (BPF_CLASS(insn->code) != BPF_ALU64) {
4632 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004633 verbose(env,
4634 "R%d 32-bit pointer arithmetic prohibited\n",
4635 dst);
Edward Creef1174f72017-08-07 15:26:19 +01004636 return -EACCES;
4637 }
David S. Millerd1174412017-05-10 11:22:52 -07004638
Joe Stringeraad2eea2018-10-02 13:35:30 -07004639 switch (ptr_reg->type) {
4640 case PTR_TO_MAP_VALUE_OR_NULL:
4641 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
4642 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01004643 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07004644 case CONST_PTR_TO_MAP:
4645 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07004646 case PTR_TO_SOCKET:
4647 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004648 case PTR_TO_SOCK_COMMON:
4649 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08004650 case PTR_TO_TCP_SOCK:
4651 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07004652 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07004653 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
4654 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01004655 return -EACCES;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01004656 case PTR_TO_MAP_VALUE:
4657 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
4658 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
4659 off_reg == dst_reg ? dst : src);
4660 return -EACCES;
4661 }
4662 /* fall-through */
Joe Stringeraad2eea2018-10-02 13:35:30 -07004663 default:
4664 break;
Edward Creef1174f72017-08-07 15:26:19 +01004665 }
4666
4667 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
4668 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04004669 */
Edward Creef1174f72017-08-07 15:26:19 +01004670 dst_reg->type = ptr_reg->type;
4671 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05004672
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08004673 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
4674 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
4675 return -EINVAL;
4676
Josef Bacik48461132016-09-28 10:54:32 -04004677 switch (opcode) {
4678 case BPF_ADD:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004679 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4680 if (ret < 0) {
4681 verbose(env, "R%d tried to add from different maps or paths\n", dst);
4682 return ret;
4683 }
Edward Creef1174f72017-08-07 15:26:19 +01004684 /* We can take a fixed offset as long as it doesn't overflow
4685 * the s32 'off' field
4686 */
Edward Creeb03c9f92017-08-07 15:26:36 +01004687 if (known && (ptr_reg->off + smin_val ==
4688 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01004689 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01004690 dst_reg->smin_value = smin_ptr;
4691 dst_reg->smax_value = smax_ptr;
4692 dst_reg->umin_value = umin_ptr;
4693 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01004694 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01004695 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01004696 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01004697 break;
4698 }
Edward Creef1174f72017-08-07 15:26:19 +01004699 /* A new variable offset is created. Note that off_reg->off
4700 * == 0, since it's a scalar.
4701 * dst_reg gets the pointer type and since some positive
4702 * integer value was added to the pointer, give it a new 'id'
4703 * if it's a PTR_TO_PACKET.
4704 * this creates a new 'base' pointer, off_reg (variable) gets
4705 * added into the variable offset, and we copy the fixed offset
4706 * from ptr_reg.
4707 */
Edward Creeb03c9f92017-08-07 15:26:36 +01004708 if (signed_add_overflows(smin_ptr, smin_val) ||
4709 signed_add_overflows(smax_ptr, smax_val)) {
4710 dst_reg->smin_value = S64_MIN;
4711 dst_reg->smax_value = S64_MAX;
4712 } else {
4713 dst_reg->smin_value = smin_ptr + smin_val;
4714 dst_reg->smax_value = smax_ptr + smax_val;
4715 }
4716 if (umin_ptr + umin_val < umin_ptr ||
4717 umax_ptr + umax_val < umax_ptr) {
4718 dst_reg->umin_value = 0;
4719 dst_reg->umax_value = U64_MAX;
4720 } else {
4721 dst_reg->umin_value = umin_ptr + umin_val;
4722 dst_reg->umax_value = umax_ptr + umax_val;
4723 }
Edward Creef1174f72017-08-07 15:26:19 +01004724 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
4725 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01004726 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004727 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01004728 dst_reg->id = ++env->id_gen;
4729 /* something was added to pkt_ptr, set range to zero */
Daniel Borkmann09625902018-11-01 00:05:52 +01004730 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01004731 }
Josef Bacik48461132016-09-28 10:54:32 -04004732 break;
4733 case BPF_SUB:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01004734 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4735 if (ret < 0) {
4736 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
4737 return ret;
4738 }
Edward Creef1174f72017-08-07 15:26:19 +01004739 if (dst_reg == off_reg) {
4740 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004741 verbose(env, "R%d tried to subtract pointer from scalar\n",
4742 dst);
Edward Creef1174f72017-08-07 15:26:19 +01004743 return -EACCES;
4744 }
4745 /* We don't allow subtraction from FP, because (according to
4746 * test_verifier.c test "invalid fp arithmetic", JITs might not
4747 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01004748 */
Edward Creef1174f72017-08-07 15:26:19 +01004749 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004750 verbose(env, "R%d subtraction from stack pointer prohibited\n",
4751 dst);
Edward Creef1174f72017-08-07 15:26:19 +01004752 return -EACCES;
4753 }
Edward Creeb03c9f92017-08-07 15:26:36 +01004754 if (known && (ptr_reg->off - smin_val ==
4755 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01004756 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01004757 dst_reg->smin_value = smin_ptr;
4758 dst_reg->smax_value = smax_ptr;
4759 dst_reg->umin_value = umin_ptr;
4760 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01004761 dst_reg->var_off = ptr_reg->var_off;
4762 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01004763 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01004764 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01004765 break;
4766 }
Edward Creef1174f72017-08-07 15:26:19 +01004767 /* A new variable offset is created. If the subtrahend is known
4768 * nonnegative, then any reg->range we had before is still good.
4769 */
Edward Creeb03c9f92017-08-07 15:26:36 +01004770 if (signed_sub_overflows(smin_ptr, smax_val) ||
4771 signed_sub_overflows(smax_ptr, smin_val)) {
4772 /* Overflow possible, we know nothing */
4773 dst_reg->smin_value = S64_MIN;
4774 dst_reg->smax_value = S64_MAX;
4775 } else {
4776 dst_reg->smin_value = smin_ptr - smax_val;
4777 dst_reg->smax_value = smax_ptr - smin_val;
4778 }
4779 if (umin_ptr < umax_val) {
4780 /* Overflow possible, we know nothing */
4781 dst_reg->umin_value = 0;
4782 dst_reg->umax_value = U64_MAX;
4783 } else {
4784 /* Cannot overflow (as long as bounds are consistent) */
4785 dst_reg->umin_value = umin_ptr - umax_val;
4786 dst_reg->umax_value = umax_ptr - umin_val;
4787 }
Edward Creef1174f72017-08-07 15:26:19 +01004788 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
4789 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01004790 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004791 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01004792 dst_reg->id = ++env->id_gen;
4793 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01004794 if (smin_val < 0)
Daniel Borkmann09625902018-11-01 00:05:52 +01004795 dst_reg->raw = 0;
Edward Creef1174f72017-08-07 15:26:19 +01004796 }
4797 break;
4798 case BPF_AND:
4799 case BPF_OR:
4800 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004801 /* bitwise ops on pointers are troublesome, prohibit. */
4802 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
4803 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01004804 return -EACCES;
4805 default:
4806 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08004807 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
4808 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01004809 return -EACCES;
4810 }
4811
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08004812 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
4813 return -EINVAL;
4814
Edward Creeb03c9f92017-08-07 15:26:36 +01004815 __update_reg_bounds(dst_reg);
4816 __reg_deduce_bounds(dst_reg);
4817 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01004818
4819 /* For unprivileged we require that resulting offset must be in bounds
4820 * in order to be able to sanitize access later on.
4821 */
Daniel Borkmanne4298d22019-01-03 00:58:31 +01004822 if (!env->allow_ptr_leaks) {
4823 if (dst_reg->type == PTR_TO_MAP_VALUE &&
4824 check_map_access(env, dst, dst_reg->off, 1, false)) {
4825 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
4826 "prohibited for !root\n", dst);
4827 return -EACCES;
4828 } else if (dst_reg->type == PTR_TO_STACK &&
4829 check_stack_access(env, dst_reg, dst_reg->off +
4830 dst_reg->var_off.value, 1)) {
4831 verbose(env, "R%d stack pointer arithmetic goes out of range, "
4832 "prohibited for !root\n", dst);
4833 return -EACCES;
4834 }
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01004835 }
4836
Edward Creef1174f72017-08-07 15:26:19 +01004837 return 0;
4838}
4839
John Fastabend07cd2632020-03-24 10:38:15 -07004840static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
4841 struct bpf_reg_state *src_reg)
4842{
4843 s64 smin_val = src_reg->smin_value;
4844 s64 smax_val = src_reg->smax_value;
4845 u64 umin_val = src_reg->umin_value;
4846 u64 umax_val = src_reg->umax_value;
4847
4848 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
4849 signed_add_overflows(dst_reg->smax_value, smax_val)) {
4850 dst_reg->smin_value = S64_MIN;
4851 dst_reg->smax_value = S64_MAX;
4852 } else {
4853 dst_reg->smin_value += smin_val;
4854 dst_reg->smax_value += smax_val;
4855 }
4856 if (dst_reg->umin_value + umin_val < umin_val ||
4857 dst_reg->umax_value + umax_val < umax_val) {
4858 dst_reg->umin_value = 0;
4859 dst_reg->umax_value = U64_MAX;
4860 } else {
4861 dst_reg->umin_value += umin_val;
4862 dst_reg->umax_value += umax_val;
4863 }
4864 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg->var_off);
4865}
4866
4867static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
4868 struct bpf_reg_state *src_reg)
4869{
4870 s64 smin_val = src_reg->smin_value;
4871 s64 smax_val = src_reg->smax_value;
4872 u64 umin_val = src_reg->umin_value;
4873 u64 umax_val = src_reg->umax_value;
4874
4875 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
4876 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
4877 /* Overflow possible, we know nothing */
4878 dst_reg->smin_value = S64_MIN;
4879 dst_reg->smax_value = S64_MAX;
4880 } else {
4881 dst_reg->smin_value -= smax_val;
4882 dst_reg->smax_value -= smin_val;
4883 }
4884 if (dst_reg->umin_value < umax_val) {
4885 /* Overflow possible, we know nothing */
4886 dst_reg->umin_value = 0;
4887 dst_reg->umax_value = U64_MAX;
4888 } else {
4889 /* Cannot overflow (as long as bounds are consistent) */
4890 dst_reg->umin_value -= umax_val;
4891 dst_reg->umax_value -= umin_val;
4892 }
4893 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg->var_off);
4894}
4895
4896static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
4897 struct bpf_reg_state *src_reg)
4898{
4899 s64 smin_val = src_reg->smin_value;
4900 u64 umin_val = src_reg->umin_value;
4901 u64 umax_val = src_reg->umax_value;
4902
4903 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg->var_off);
4904 if (smin_val < 0 || dst_reg->smin_value < 0) {
4905 /* Ain't nobody got time to multiply that sign */
4906 __mark_reg_unbounded(dst_reg);
4907 __update_reg_bounds(dst_reg);
4908 return;
4909 }
4910 /* Both values are positive, so we can work with unsigned and
4911 * copy the result to signed (unless it exceeds S64_MAX).
4912 */
4913 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
4914 /* Potential overflow, we know nothing */
4915 __mark_reg_unbounded(dst_reg);
4916 /* (except what we can learn from the var_off) */
4917 __update_reg_bounds(dst_reg);
4918 return;
4919 }
4920 dst_reg->umin_value *= umin_val;
4921 dst_reg->umax_value *= umax_val;
4922 if (dst_reg->umax_value > S64_MAX) {
4923 /* Overflow possible, we know nothing */
4924 dst_reg->smin_value = S64_MIN;
4925 dst_reg->smax_value = S64_MAX;
4926 } else {
4927 dst_reg->smin_value = dst_reg->umin_value;
4928 dst_reg->smax_value = dst_reg->umax_value;
4929 }
4930}
4931
4932static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
4933 struct bpf_reg_state *src_reg)
4934{
4935 s64 smin_val = src_reg->smin_value;
4936 u64 umax_val = src_reg->umax_value;
4937
4938 /* We get our minimum from the var_off, since that's inherently
4939 * bitwise. Our maximum is the minimum of the operands' maxima.
4940 */
4941 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg->var_off);
4942 dst_reg->umin_value = dst_reg->var_off.value;
4943 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
4944 if (dst_reg->smin_value < 0 || smin_val < 0) {
4945 /* Lose signed bounds when ANDing negative numbers,
4946 * ain't nobody got time for that.
4947 */
4948 dst_reg->smin_value = S64_MIN;
4949 dst_reg->smax_value = S64_MAX;
4950 } else {
4951 /* ANDing two positives gives a positive, so safe to
4952 * cast result into s64.
4953 */
4954 dst_reg->smin_value = dst_reg->umin_value;
4955 dst_reg->smax_value = dst_reg->umax_value;
4956 }
4957 /* We may learn something more from the var_off */
4958 __update_reg_bounds(dst_reg);
4959}
4960
4961static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
4962 struct bpf_reg_state *src_reg)
4963{
4964 s64 smin_val = src_reg->smin_value;
4965 u64 umin_val = src_reg->umin_value;
4966
4967 /* We get our maximum from the var_off, and our minimum is the
4968 * maximum of the operands' minima
4969 */
4970 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg->var_off);
4971 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
4972 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
4973 if (dst_reg->smin_value < 0 || smin_val < 0) {
4974 /* Lose signed bounds when ORing negative numbers,
4975 * ain't nobody got time for that.
4976 */
4977 dst_reg->smin_value = S64_MIN;
4978 dst_reg->smax_value = S64_MAX;
4979 } else {
4980 /* ORing two positives gives a positive, so safe to
4981 * cast result into s64.
4982 */
4983 dst_reg->smin_value = dst_reg->umin_value;
4984 dst_reg->smax_value = dst_reg->umax_value;
4985 }
4986 /* We may learn something more from the var_off */
4987 __update_reg_bounds(dst_reg);
4988}
4989
4990static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
4991 struct bpf_reg_state *src_reg)
4992{
4993 u64 umax_val = src_reg->umax_value;
4994 u64 umin_val = src_reg->umin_value;
4995
4996 /* We lose all sign bit information (except what we can pick
4997 * up from var_off)
4998 */
4999 dst_reg->smin_value = S64_MIN;
5000 dst_reg->smax_value = S64_MAX;
5001 /* If we might shift our top bit out, then we know nothing */
5002 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
5003 dst_reg->umin_value = 0;
5004 dst_reg->umax_value = U64_MAX;
5005 } else {
5006 dst_reg->umin_value <<= umin_val;
5007 dst_reg->umax_value <<= umax_val;
5008 }
5009 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
5010 /* We may learn something more from the var_off */
5011 __update_reg_bounds(dst_reg);
5012}
5013
5014static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
5015 struct bpf_reg_state *src_reg)
5016{
5017 u64 umax_val = src_reg->umax_value;
5018 u64 umin_val = src_reg->umin_value;
5019
5020 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
5021 * be negative, then either:
5022 * 1) src_reg might be zero, so the sign bit of the result is
5023 * unknown, so we lose our signed bounds
5024 * 2) it's known negative, thus the unsigned bounds capture the
5025 * signed bounds
5026 * 3) the signed bounds cross zero, so they tell us nothing
5027 * about the result
5028 * If the value in dst_reg is known nonnegative, then again the
5029 * unsigned bounts capture the signed bounds.
5030 * Thus, in all cases it suffices to blow away our signed bounds
5031 * and rely on inferring new ones from the unsigned bounds and
5032 * var_off of the result.
5033 */
5034 dst_reg->smin_value = S64_MIN;
5035 dst_reg->smax_value = S64_MAX;
5036 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
5037 dst_reg->umin_value >>= umax_val;
5038 dst_reg->umax_value >>= umin_val;
5039 /* We may learn something more from the var_off */
5040 __update_reg_bounds(dst_reg);
5041}
5042
5043static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
5044 struct bpf_reg_state *src_reg,
5045 u64 insn_bitness)
5046{
5047 u64 umin_val = src_reg->umin_value;
5048
5049 /* Upon reaching here, src_known is true and
5050 * umax_val is equal to umin_val.
5051 */
5052 if (insn_bitness == 32) {
5053 dst_reg->smin_value = (u32)(((s32)dst_reg->smin_value) >> umin_val);
5054 dst_reg->smax_value = (u32)(((s32)dst_reg->smax_value) >> umin_val);
5055 } else {
5056 dst_reg->smin_value >>= umin_val;
5057 dst_reg->smax_value >>= umin_val;
5058 }
5059
5060 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val,
5061 insn_bitness);
5062
5063 /* blow away the dst_reg umin_value/umax_value and rely on
5064 * dst_reg var_off to refine the result.
5065 */
5066 dst_reg->umin_value = 0;
5067 dst_reg->umax_value = U64_MAX;
5068 __update_reg_bounds(dst_reg);
5069}
5070
Jann Horn468f6ea2017-12-18 20:11:56 -08005071/* WARNING: This function does calculations on 64-bit values, but the actual
5072 * execution may occur on 32-bit values. Therefore, things like bitshifts
5073 * need extra checks in the 32-bit case.
5074 */
Edward Creef1174f72017-08-07 15:26:19 +01005075static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
5076 struct bpf_insn *insn,
5077 struct bpf_reg_state *dst_reg,
5078 struct bpf_reg_state src_reg)
5079{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005080 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01005081 u8 opcode = BPF_OP(insn->code);
5082 bool src_known, dst_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01005083 s64 smin_val, smax_val;
5084 u64 umin_val, umax_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08005085 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005086 u32 dst = insn->dst_reg;
5087 int ret;
Edward Creef1174f72017-08-07 15:26:19 +01005088
Jann Hornb7992072018-10-05 18:17:59 +02005089 if (insn_bitness == 32) {
5090 /* Relevant for 32-bit RSH: Information can propagate towards
5091 * LSB, so it isn't sufficient to only truncate the output to
5092 * 32 bits.
5093 */
5094 coerce_reg_to_size(dst_reg, 4);
5095 coerce_reg_to_size(&src_reg, 4);
5096 }
5097
Edward Creeb03c9f92017-08-07 15:26:36 +01005098 smin_val = src_reg.smin_value;
5099 smax_val = src_reg.smax_value;
5100 umin_val = src_reg.umin_value;
5101 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01005102 src_known = tnum_is_const(src_reg.var_off);
5103 dst_known = tnum_is_const(dst_reg->var_off);
5104
Daniel Borkmann6f161012018-01-18 01:15:21 +01005105 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
5106 smin_val > smax_val || umin_val > umax_val) {
5107 /* Taint dst register if offset had invalid bounds derived from
5108 * e.g. dead branches.
5109 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005110 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01005111 return 0;
5112 }
5113
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005114 if (!src_known &&
5115 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005116 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005117 return 0;
5118 }
5119
Edward Creef1174f72017-08-07 15:26:19 +01005120 switch (opcode) {
5121 case BPF_ADD:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005122 ret = sanitize_val_alu(env, insn);
5123 if (ret < 0) {
5124 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
5125 return ret;
5126 }
John Fastabend07cd2632020-03-24 10:38:15 -07005127 scalar_min_max_add(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005128 break;
5129 case BPF_SUB:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005130 ret = sanitize_val_alu(env, insn);
5131 if (ret < 0) {
5132 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
5133 return ret;
5134 }
John Fastabend07cd2632020-03-24 10:38:15 -07005135 scalar_min_max_sub(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005136 break;
5137 case BPF_MUL:
John Fastabend07cd2632020-03-24 10:38:15 -07005138 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005139 break;
5140 case BPF_AND:
Edward Creef1174f72017-08-07 15:26:19 +01005141 if (src_known && dst_known) {
Edward Creeb03c9f92017-08-07 15:26:36 +01005142 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5143 src_reg.var_off.value);
Edward Creef1174f72017-08-07 15:26:19 +01005144 break;
5145 }
John Fastabend07cd2632020-03-24 10:38:15 -07005146 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005147 break;
5148 case BPF_OR:
5149 if (src_known && dst_known) {
Edward Creeb03c9f92017-08-07 15:26:36 +01005150 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5151 src_reg.var_off.value);
Edward Creef1174f72017-08-07 15:26:19 +01005152 break;
5153 }
John Fastabend07cd2632020-03-24 10:38:15 -07005154 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005155 break;
5156 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08005157 if (umax_val >= insn_bitness) {
5158 /* Shifts greater than 31 or 63 are undefined.
5159 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01005160 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005161 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005162 break;
5163 }
John Fastabend07cd2632020-03-24 10:38:15 -07005164 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005165 break;
5166 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08005167 if (umax_val >= insn_bitness) {
5168 /* Shifts greater than 31 or 63 are undefined.
5169 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01005170 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005171 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005172 break;
5173 }
John Fastabend07cd2632020-03-24 10:38:15 -07005174 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005175 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07005176 case BPF_ARSH:
5177 if (umax_val >= insn_bitness) {
5178 /* Shifts greater than 31 or 63 are undefined.
5179 * This includes shifts by a negative number.
5180 */
5181 mark_reg_unknown(env, regs, insn->dst_reg);
5182 break;
5183 }
John Fastabend07cd2632020-03-24 10:38:15 -07005184 scalar_min_max_arsh(dst_reg, &src_reg, insn_bitness);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07005185 break;
Josef Bacik48461132016-09-28 10:54:32 -04005186 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005187 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005188 break;
5189 }
5190
Jann Horn468f6ea2017-12-18 20:11:56 -08005191 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5192 /* 32-bit ALU ops are (32,32)->32 */
5193 coerce_reg_to_size(dst_reg, 4);
Jann Horn468f6ea2017-12-18 20:11:56 -08005194 }
5195
John Fastabend294f2fc2020-03-24 10:38:37 -07005196 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01005197 __reg_deduce_bounds(dst_reg);
5198 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005199 return 0;
5200}
5201
5202/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
5203 * and var_off.
5204 */
5205static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
5206 struct bpf_insn *insn)
5207{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005208 struct bpf_verifier_state *vstate = env->cur_state;
5209 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5210 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01005211 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
5212 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005213 int err;
Edward Creef1174f72017-08-07 15:26:19 +01005214
5215 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01005216 src_reg = NULL;
5217 if (dst_reg->type != SCALAR_VALUE)
5218 ptr_reg = dst_reg;
5219 if (BPF_SRC(insn->code) == BPF_X) {
5220 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01005221 if (src_reg->type != SCALAR_VALUE) {
5222 if (dst_reg->type != SCALAR_VALUE) {
5223 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005224 * an arbitrary scalar. Disallow all math except
5225 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01005226 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07005227 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005228 mark_reg_unknown(env, regs, insn->dst_reg);
5229 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01005230 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005231 verbose(env, "R%d pointer %s pointer prohibited\n",
5232 insn->dst_reg,
5233 bpf_alu_string[opcode >> 4]);
5234 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01005235 } else {
5236 /* scalar += pointer
5237 * This is legal, but we have to reverse our
5238 * src/dest handling in computing the range
5239 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005240 err = mark_chain_precision(env, insn->dst_reg);
5241 if (err)
5242 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005243 return adjust_ptr_min_max_vals(env, insn,
5244 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005245 }
5246 } else if (ptr_reg) {
5247 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005248 err = mark_chain_precision(env, insn->src_reg);
5249 if (err)
5250 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005251 return adjust_ptr_min_max_vals(env, insn,
5252 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005253 }
5254 } else {
5255 /* Pretend the src is a reg with a known value, since we only
5256 * need to be able to read from this state.
5257 */
5258 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01005259 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01005260 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08005261 if (ptr_reg) /* pointer += K */
5262 return adjust_ptr_min_max_vals(env, insn,
5263 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005264 }
5265
5266 /* Got here implies adding two SCALAR_VALUEs */
5267 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005268 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005269 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01005270 return -EINVAL;
5271 }
5272 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005273 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005274 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01005275 return -EINVAL;
5276 }
5277 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005278}
5279
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005280/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01005281static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005282{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005283 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005284 u8 opcode = BPF_OP(insn->code);
5285 int err;
5286
5287 if (opcode == BPF_END || opcode == BPF_NEG) {
5288 if (opcode == BPF_NEG) {
5289 if (BPF_SRC(insn->code) != 0 ||
5290 insn->src_reg != BPF_REG_0 ||
5291 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005292 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005293 return -EINVAL;
5294 }
5295 } else {
5296 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01005297 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
5298 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005299 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005300 return -EINVAL;
5301 }
5302 }
5303
5304 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01005305 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005306 if (err)
5307 return err;
5308
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005309 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005310 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005311 insn->dst_reg);
5312 return -EACCES;
5313 }
5314
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005315 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01005316 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005317 if (err)
5318 return err;
5319
5320 } else if (opcode == BPF_MOV) {
5321
5322 if (BPF_SRC(insn->code) == BPF_X) {
5323 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005324 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005325 return -EINVAL;
5326 }
5327
5328 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01005329 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005330 if (err)
5331 return err;
5332 } else {
5333 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005334 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005335 return -EINVAL;
5336 }
5337 }
5338
Arthur Fabrefbeb1602018-07-31 18:17:22 +01005339 /* check dest operand, mark as required later */
5340 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005341 if (err)
5342 return err;
5343
5344 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05005345 struct bpf_reg_state *src_reg = regs + insn->src_reg;
5346 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
5347
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005348 if (BPF_CLASS(insn->code) == BPF_ALU64) {
5349 /* case: R1 = R2
5350 * copy register state to dest reg
5351 */
Jiong Wange434b8c2018-12-07 12:16:18 -05005352 *dst_reg = *src_reg;
5353 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01005354 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005355 } else {
Edward Creef1174f72017-08-07 15:26:19 +01005356 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005357 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005358 verbose(env,
5359 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005360 insn->src_reg);
5361 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05005362 } else if (src_reg->type == SCALAR_VALUE) {
5363 *dst_reg = *src_reg;
5364 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01005365 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05005366 } else {
5367 mark_reg_unknown(env, regs,
5368 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005369 }
Jiong Wange434b8c2018-12-07 12:16:18 -05005370 coerce_reg_to_size(dst_reg, 4);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005371 }
5372 } else {
5373 /* case: R = imm
5374 * remember the value we stored into this reg
5375 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01005376 /* clear any state __mark_reg_known doesn't set */
5377 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005378 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08005379 if (BPF_CLASS(insn->code) == BPF_ALU64) {
5380 __mark_reg_known(regs + insn->dst_reg,
5381 insn->imm);
5382 } else {
5383 __mark_reg_known(regs + insn->dst_reg,
5384 (u32)insn->imm);
5385 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005386 }
5387
5388 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005389 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005390 return -EINVAL;
5391
5392 } else { /* all other ALU ops: and, sub, xor, add, ... */
5393
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005394 if (BPF_SRC(insn->code) == BPF_X) {
5395 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005396 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005397 return -EINVAL;
5398 }
5399 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01005400 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005401 if (err)
5402 return err;
5403 } else {
5404 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005405 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005406 return -EINVAL;
5407 }
5408 }
5409
5410 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01005411 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005412 if (err)
5413 return err;
5414
5415 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
5416 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005417 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005418 return -EINVAL;
5419 }
5420
Rabin Vincent229394e82016-01-12 20:17:08 +01005421 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
5422 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
5423 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
5424
5425 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005426 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01005427 return -EINVAL;
5428 }
5429 }
5430
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07005431 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01005432 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07005433 if (err)
5434 return err;
5435
Edward Creef1174f72017-08-07 15:26:19 +01005436 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005437 }
5438
5439 return 0;
5440}
5441
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02005442static void __find_good_pkt_pointers(struct bpf_func_state *state,
5443 struct bpf_reg_state *dst_reg,
5444 enum bpf_reg_type type, u16 new_range)
5445{
5446 struct bpf_reg_state *reg;
5447 int i;
5448
5449 for (i = 0; i < MAX_BPF_REG; i++) {
5450 reg = &state->regs[i];
5451 if (reg->type == type && reg->id == dst_reg->id)
5452 /* keep the maximum range already checked */
5453 reg->range = max(reg->range, new_range);
5454 }
5455
5456 bpf_for_each_spilled_reg(i, state, reg) {
5457 if (!reg)
5458 continue;
5459 if (reg->type == type && reg->id == dst_reg->id)
5460 reg->range = max(reg->range, new_range);
5461 }
5462}
5463
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005464static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005465 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01005466 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005467 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005468{
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005469 u16 new_range;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02005470 int i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005471
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005472 if (dst_reg->off < 0 ||
5473 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01005474 /* This doesn't give us any range */
5475 return;
5476
Edward Creeb03c9f92017-08-07 15:26:36 +01005477 if (dst_reg->umax_value > MAX_PACKET_OFF ||
5478 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01005479 /* Risk of overflow. For instance, ptr + (1<<63) may be less
5480 * than pkt_end, but that's because it's also less than pkt.
5481 */
5482 return;
5483
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005484 new_range = dst_reg->off;
5485 if (range_right_open)
5486 new_range--;
5487
5488 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005489 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005490 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005491 *
5492 * r2 = r3;
5493 * r2 += 8;
5494 * if (r2 > pkt_end) goto <handle exception>
5495 * <access okay>
5496 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005497 * r2 = r3;
5498 * r2 += 8;
5499 * if (r2 < pkt_end) goto <access okay>
5500 * <handle exception>
5501 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005502 * Where:
5503 * r2 == dst_reg, pkt_end == src_reg
5504 * r2=pkt(id=n,off=8,r=0)
5505 * r3=pkt(id=n,off=0,r=0)
5506 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005507 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005508 *
5509 * r2 = r3;
5510 * r2 += 8;
5511 * if (pkt_end >= r2) goto <access okay>
5512 * <handle exception>
5513 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005514 * r2 = r3;
5515 * r2 += 8;
5516 * if (pkt_end <= r2) goto <handle exception>
5517 * <access okay>
5518 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005519 * Where:
5520 * pkt_end == dst_reg, r2 == src_reg
5521 * r2=pkt(id=n,off=8,r=0)
5522 * r3=pkt(id=n,off=0,r=0)
5523 *
5524 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02005525 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
5526 * and [r3, r3 + 8-1) respectively is safe to access depending on
5527 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005528 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02005529
Edward Creef1174f72017-08-07 15:26:19 +01005530 /* If our ids match, then we must have the same max_value. And we
5531 * don't care about the other reg's fixed offset, since if it's too big
5532 * the range won't allow anything.
5533 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
5534 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02005535 for (i = 0; i <= vstate->curframe; i++)
5536 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
5537 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005538}
5539
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005540/* compute branch direction of the expression "if (reg opcode val) goto target;"
5541 * and return:
5542 * 1 - branch will be taken and "goto target" will be executed
5543 * 0 - branch will not be taken and fall-through to next insn
5544 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
5545 */
Jiong Wang092ed092019-01-26 12:26:01 -05005546static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
5547 bool is_jmp32)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005548{
Jiong Wang092ed092019-01-26 12:26:01 -05005549 struct bpf_reg_state reg_lo;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005550 s64 sval;
5551
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005552 if (__is_pointer_value(false, reg))
5553 return -1;
5554
Jiong Wang092ed092019-01-26 12:26:01 -05005555 if (is_jmp32) {
5556 reg_lo = *reg;
5557 reg = &reg_lo;
5558 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
5559 * could truncate high bits and update umin/umax according to
5560 * information of low bits.
5561 */
5562 coerce_reg_to_size(reg, 4);
5563 /* smin/smax need special handling. For example, after coerce,
5564 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
5565 * used as operand to JMP32. It is a negative number from s32's
5566 * point of view, while it is a positive number when seen as
5567 * s64. The smin/smax are kept as s64, therefore, when used with
5568 * JMP32, they need to be transformed into s32, then sign
5569 * extended back to s64.
5570 *
5571 * Also, smin/smax were copied from umin/umax. If umin/umax has
5572 * different sign bit, then min/max relationship doesn't
5573 * maintain after casting into s32, for this case, set smin/smax
5574 * to safest range.
5575 */
5576 if ((reg->umax_value ^ reg->umin_value) &
5577 (1ULL << 31)) {
5578 reg->smin_value = S32_MIN;
5579 reg->smax_value = S32_MAX;
5580 }
5581 reg->smin_value = (s64)(s32)reg->smin_value;
5582 reg->smax_value = (s64)(s32)reg->smax_value;
5583
5584 val = (u32)val;
5585 sval = (s64)(s32)val;
5586 } else {
5587 sval = (s64)val;
5588 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05005589
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005590 switch (opcode) {
5591 case BPF_JEQ:
5592 if (tnum_is_const(reg->var_off))
5593 return !!tnum_equals_const(reg->var_off, val);
5594 break;
5595 case BPF_JNE:
5596 if (tnum_is_const(reg->var_off))
5597 return !tnum_equals_const(reg->var_off, val);
5598 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08005599 case BPF_JSET:
5600 if ((~reg->var_off.mask & reg->var_off.value) & val)
5601 return 1;
5602 if (!((reg->var_off.mask | reg->var_off.value) & val))
5603 return 0;
5604 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005605 case BPF_JGT:
5606 if (reg->umin_value > val)
5607 return 1;
5608 else if (reg->umax_value <= val)
5609 return 0;
5610 break;
5611 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005612 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005613 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005614 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005615 return 0;
5616 break;
5617 case BPF_JLT:
5618 if (reg->umax_value < val)
5619 return 1;
5620 else if (reg->umin_value >= val)
5621 return 0;
5622 break;
5623 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005624 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005625 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005626 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005627 return 0;
5628 break;
5629 case BPF_JGE:
5630 if (reg->umin_value >= val)
5631 return 1;
5632 else if (reg->umax_value < val)
5633 return 0;
5634 break;
5635 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005636 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005637 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005638 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005639 return 0;
5640 break;
5641 case BPF_JLE:
5642 if (reg->umax_value <= val)
5643 return 1;
5644 else if (reg->umin_value > val)
5645 return 0;
5646 break;
5647 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005648 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005649 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005650 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08005651 return 0;
5652 break;
5653 }
5654
5655 return -1;
5656}
5657
Jiong Wang092ed092019-01-26 12:26:01 -05005658/* Generate min value of the high 32-bit from TNUM info. */
5659static u64 gen_hi_min(struct tnum var)
5660{
5661 return var.value & ~0xffffffffULL;
5662}
5663
5664/* Generate max value of the high 32-bit from TNUM info. */
5665static u64 gen_hi_max(struct tnum var)
5666{
5667 return (var.value | var.mask) & ~0xffffffffULL;
5668}
5669
5670/* Return true if VAL is compared with a s64 sign extended from s32, and they
5671 * are with the same signedness.
5672 */
5673static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
5674{
5675 return ((s32)sval >= 0 &&
5676 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
5677 ((s32)sval < 0 &&
5678 reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
5679}
5680
Jann Horn604dca52020-03-30 18:03:23 +02005681/* Constrain the possible values of @reg with unsigned upper bound @bound.
5682 * If @is_exclusive, @bound is an exclusive limit, otherwise it is inclusive.
5683 * If @is_jmp32, @bound is a 32-bit value that only constrains the low 32 bits
5684 * of @reg.
5685 */
5686static void set_upper_bound(struct bpf_reg_state *reg, u64 bound, bool is_jmp32,
5687 bool is_exclusive)
5688{
5689 if (is_exclusive) {
5690 /* There are no values for `reg` that make `reg<0` true. */
5691 if (bound == 0)
5692 return;
5693 bound--;
5694 }
5695 if (is_jmp32) {
5696 /* Constrain the register's value in the tnum representation.
5697 * For 64-bit comparisons this happens later in
5698 * __reg_bound_offset(), but for 32-bit comparisons, we can be
5699 * more precise than what can be derived from the updated
5700 * numeric bounds.
5701 */
5702 struct tnum t = tnum_range(0, bound);
5703
5704 t.mask |= ~0xffffffffULL; /* upper half is unknown */
5705 reg->var_off = tnum_intersect(reg->var_off, t);
5706
5707 /* Compute the 64-bit bound from the 32-bit bound. */
5708 bound += gen_hi_max(reg->var_off);
5709 }
5710 reg->umax_value = min(reg->umax_value, bound);
5711}
5712
5713/* Constrain the possible values of @reg with unsigned lower bound @bound.
5714 * If @is_exclusive, @bound is an exclusive limit, otherwise it is inclusive.
5715 * If @is_jmp32, @bound is a 32-bit value that only constrains the low 32 bits
5716 * of @reg.
5717 */
5718static void set_lower_bound(struct bpf_reg_state *reg, u64 bound, bool is_jmp32,
5719 bool is_exclusive)
5720{
5721 if (is_exclusive) {
5722 /* There are no values for `reg` that make `reg>MAX` true. */
5723 if (bound == (is_jmp32 ? U32_MAX : U64_MAX))
5724 return;
5725 bound++;
5726 }
5727 if (is_jmp32) {
5728 /* Constrain the register's value in the tnum representation.
5729 * For 64-bit comparisons this happens later in
5730 * __reg_bound_offset(), but for 32-bit comparisons, we can be
5731 * more precise than what can be derived from the updated
5732 * numeric bounds.
5733 */
5734 struct tnum t = tnum_range(bound, U32_MAX);
5735
5736 t.mask |= ~0xffffffffULL; /* upper half is unknown */
5737 reg->var_off = tnum_intersect(reg->var_off, t);
5738
5739 /* Compute the 64-bit bound from the 32-bit bound. */
5740 bound += gen_hi_min(reg->var_off);
5741 }
5742 reg->umin_value = max(reg->umin_value, bound);
5743}
5744
Josef Bacik48461132016-09-28 10:54:32 -04005745/* Adjusts the register min/max values in the case that the dst_reg is the
5746 * variable register that we are working on, and src_reg is a constant or we're
5747 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01005748 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04005749 */
5750static void reg_set_min_max(struct bpf_reg_state *true_reg,
5751 struct bpf_reg_state *false_reg, u64 val,
Jiong Wang092ed092019-01-26 12:26:01 -05005752 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04005753{
Jiong Wanga72dafa2019-01-26 12:26:00 -05005754 s64 sval;
5755
Edward Creef1174f72017-08-07 15:26:19 +01005756 /* If the dst_reg is a pointer, we can't learn anything about its
5757 * variable offset from the compare (unless src_reg were a pointer into
5758 * the same object, but we don't bother with that.
5759 * Since false_reg and true_reg have the same type by construction, we
5760 * only need to check one of them for pointerness.
5761 */
5762 if (__is_pointer_value(false, false_reg))
5763 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02005764
Jiong Wang092ed092019-01-26 12:26:01 -05005765 val = is_jmp32 ? (u32)val : val;
5766 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005767
Josef Bacik48461132016-09-28 10:54:32 -04005768 switch (opcode) {
5769 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04005770 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005771 {
5772 struct bpf_reg_state *reg =
5773 opcode == BPF_JEQ ? true_reg : false_reg;
5774
5775 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
5776 * if it is true we know the value for sure. Likewise for
5777 * BPF_JNE.
Josef Bacik48461132016-09-28 10:54:32 -04005778 */
Jiong Wang092ed092019-01-26 12:26:01 -05005779 if (is_jmp32) {
5780 u64 old_v = reg->var_off.value;
5781 u64 hi_mask = ~0xffffffffULL;
5782
5783 reg->var_off.value = (old_v & hi_mask) | val;
5784 reg->var_off.mask &= hi_mask;
5785 } else {
5786 __mark_reg_known(reg, val);
5787 }
Josef Bacik48461132016-09-28 10:54:32 -04005788 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005789 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08005790 case BPF_JSET:
5791 false_reg->var_off = tnum_and(false_reg->var_off,
5792 tnum_const(~val));
5793 if (is_power_of_2(val))
5794 true_reg->var_off = tnum_or(true_reg->var_off,
5795 tnum_const(val));
5796 break;
Josef Bacik48461132016-09-28 10:54:32 -04005797 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005798 case BPF_JGT:
5799 {
Jann Horn604dca52020-03-30 18:03:23 +02005800 set_upper_bound(false_reg, val, is_jmp32, opcode == BPF_JGE);
5801 set_lower_bound(true_reg, val, is_jmp32, opcode == BPF_JGT);
Edward Creeb03c9f92017-08-07 15:26:36 +01005802 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005803 }
Josef Bacik48461132016-09-28 10:54:32 -04005804 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005805 case BPF_JSGT:
5806 {
5807 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
5808 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
5809
Jiong Wang092ed092019-01-26 12:26:01 -05005810 /* If the full s64 was not sign-extended from s32 then don't
5811 * deduct further info.
5812 */
5813 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5814 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005815 false_reg->smax_value = min(false_reg->smax_value, false_smax);
5816 true_reg->smin_value = max(true_reg->smin_value, true_smin);
Josef Bacik48461132016-09-28 10:54:32 -04005817 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005818 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005819 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005820 case BPF_JLT:
5821 {
Jann Horn604dca52020-03-30 18:03:23 +02005822 set_lower_bound(false_reg, val, is_jmp32, opcode == BPF_JLE);
5823 set_upper_bound(true_reg, val, is_jmp32, opcode == BPF_JLT);
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005824 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005825 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005826 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05005827 case BPF_JSLT:
5828 {
5829 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
5830 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
5831
Jiong Wang092ed092019-01-26 12:26:01 -05005832 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5833 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005834 false_reg->smin_value = max(false_reg->smin_value, false_smin);
5835 true_reg->smax_value = min(true_reg->smax_value, true_smax);
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02005836 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05005837 }
Josef Bacik48461132016-09-28 10:54:32 -04005838 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02005839 return;
Josef Bacik48461132016-09-28 10:54:32 -04005840 }
5841
Edward Creeb03c9f92017-08-07 15:26:36 +01005842 __reg_deduce_bounds(false_reg);
5843 __reg_deduce_bounds(true_reg);
5844 /* We might have learned some bits from the bounds. */
5845 __reg_bound_offset(false_reg);
5846 __reg_bound_offset(true_reg);
5847 /* Intersecting with the old var_off might have improved our bounds
5848 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5849 * then new var_off is (0; 0x7f...fc) which improves our umax.
5850 */
5851 __update_reg_bounds(false_reg);
5852 __update_reg_bounds(true_reg);
Josef Bacik48461132016-09-28 10:54:32 -04005853}
5854
Edward Creef1174f72017-08-07 15:26:19 +01005855/* Same as above, but for the case that dst_reg holds a constant and src_reg is
5856 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04005857 */
5858static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
5859 struct bpf_reg_state *false_reg, u64 val,
Jiong Wang092ed092019-01-26 12:26:01 -05005860 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04005861{
Jann Horn0fc31b12020-03-30 18:03:24 +02005862 /* How can we transform "a <op> b" into "b <op> a"? */
5863 static const u8 opcode_flip[16] = {
5864 /* these stay the same */
5865 [BPF_JEQ >> 4] = BPF_JEQ,
5866 [BPF_JNE >> 4] = BPF_JNE,
5867 [BPF_JSET >> 4] = BPF_JSET,
5868 /* these swap "lesser" and "greater" (L and G in the opcodes) */
5869 [BPF_JGE >> 4] = BPF_JLE,
5870 [BPF_JGT >> 4] = BPF_JLT,
5871 [BPF_JLE >> 4] = BPF_JGE,
5872 [BPF_JLT >> 4] = BPF_JGT,
5873 [BPF_JSGE >> 4] = BPF_JSLE,
5874 [BPF_JSGT >> 4] = BPF_JSLT,
5875 [BPF_JSLE >> 4] = BPF_JSGE,
5876 [BPF_JSLT >> 4] = BPF_JSGT
5877 };
5878 opcode = opcode_flip[opcode >> 4];
5879 /* This uses zero as "not present in table"; luckily the zero opcode,
5880 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01005881 */
Jann Horn0fc31b12020-03-30 18:03:24 +02005882 if (opcode)
5883 reg_set_min_max(true_reg, false_reg, val, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01005884}
5885
5886/* Regs are known to be equal, so intersect their min/max/var_off */
5887static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
5888 struct bpf_reg_state *dst_reg)
5889{
Edward Creeb03c9f92017-08-07 15:26:36 +01005890 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
5891 dst_reg->umin_value);
5892 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
5893 dst_reg->umax_value);
5894 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
5895 dst_reg->smin_value);
5896 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
5897 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01005898 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
5899 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01005900 /* We might have learned new bounds from the var_off. */
5901 __update_reg_bounds(src_reg);
5902 __update_reg_bounds(dst_reg);
5903 /* We might have learned something about the sign bit. */
5904 __reg_deduce_bounds(src_reg);
5905 __reg_deduce_bounds(dst_reg);
5906 /* We might have learned some bits from the bounds. */
5907 __reg_bound_offset(src_reg);
5908 __reg_bound_offset(dst_reg);
5909 /* Intersecting with the old var_off might have improved our bounds
5910 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5911 * then new var_off is (0; 0x7f...fc) which improves our umax.
5912 */
5913 __update_reg_bounds(src_reg);
5914 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01005915}
5916
5917static void reg_combine_min_max(struct bpf_reg_state *true_src,
5918 struct bpf_reg_state *true_dst,
5919 struct bpf_reg_state *false_src,
5920 struct bpf_reg_state *false_dst,
5921 u8 opcode)
5922{
5923 switch (opcode) {
5924 case BPF_JEQ:
5925 __reg_combine_min_max(true_src, true_dst);
5926 break;
5927 case BPF_JNE:
5928 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01005929 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02005930 }
Josef Bacik48461132016-09-28 10:54:32 -04005931}
5932
Joe Stringerfd978bf72018-10-02 13:35:35 -07005933static void mark_ptr_or_null_reg(struct bpf_func_state *state,
5934 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07005935 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02005936{
Joe Stringer840b9612018-10-02 13:35:32 -07005937 if (reg_type_may_be_null(reg->type) && reg->id == id) {
Edward Creef1174f72017-08-07 15:26:19 +01005938 /* Old offset (both fixed and variable parts) should
5939 * have been known-zero, because we don't allow pointer
5940 * arithmetic on pointers that might be NULL.
5941 */
Edward Creeb03c9f92017-08-07 15:26:36 +01005942 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
5943 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01005944 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01005945 __mark_reg_known_zero(reg);
5946 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01005947 }
5948 if (is_null) {
5949 reg->type = SCALAR_VALUE;
Joe Stringer840b9612018-10-02 13:35:32 -07005950 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
5951 if (reg->map_ptr->inner_map_meta) {
5952 reg->type = CONST_PTR_TO_MAP;
5953 reg->map_ptr = reg->map_ptr->inner_map_meta;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07005954 } else if (reg->map_ptr->map_type ==
5955 BPF_MAP_TYPE_XSKMAP) {
5956 reg->type = PTR_TO_XDP_SOCK;
Joe Stringer840b9612018-10-02 13:35:32 -07005957 } else {
5958 reg->type = PTR_TO_MAP_VALUE;
5959 }
Joe Stringerc64b7982018-10-02 13:35:33 -07005960 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
5961 reg->type = PTR_TO_SOCKET;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005962 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
5963 reg->type = PTR_TO_SOCK_COMMON;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005964 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
5965 reg->type = PTR_TO_TCP_SOCK;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07005966 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005967 if (is_null) {
5968 /* We don't need id and ref_obj_id from this point
5969 * onwards anymore, thus we should better reset it,
5970 * so that state pruning has chances to take effect.
5971 */
5972 reg->id = 0;
5973 reg->ref_obj_id = 0;
5974 } else if (!reg_may_point_to_spin_lock(reg)) {
5975 /* For not-NULL ptr, reg->ref_obj_id will be reset
5976 * in release_reg_references().
5977 *
5978 * reg->id is still used by spin_lock ptr. Other
5979 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07005980 */
5981 reg->id = 0;
5982 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02005983 }
5984}
5985
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02005986static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
5987 bool is_null)
5988{
5989 struct bpf_reg_state *reg;
5990 int i;
5991
5992 for (i = 0; i < MAX_BPF_REG; i++)
5993 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
5994
5995 bpf_for_each_spilled_reg(i, state, reg) {
5996 if (!reg)
5997 continue;
5998 mark_ptr_or_null_reg(state, reg, id, is_null);
5999 }
6000}
6001
Thomas Graf57a09bf2016-10-18 19:51:19 +02006002/* The logic is similar to find_good_pkt_pointers(), both could eventually
6003 * be folded together at some point.
6004 */
Joe Stringer840b9612018-10-02 13:35:32 -07006005static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
6006 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02006007{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006008 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006009 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006010 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01006011 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006012 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02006013
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006014 if (ref_obj_id && ref_obj_id == id && is_null)
6015 /* regs[regno] is in the " == NULL" branch.
6016 * No one could have freed the reference state before
6017 * doing the NULL check.
6018 */
6019 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07006020
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02006021 for (i = 0; i <= vstate->curframe; i++)
6022 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02006023}
6024
Daniel Borkmann5beca082017-11-01 23:58:10 +01006025static bool try_match_pkt_pointers(const struct bpf_insn *insn,
6026 struct bpf_reg_state *dst_reg,
6027 struct bpf_reg_state *src_reg,
6028 struct bpf_verifier_state *this_branch,
6029 struct bpf_verifier_state *other_branch)
6030{
6031 if (BPF_SRC(insn->code) != BPF_X)
6032 return false;
6033
Jiong Wang092ed092019-01-26 12:26:01 -05006034 /* Pointers are always 64-bit. */
6035 if (BPF_CLASS(insn->code) == BPF_JMP32)
6036 return false;
6037
Daniel Borkmann5beca082017-11-01 23:58:10 +01006038 switch (BPF_OP(insn->code)) {
6039 case BPF_JGT:
6040 if ((dst_reg->type == PTR_TO_PACKET &&
6041 src_reg->type == PTR_TO_PACKET_END) ||
6042 (dst_reg->type == PTR_TO_PACKET_META &&
6043 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6044 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
6045 find_good_pkt_pointers(this_branch, dst_reg,
6046 dst_reg->type, false);
6047 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6048 src_reg->type == PTR_TO_PACKET) ||
6049 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6050 src_reg->type == PTR_TO_PACKET_META)) {
6051 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
6052 find_good_pkt_pointers(other_branch, src_reg,
6053 src_reg->type, true);
6054 } else {
6055 return false;
6056 }
6057 break;
6058 case BPF_JLT:
6059 if ((dst_reg->type == PTR_TO_PACKET &&
6060 src_reg->type == PTR_TO_PACKET_END) ||
6061 (dst_reg->type == PTR_TO_PACKET_META &&
6062 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6063 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
6064 find_good_pkt_pointers(other_branch, dst_reg,
6065 dst_reg->type, true);
6066 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6067 src_reg->type == PTR_TO_PACKET) ||
6068 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6069 src_reg->type == PTR_TO_PACKET_META)) {
6070 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
6071 find_good_pkt_pointers(this_branch, src_reg,
6072 src_reg->type, false);
6073 } else {
6074 return false;
6075 }
6076 break;
6077 case BPF_JGE:
6078 if ((dst_reg->type == PTR_TO_PACKET &&
6079 src_reg->type == PTR_TO_PACKET_END) ||
6080 (dst_reg->type == PTR_TO_PACKET_META &&
6081 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6082 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
6083 find_good_pkt_pointers(this_branch, dst_reg,
6084 dst_reg->type, true);
6085 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6086 src_reg->type == PTR_TO_PACKET) ||
6087 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6088 src_reg->type == PTR_TO_PACKET_META)) {
6089 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
6090 find_good_pkt_pointers(other_branch, src_reg,
6091 src_reg->type, false);
6092 } else {
6093 return false;
6094 }
6095 break;
6096 case BPF_JLE:
6097 if ((dst_reg->type == PTR_TO_PACKET &&
6098 src_reg->type == PTR_TO_PACKET_END) ||
6099 (dst_reg->type == PTR_TO_PACKET_META &&
6100 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6101 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
6102 find_good_pkt_pointers(other_branch, dst_reg,
6103 dst_reg->type, false);
6104 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6105 src_reg->type == PTR_TO_PACKET) ||
6106 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6107 src_reg->type == PTR_TO_PACKET_META)) {
6108 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
6109 find_good_pkt_pointers(this_branch, src_reg,
6110 src_reg->type, true);
6111 } else {
6112 return false;
6113 }
6114 break;
6115 default:
6116 return false;
6117 }
6118
6119 return true;
6120}
6121
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006122static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006123 struct bpf_insn *insn, int *insn_idx)
6124{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006125 struct bpf_verifier_state *this_branch = env->cur_state;
6126 struct bpf_verifier_state *other_branch;
6127 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006128 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006129 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05006130 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006131 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006132 int err;
6133
Jiong Wang092ed092019-01-26 12:26:01 -05006134 /* Only conditional jumps are expected to reach here. */
6135 if (opcode == BPF_JA || opcode > BPF_JSLE) {
6136 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006137 return -EINVAL;
6138 }
6139
6140 if (BPF_SRC(insn->code) == BPF_X) {
6141 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05006142 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006143 return -EINVAL;
6144 }
6145
6146 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006147 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006148 if (err)
6149 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006150
6151 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006152 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006153 insn->src_reg);
6154 return -EACCES;
6155 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006156 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006157 } else {
6158 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05006159 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006160 return -EINVAL;
6161 }
6162 }
6163
6164 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01006165 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006166 if (err)
6167 return err;
6168
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006169 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05006170 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006171
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006172 if (BPF_SRC(insn->code) == BPF_K)
6173 pred = is_branch_taken(dst_reg, insn->imm,
6174 opcode, is_jmp32);
6175 else if (src_reg->type == SCALAR_VALUE &&
6176 tnum_is_const(src_reg->var_off))
6177 pred = is_branch_taken(dst_reg, src_reg->var_off.value,
6178 opcode, is_jmp32);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006179 if (pred >= 0) {
6180 err = mark_chain_precision(env, insn->dst_reg);
6181 if (BPF_SRC(insn->code) == BPF_X && !err)
6182 err = mark_chain_precision(env, insn->src_reg);
6183 if (err)
6184 return err;
6185 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07006186 if (pred == 1) {
6187 /* only follow the goto, ignore fall-through */
6188 *insn_idx += insn->off;
6189 return 0;
6190 } else if (pred == 0) {
6191 /* only follow fall-through branch, since
6192 * that's where the program will go
6193 */
6194 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006195 }
6196
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006197 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
6198 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006199 if (!other_branch)
6200 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006201 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006202
Josef Bacik48461132016-09-28 10:54:32 -04006203 /* detect if we are comparing against a constant value so we can adjust
6204 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01006205 * this is only legit if both are scalars (or pointers to the same
6206 * object, I suppose, but we don't support that right now), because
6207 * otherwise the different base pointers mean the offsets aren't
6208 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04006209 */
6210 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05006211 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
6212 struct bpf_reg_state lo_reg0 = *dst_reg;
6213 struct bpf_reg_state lo_reg1 = *src_reg;
6214 struct bpf_reg_state *src_lo, *dst_lo;
6215
6216 dst_lo = &lo_reg0;
6217 src_lo = &lo_reg1;
6218 coerce_reg_to_size(dst_lo, 4);
6219 coerce_reg_to_size(src_lo, 4);
6220
Edward Creef1174f72017-08-07 15:26:19 +01006221 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05006222 src_reg->type == SCALAR_VALUE) {
6223 if (tnum_is_const(src_reg->var_off) ||
6224 (is_jmp32 && tnum_is_const(src_lo->var_off)))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006225 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05006226 dst_reg,
6227 is_jmp32
6228 ? src_lo->var_off.value
6229 : src_reg->var_off.value,
6230 opcode, is_jmp32);
6231 else if (tnum_is_const(dst_reg->var_off) ||
6232 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006233 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05006234 src_reg,
6235 is_jmp32
6236 ? dst_lo->var_off.value
6237 : dst_reg->var_off.value,
6238 opcode, is_jmp32);
6239 else if (!is_jmp32 &&
6240 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01006241 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006242 reg_combine_min_max(&other_branch_regs[insn->src_reg],
6243 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05006244 src_reg, dst_reg, opcode);
Edward Creef1174f72017-08-07 15:26:19 +01006245 }
6246 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006247 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05006248 dst_reg, insn->imm, opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04006249 }
6250
Jiong Wang092ed092019-01-26 12:26:01 -05006251 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
6252 * NOTE: these optimizations below are related with pointer comparison
6253 * which will never be JMP32.
6254 */
6255 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07006256 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07006257 reg_type_may_be_null(dst_reg->type)) {
6258 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02006259 * safe or unknown depending R == 0 or R != 0 conditional.
6260 */
Joe Stringer840b9612018-10-02 13:35:32 -07006261 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
6262 opcode == BPF_JNE);
6263 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
6264 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01006265 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
6266 this_branch, other_branch) &&
6267 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006268 verbose(env, "R%d pointer comparison prohibited\n",
6269 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07006270 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006271 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07006272 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006273 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006274 return 0;
6275}
6276
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006277/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006278static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006279{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02006280 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006281 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02006282 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006283 int err;
6284
6285 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006286 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006287 return -EINVAL;
6288 }
6289 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006290 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006291 return -EINVAL;
6292 }
6293
Edward Creedc503a82017-08-15 20:34:35 +01006294 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006295 if (err)
6296 return err;
6297
Jakub Kicinski6b173872016-09-21 11:43:59 +01006298 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01006299 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
6300
Edward Creef1174f72017-08-07 15:26:19 +01006301 regs[insn->dst_reg].type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01006302 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006303 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01006304 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006305
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02006306 map = env->used_maps[aux->map_index];
6307 mark_reg_known_zero(env, regs, insn->dst_reg);
6308 regs[insn->dst_reg].map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006309
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02006310 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
6311 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
6312 regs[insn->dst_reg].off = aux->map_off;
6313 if (map_value_has_spin_lock(map))
6314 regs[insn->dst_reg].id = ++env->id_gen;
6315 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
6316 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
6317 } else {
6318 verbose(env, "bpf verifier is misconfigured\n");
6319 return -EINVAL;
6320 }
6321
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006322 return 0;
6323}
6324
Daniel Borkmann96be4322015-03-01 12:31:46 +01006325static bool may_access_skb(enum bpf_prog_type type)
6326{
6327 switch (type) {
6328 case BPF_PROG_TYPE_SOCKET_FILTER:
6329 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01006330 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01006331 return true;
6332 default:
6333 return false;
6334 }
6335}
6336
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006337/* verify safety of LD_ABS|LD_IND instructions:
6338 * - they can only appear in the programs where ctx == skb
6339 * - since they are wrappers of function calls, they scratch R1-R5 registers,
6340 * preserve R6-R9, and store return value into R0
6341 *
6342 * Implicit input:
6343 * ctx == skb == R6 == CTX
6344 *
6345 * Explicit input:
6346 * SRC == any register
6347 * IMM == 32-bit immediate
6348 *
6349 * Output:
6350 * R0 - 8/16/32-bit skb data converted to cpu endianness
6351 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006352static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006353{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006354 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01006355 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006356 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006357 int i, err;
6358
Daniel Borkmann24701ec2015-03-01 12:31:47 +01006359 if (!may_access_skb(env->prog->type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006360 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006361 return -EINVAL;
6362 }
6363
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02006364 if (!env->ops->gen_ld_abs) {
6365 verbose(env, "bpf verifier is misconfigured\n");
6366 return -EINVAL;
6367 }
6368
Jiong Wangf910cef2018-05-02 16:17:17 -04006369 if (env->subprog_cnt > 1) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006370 /* when program has LD_ABS insn JITs and interpreter assume
6371 * that r1 == ctx == skb which is not the case for callees
6372 * that can have arbitrary arguments. It's problematic
6373 * for main prog as well since JITs would need to analyze
6374 * all functions in order to make proper register save/restore
6375 * decisions in the main prog. Hence disallow LD_ABS with calls
6376 */
6377 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
6378 return -EINVAL;
6379 }
6380
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006381 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07006382 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006383 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006384 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006385 return -EINVAL;
6386 }
6387
6388 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01006389 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006390 if (err)
6391 return err;
6392
Joe Stringerfd978bf72018-10-02 13:35:35 -07006393 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
6394 * gen_ld_abs() may terminate the program at runtime, leading to
6395 * reference leak.
6396 */
6397 err = check_reference_leak(env);
6398 if (err) {
6399 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
6400 return err;
6401 }
6402
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08006403 if (env->cur_state->active_spin_lock) {
6404 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
6405 return -EINVAL;
6406 }
6407
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01006408 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006409 verbose(env,
6410 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006411 return -EINVAL;
6412 }
6413
6414 if (mode == BPF_IND) {
6415 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01006416 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006417 if (err)
6418 return err;
6419 }
6420
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01006421 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
6422 if (err < 0)
6423 return err;
6424
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006425 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01006426 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006427 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01006428 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6429 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006430
6431 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01006432 * the value fetched from the packet.
6433 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006434 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006435 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01006436 /* ld_abs load up to 32-bit skb data. */
6437 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08006438 return 0;
6439}
6440
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006441static int check_return_code(struct bpf_verifier_env *env)
6442{
brakmo5cf1e912019-05-28 16:59:36 -07006443 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08006444 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006445 struct bpf_reg_state *reg;
6446 struct tnum range = tnum_range(0, 1);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08006447 int err;
6448
KP Singh9e4e01d2020-03-29 01:43:52 +01006449 /* LSM and struct_ops func-ptr's return type could be "void" */
6450 if ((env->prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
6451 env->prog->type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08006452 !prog->aux->attach_func_proto->type)
6453 return 0;
6454
6455 /* eBPF calling convetion is such that R0 is used
6456 * to return the value from eBPF program.
6457 * Make sure that it's readable at this time
6458 * of bpf_exit, which means that program wrote
6459 * something into it earlier
6460 */
6461 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
6462 if (err)
6463 return err;
6464
6465 if (is_pointer_value(env, BPF_REG_0)) {
6466 verbose(env, "R0 leaks addr as return value\n");
6467 return -EACCES;
6468 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006469
6470 switch (env->prog->type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02006471 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
6472 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
6473 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
6474 range = tnum_range(1, 1);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05006475 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006476 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07006477 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
6478 range = tnum_range(0, 3);
6479 enforce_attach_type_range = tnum_range(2, 3);
6480 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05006481 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006482 case BPF_PROG_TYPE_CGROUP_SOCK:
6483 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05006484 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08006485 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07006486 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006487 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07006488 case BPF_PROG_TYPE_RAW_TRACEPOINT:
6489 if (!env->prog->aux->attach_btf_id)
6490 return 0;
6491 range = tnum_const(0);
6492 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006493 default:
6494 return 0;
6495 }
6496
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006497 reg = cur_regs(env) + BPF_REG_0;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006498 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006499 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006500 reg_type_str[reg->type]);
6501 return -EINVAL;
6502 }
6503
6504 if (!tnum_in(range, reg->var_off)) {
brakmo5cf1e912019-05-28 16:59:36 -07006505 char tn_buf[48];
6506
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006507 verbose(env, "At program exit the register R0 ");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006508 if (!tnum_is_unknown(reg->var_off)) {
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006509 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006510 verbose(env, "has value %s", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006511 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006512 verbose(env, "has unknown scalar value");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006513 }
brakmo5cf1e912019-05-28 16:59:36 -07006514 tnum_strn(tn_buf, sizeof(tn_buf), range);
Daniel Borkmann983695f2019-06-07 01:48:57 +02006515 verbose(env, " should have been in %s\n", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006516 return -EINVAL;
6517 }
brakmo5cf1e912019-05-28 16:59:36 -07006518
6519 if (!tnum_is_unknown(enforce_attach_type_range) &&
6520 tnum_in(enforce_attach_type_range, reg->var_off))
6521 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07006522 return 0;
6523}
6524
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006525/* non-recursive DFS pseudo code
6526 * 1 procedure DFS-iterative(G,v):
6527 * 2 label v as discovered
6528 * 3 let S be a stack
6529 * 4 S.push(v)
6530 * 5 while S is not empty
6531 * 6 t <- S.pop()
6532 * 7 if t is what we're looking for:
6533 * 8 return t
6534 * 9 for all edges e in G.adjacentEdges(t) do
6535 * 10 if edge e is already labelled
6536 * 11 continue with the next edge
6537 * 12 w <- G.adjacentVertex(t,e)
6538 * 13 if vertex w is not discovered and not explored
6539 * 14 label e as tree-edge
6540 * 15 label w as discovered
6541 * 16 S.push(w)
6542 * 17 continue at 5
6543 * 18 else if vertex w is discovered
6544 * 19 label e as back-edge
6545 * 20 else
6546 * 21 // vertex w is explored
6547 * 22 label e as forward- or cross-edge
6548 * 23 label t as explored
6549 * 24 S.pop()
6550 *
6551 * convention:
6552 * 0x10 - discovered
6553 * 0x11 - discovered and fall-through edge labelled
6554 * 0x12 - discovered and fall-through and branch edges labelled
6555 * 0x20 - explored
6556 */
6557
6558enum {
6559 DISCOVERED = 0x10,
6560 EXPLORED = 0x20,
6561 FALLTHROUGH = 1,
6562 BRANCH = 2,
6563};
6564
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07006565static u32 state_htab_size(struct bpf_verifier_env *env)
6566{
6567 return env->prog->len;
6568}
6569
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006570static struct bpf_verifier_state_list **explored_state(
6571 struct bpf_verifier_env *env,
6572 int idx)
6573{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07006574 struct bpf_verifier_state *cur = env->cur_state;
6575 struct bpf_func_state *state = cur->frame[cur->curframe];
6576
6577 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006578}
6579
6580static void init_explored_state(struct bpf_verifier_env *env, int idx)
6581{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07006582 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006583}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07006584
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006585/* t, w, e - match pseudo-code above:
6586 * t - index of current instruction
6587 * w - next instruction
6588 * e - edge
6589 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07006590static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
6591 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006592{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006593 int *insn_stack = env->cfg.insn_stack;
6594 int *insn_state = env->cfg.insn_state;
6595
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006596 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
6597 return 0;
6598
6599 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
6600 return 0;
6601
6602 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08006603 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006604 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006605 return -EINVAL;
6606 }
6607
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07006608 if (e == BRANCH)
6609 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006610 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07006611
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006612 if (insn_state[w] == 0) {
6613 /* tree-edge */
6614 insn_state[t] = DISCOVERED | e;
6615 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006616 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006617 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006618 insn_stack[env->cfg.cur_stack++] = w;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006619 return 1;
6620 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07006621 if (loop_ok && env->allow_ptr_leaks)
6622 return 0;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08006623 verbose_linfo(env, t, "%d: ", t);
6624 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006625 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006626 return -EINVAL;
6627 } else if (insn_state[w] == EXPLORED) {
6628 /* forward- or cross-edge */
6629 insn_state[t] = DISCOVERED | e;
6630 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006631 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006632 return -EFAULT;
6633 }
6634 return 0;
6635}
6636
6637/* non-recursive depth-first-search to detect loops in BPF program
6638 * loop == back-edge in directed graph
6639 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01006640static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006641{
6642 struct bpf_insn *insns = env->prog->insnsi;
6643 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006644 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006645 int ret = 0;
6646 int i, t;
6647
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006648 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006649 if (!insn_state)
6650 return -ENOMEM;
6651
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006652 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006653 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07006654 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006655 return -ENOMEM;
6656 }
6657
6658 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
6659 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006660 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006661
6662peek_stack:
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006663 if (env->cfg.cur_stack == 0)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006664 goto check_state;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006665 t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006666
Jiong Wang092ed092019-01-26 12:26:01 -05006667 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
6668 BPF_CLASS(insns[t].code) == BPF_JMP32) {
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006669 u8 opcode = BPF_OP(insns[t].code);
6670
6671 if (opcode == BPF_EXIT) {
6672 goto mark_explored;
6673 } else if (opcode == BPF_CALL) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07006674 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006675 if (ret == 1)
6676 goto peek_stack;
6677 else if (ret < 0)
6678 goto err_free;
Daniel Borkmann07016152016-04-05 22:33:17 +02006679 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006680 init_explored_state(env, t + 1);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08006681 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006682 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07006683 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
6684 env, false);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08006685 if (ret == 1)
6686 goto peek_stack;
6687 else if (ret < 0)
6688 goto err_free;
6689 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006690 } else if (opcode == BPF_JA) {
6691 if (BPF_SRC(insns[t].code) != BPF_K) {
6692 ret = -EINVAL;
6693 goto err_free;
6694 }
6695 /* unconditional jump with single edge */
6696 ret = push_insn(t, t + insns[t].off + 1,
Alexei Starovoitov25897262019-06-15 12:12:20 -07006697 FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006698 if (ret == 1)
6699 goto peek_stack;
6700 else if (ret < 0)
6701 goto err_free;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006702 /* unconditional jmp is not a good pruning point,
6703 * but it's marked, since backtracking needs
6704 * to record jmp history in is_state_visited().
6705 */
6706 init_explored_state(env, t + insns[t].off + 1);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07006707 /* tell verifier to check for equivalent states
6708 * after every call and jump
6709 */
Alexei Starovoitovc3de6312015-04-14 15:57:13 -07006710 if (t + 1 < insn_cnt)
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006711 init_explored_state(env, t + 1);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006712 } else {
6713 /* conditional jump with two edges */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07006714 init_explored_state(env, t);
Alexei Starovoitov25897262019-06-15 12:12:20 -07006715 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006716 if (ret == 1)
6717 goto peek_stack;
6718 else if (ret < 0)
6719 goto err_free;
6720
Alexei Starovoitov25897262019-06-15 12:12:20 -07006721 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006722 if (ret == 1)
6723 goto peek_stack;
6724 else if (ret < 0)
6725 goto err_free;
6726 }
6727 } else {
6728 /* all other non-branch instructions with single
6729 * fall-through edge
6730 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07006731 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006732 if (ret == 1)
6733 goto peek_stack;
6734 else if (ret < 0)
6735 goto err_free;
6736 }
6737
6738mark_explored:
6739 insn_state[t] = EXPLORED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006740 if (env->cfg.cur_stack-- <= 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006741 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006742 ret = -EFAULT;
6743 goto err_free;
6744 }
6745 goto peek_stack;
6746
6747check_state:
6748 for (i = 0; i < insn_cnt; i++) {
6749 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006750 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006751 ret = -EINVAL;
6752 goto err_free;
6753 }
6754 }
6755 ret = 0; /* cfg looks good */
6756
6757err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07006758 kvfree(insn_state);
6759 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07006760 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07006761 return ret;
6762}
6763
Yonghong Song838e9692018-11-19 15:29:11 -08006764/* The minimum supported BTF func info size */
6765#define MIN_BPF_FUNCINFO_SIZE 8
6766#define MAX_FUNCINFO_REC_SIZE 252
6767
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006768static int check_btf_func(struct bpf_verifier_env *env,
6769 const union bpf_attr *attr,
6770 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08006771{
Peter Oskolkovd0b28182019-01-16 10:43:01 -08006772 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08006773 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006774 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006775 struct bpf_func_info_aux *info_aux = NULL;
Yonghong Song838e9692018-11-19 15:29:11 -08006776 const struct btf_type *type;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006777 struct bpf_prog *prog;
6778 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08006779 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08006780 u32 prev_offset = 0;
Yonghong Song838e9692018-11-19 15:29:11 -08006781 int ret = 0;
6782
6783 nfuncs = attr->func_info_cnt;
6784 if (!nfuncs)
6785 return 0;
6786
6787 if (nfuncs != env->subprog_cnt) {
6788 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
6789 return -EINVAL;
6790 }
6791
6792 urec_size = attr->func_info_rec_size;
6793 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
6794 urec_size > MAX_FUNCINFO_REC_SIZE ||
6795 urec_size % sizeof(u32)) {
6796 verbose(env, "invalid func info rec size %u\n", urec_size);
6797 return -EINVAL;
6798 }
6799
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006800 prog = env->prog;
6801 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08006802
6803 urecord = u64_to_user_ptr(attr->func_info);
6804 min_size = min_t(u32, krec_size, urec_size);
6805
Yonghong Songba64e7d2018-11-24 23:20:44 -08006806 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006807 if (!krecord)
6808 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006809 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
6810 if (!info_aux)
6811 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08006812
Yonghong Song838e9692018-11-19 15:29:11 -08006813 for (i = 0; i < nfuncs; i++) {
6814 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
6815 if (ret) {
6816 if (ret == -E2BIG) {
6817 verbose(env, "nonzero tailing record in func info");
6818 /* set the size kernel expects so loader can zero
6819 * out the rest of the record.
6820 */
6821 if (put_user(min_size, &uattr->func_info_rec_size))
6822 ret = -EFAULT;
6823 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006824 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006825 }
6826
Yonghong Songba64e7d2018-11-24 23:20:44 -08006827 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08006828 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006829 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006830 }
6831
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006832 /* check insn_off */
Yonghong Song838e9692018-11-19 15:29:11 -08006833 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006834 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08006835 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006836 "nonzero insn_off %u for the first func info record",
6837 krecord[i].insn_off);
Yonghong Song838e9692018-11-19 15:29:11 -08006838 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006839 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006840 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006841 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08006842 verbose(env,
6843 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006844 krecord[i].insn_off, prev_offset);
Yonghong Song838e9692018-11-19 15:29:11 -08006845 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006846 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006847 }
6848
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006849 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08006850 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
6851 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006852 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006853 }
6854
6855 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08006856 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08006857 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08006858 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08006859 krecord[i].type_id);
Yonghong Song838e9692018-11-19 15:29:11 -08006860 ret = -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006861 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08006862 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08006863 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08006864 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08006865 urecord += urec_size;
6866 }
6867
Yonghong Songba64e7d2018-11-24 23:20:44 -08006868 prog->aux->func_info = krecord;
6869 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006870 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08006871 return 0;
6872
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006873err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08006874 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006875 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08006876 return ret;
6877}
6878
Yonghong Songba64e7d2018-11-24 23:20:44 -08006879static void adjust_btf_func(struct bpf_verifier_env *env)
6880{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006881 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08006882 int i;
6883
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006884 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08006885 return;
6886
6887 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08006888 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08006889}
6890
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006891#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
6892 sizeof(((struct bpf_line_info *)(0))->line_col))
6893#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
6894
6895static int check_btf_line(struct bpf_verifier_env *env,
6896 const union bpf_attr *attr,
6897 union bpf_attr __user *uattr)
6898{
6899 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
6900 struct bpf_subprog_info *sub;
6901 struct bpf_line_info *linfo;
6902 struct bpf_prog *prog;
6903 const struct btf *btf;
6904 void __user *ulinfo;
6905 int err;
6906
6907 nr_linfo = attr->line_info_cnt;
6908 if (!nr_linfo)
6909 return 0;
6910
6911 rec_size = attr->line_info_rec_size;
6912 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
6913 rec_size > MAX_LINEINFO_REC_SIZE ||
6914 rec_size & (sizeof(u32) - 1))
6915 return -EINVAL;
6916
6917 /* Need to zero it in case the userspace may
6918 * pass in a smaller bpf_line_info object.
6919 */
6920 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
6921 GFP_KERNEL | __GFP_NOWARN);
6922 if (!linfo)
6923 return -ENOMEM;
6924
6925 prog = env->prog;
6926 btf = prog->aux->btf;
6927
6928 s = 0;
6929 sub = env->subprog_info;
6930 ulinfo = u64_to_user_ptr(attr->line_info);
6931 expected_size = sizeof(struct bpf_line_info);
6932 ncopy = min_t(u32, expected_size, rec_size);
6933 for (i = 0; i < nr_linfo; i++) {
6934 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
6935 if (err) {
6936 if (err == -E2BIG) {
6937 verbose(env, "nonzero tailing record in line_info");
6938 if (put_user(expected_size,
6939 &uattr->line_info_rec_size))
6940 err = -EFAULT;
6941 }
6942 goto err_free;
6943 }
6944
6945 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
6946 err = -EFAULT;
6947 goto err_free;
6948 }
6949
6950 /*
6951 * Check insn_off to ensure
6952 * 1) strictly increasing AND
6953 * 2) bounded by prog->len
6954 *
6955 * The linfo[0].insn_off == 0 check logically falls into
6956 * the later "missing bpf_line_info for func..." case
6957 * because the first linfo[0].insn_off must be the
6958 * first sub also and the first sub must have
6959 * subprog_info[0].start == 0.
6960 */
6961 if ((i && linfo[i].insn_off <= prev_offset) ||
6962 linfo[i].insn_off >= prog->len) {
6963 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
6964 i, linfo[i].insn_off, prev_offset,
6965 prog->len);
6966 err = -EINVAL;
6967 goto err_free;
6968 }
6969
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08006970 if (!prog->insnsi[linfo[i].insn_off].code) {
6971 verbose(env,
6972 "Invalid insn code at line_info[%u].insn_off\n",
6973 i);
6974 err = -EINVAL;
6975 goto err_free;
6976 }
6977
Martin KaFai Lau23127b32018-12-13 10:41:46 -08006978 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
6979 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08006980 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
6981 err = -EINVAL;
6982 goto err_free;
6983 }
6984
6985 if (s != env->subprog_cnt) {
6986 if (linfo[i].insn_off == sub[s].start) {
6987 sub[s].linfo_idx = i;
6988 s++;
6989 } else if (sub[s].start < linfo[i].insn_off) {
6990 verbose(env, "missing bpf_line_info for func#%u\n", s);
6991 err = -EINVAL;
6992 goto err_free;
6993 }
6994 }
6995
6996 prev_offset = linfo[i].insn_off;
6997 ulinfo += rec_size;
6998 }
6999
7000 if (s != env->subprog_cnt) {
7001 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
7002 env->subprog_cnt - s, s);
7003 err = -EINVAL;
7004 goto err_free;
7005 }
7006
7007 prog->aux->linfo = linfo;
7008 prog->aux->nr_linfo = nr_linfo;
7009
7010 return 0;
7011
7012err_free:
7013 kvfree(linfo);
7014 return err;
7015}
7016
7017static int check_btf_info(struct bpf_verifier_env *env,
7018 const union bpf_attr *attr,
7019 union bpf_attr __user *uattr)
7020{
7021 struct btf *btf;
7022 int err;
7023
7024 if (!attr->func_info_cnt && !attr->line_info_cnt)
7025 return 0;
7026
7027 btf = btf_get_by_fd(attr->prog_btf_fd);
7028 if (IS_ERR(btf))
7029 return PTR_ERR(btf);
7030 env->prog->aux->btf = btf;
7031
7032 err = check_btf_func(env, attr, uattr);
7033 if (err)
7034 return err;
7035
7036 err = check_btf_line(env, attr, uattr);
7037 if (err)
7038 return err;
7039
7040 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07007041}
7042
Edward Creef1174f72017-08-07 15:26:19 +01007043/* check %cur's range satisfies %old's */
7044static bool range_within(struct bpf_reg_state *old,
7045 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007046{
Edward Creeb03c9f92017-08-07 15:26:36 +01007047 return old->umin_value <= cur->umin_value &&
7048 old->umax_value >= cur->umax_value &&
7049 old->smin_value <= cur->smin_value &&
7050 old->smax_value >= cur->smax_value;
Edward Creef1174f72017-08-07 15:26:19 +01007051}
7052
7053/* Maximum number of register states that can exist at once */
7054#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
7055struct idpair {
7056 u32 old;
7057 u32 cur;
7058};
7059
7060/* If in the old state two registers had the same id, then they need to have
7061 * the same id in the new state as well. But that id could be different from
7062 * the old state, so we need to track the mapping from old to new ids.
7063 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
7064 * regs with old id 5 must also have new id 9 for the new state to be safe. But
7065 * regs with a different old id could still have new id 9, we don't care about
7066 * that.
7067 * So we look through our idmap to see if this old id has been seen before. If
7068 * so, we require the new id to match; otherwise, we add the id pair to the map.
7069 */
7070static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
7071{
7072 unsigned int i;
7073
7074 for (i = 0; i < ID_MAP_SIZE; i++) {
7075 if (!idmap[i].old) {
7076 /* Reached an empty slot; haven't seen this id before */
7077 idmap[i].old = old_id;
7078 idmap[i].cur = cur_id;
7079 return true;
7080 }
7081 if (idmap[i].old == old_id)
7082 return idmap[i].cur == cur_id;
7083 }
7084 /* We ran out of idmap slots, which should be impossible */
7085 WARN_ON_ONCE(1);
7086 return false;
7087}
7088
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007089static void clean_func_state(struct bpf_verifier_env *env,
7090 struct bpf_func_state *st)
7091{
7092 enum bpf_reg_liveness live;
7093 int i, j;
7094
7095 for (i = 0; i < BPF_REG_FP; i++) {
7096 live = st->regs[i].live;
7097 /* liveness must not touch this register anymore */
7098 st->regs[i].live |= REG_LIVE_DONE;
7099 if (!(live & REG_LIVE_READ))
7100 /* since the register is unused, clear its state
7101 * to make further comparison simpler
7102 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01007103 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007104 }
7105
7106 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
7107 live = st->stack[i].spilled_ptr.live;
7108 /* liveness must not touch this stack slot anymore */
7109 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
7110 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01007111 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007112 for (j = 0; j < BPF_REG_SIZE; j++)
7113 st->stack[i].slot_type[j] = STACK_INVALID;
7114 }
7115 }
7116}
7117
7118static void clean_verifier_state(struct bpf_verifier_env *env,
7119 struct bpf_verifier_state *st)
7120{
7121 int i;
7122
7123 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
7124 /* all regs in this state in all frames were already marked */
7125 return;
7126
7127 for (i = 0; i <= st->curframe; i++)
7128 clean_func_state(env, st->frame[i]);
7129}
7130
7131/* the parentage chains form a tree.
7132 * the verifier states are added to state lists at given insn and
7133 * pushed into state stack for future exploration.
7134 * when the verifier reaches bpf_exit insn some of the verifer states
7135 * stored in the state lists have their final liveness state already,
7136 * but a lot of states will get revised from liveness point of view when
7137 * the verifier explores other branches.
7138 * Example:
7139 * 1: r0 = 1
7140 * 2: if r1 == 100 goto pc+1
7141 * 3: r0 = 2
7142 * 4: exit
7143 * when the verifier reaches exit insn the register r0 in the state list of
7144 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
7145 * of insn 2 and goes exploring further. At the insn 4 it will walk the
7146 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
7147 *
7148 * Since the verifier pushes the branch states as it sees them while exploring
7149 * the program the condition of walking the branch instruction for the second
7150 * time means that all states below this branch were already explored and
7151 * their final liveness markes are already propagated.
7152 * Hence when the verifier completes the search of state list in is_state_visited()
7153 * we can call this clean_live_states() function to mark all liveness states
7154 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
7155 * will not be used.
7156 * This function also clears the registers and stack for states that !READ
7157 * to simplify state merging.
7158 *
7159 * Important note here that walking the same branch instruction in the callee
7160 * doesn't meant that the states are DONE. The verifier has to compare
7161 * the callsites
7162 */
7163static void clean_live_states(struct bpf_verifier_env *env, int insn,
7164 struct bpf_verifier_state *cur)
7165{
7166 struct bpf_verifier_state_list *sl;
7167 int i;
7168
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007169 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007170 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07007171 if (sl->state.branches)
7172 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007173 if (sl->state.insn_idx != insn ||
7174 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007175 goto next;
7176 for (i = 0; i <= cur->curframe; i++)
7177 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
7178 goto next;
7179 clean_verifier_state(env, &sl->state);
7180next:
7181 sl = sl->next;
7182 }
7183}
7184
Edward Creef1174f72017-08-07 15:26:19 +01007185/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01007186static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7187 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01007188{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007189 bool equal;
7190
Edward Creedc503a82017-08-15 20:34:35 +01007191 if (!(rold->live & REG_LIVE_READ))
7192 /* explored state didn't use this */
7193 return true;
7194
Edward Cree679c7822018-08-22 20:02:19 +01007195 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007196
7197 if (rold->type == PTR_TO_STACK)
7198 /* two stack pointers are equal only if they're pointing to
7199 * the same stack frame, since fp-8 in foo != fp-8 in bar
7200 */
7201 return equal && rold->frameno == rcur->frameno;
7202
7203 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01007204 return true;
7205
7206 if (rold->type == NOT_INIT)
7207 /* explored state can't have used this */
7208 return true;
7209 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007210 return false;
Edward Creef1174f72017-08-07 15:26:19 +01007211 switch (rold->type) {
7212 case SCALAR_VALUE:
7213 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007214 if (!rold->precise && !rcur->precise)
7215 return true;
Edward Creef1174f72017-08-07 15:26:19 +01007216 /* new val must satisfy old val knowledge */
7217 return range_within(rold, rcur) &&
7218 tnum_in(rold->var_off, rcur->var_off);
7219 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08007220 /* We're trying to use a pointer in place of a scalar.
7221 * Even if the scalar was unbounded, this could lead to
7222 * pointer leaks because scalars are allowed to leak
7223 * while pointers are not. We could make this safe in
7224 * special cases if root is calling us, but it's
7225 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01007226 */
Jann Horn179d1c52017-12-18 20:11:59 -08007227 return false;
Edward Creef1174f72017-08-07 15:26:19 +01007228 }
7229 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01007230 /* If the new min/max/var_off satisfy the old ones and
7231 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08007232 * 'id' is not compared, since it's only used for maps with
7233 * bpf_spin_lock inside map element and in such cases if
7234 * the rest of the prog is valid for one map element then
7235 * it's valid for all map elements regardless of the key
7236 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01007237 */
7238 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
7239 range_within(rold, rcur) &&
7240 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01007241 case PTR_TO_MAP_VALUE_OR_NULL:
7242 /* a PTR_TO_MAP_VALUE could be safe to use as a
7243 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
7244 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
7245 * checked, doing so could have affected others with the same
7246 * id, and we can't check for that because we lost the id when
7247 * we converted to a PTR_TO_MAP_VALUE.
7248 */
7249 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
7250 return false;
7251 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
7252 return false;
7253 /* Check our ids match any regs they're supposed to */
7254 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007255 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01007256 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007257 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01007258 return false;
7259 /* We must have at least as much range as the old ptr
7260 * did, so that any accesses which were safe before are
7261 * still safe. This is true even if old range < old off,
7262 * since someone could have accessed through (ptr - k), or
7263 * even done ptr -= k in a register, to get a safe access.
7264 */
7265 if (rold->range > rcur->range)
7266 return false;
7267 /* If the offsets don't match, we can't trust our alignment;
7268 * nor can we be sure that we won't fall out of range.
7269 */
7270 if (rold->off != rcur->off)
7271 return false;
7272 /* id relations must be preserved */
7273 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
7274 return false;
7275 /* new val must satisfy old val knowledge */
7276 return range_within(rold, rcur) &&
7277 tnum_in(rold->var_off, rcur->var_off);
7278 case PTR_TO_CTX:
7279 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01007280 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07007281 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07007282 case PTR_TO_SOCKET:
7283 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08007284 case PTR_TO_SOCK_COMMON:
7285 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08007286 case PTR_TO_TCP_SOCK:
7287 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07007288 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01007289 /* Only valid matches are exact, which memcmp() above
7290 * would have accepted
7291 */
7292 default:
7293 /* Don't know what's going on, just say it's not safe */
7294 return false;
7295 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007296
Edward Creef1174f72017-08-07 15:26:19 +01007297 /* Shouldn't get here; if we do, say it's not safe */
7298 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007299 return false;
7300}
7301
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007302static bool stacksafe(struct bpf_func_state *old,
7303 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007304 struct idpair *idmap)
7305{
7306 int i, spi;
7307
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007308 /* walk slots of the explored stack and ignore any additional
7309 * slots in the current stack, since explored(safe) state
7310 * didn't use them
7311 */
7312 for (i = 0; i < old->allocated_stack; i++) {
7313 spi = i / BPF_REG_SIZE;
7314
Alexei Starovoitovb2339202018-12-13 11:42:31 -08007315 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
7316 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08007317 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +00007318 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -08007319 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08007320
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007321 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
7322 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -08007323
7324 /* explored stack has more populated slots than current stack
7325 * and these slots were used
7326 */
7327 if (i >= cur->allocated_stack)
7328 return false;
7329
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08007330 /* if old state was safe with misc data in the stack
7331 * it will be safe with zero-initialized stack.
7332 * The opposite is not true
7333 */
7334 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
7335 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
7336 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007337 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
7338 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
7339 /* Ex: old explored (safe) state has STACK_SPILL in
7340 * this stack slot, but current has has STACK_MISC ->
7341 * this verifier states are not equivalent,
7342 * return false to continue verification of this path
7343 */
7344 return false;
7345 if (i % BPF_REG_SIZE)
7346 continue;
7347 if (old->stack[spi].slot_type[0] != STACK_SPILL)
7348 continue;
7349 if (!regsafe(&old->stack[spi].spilled_ptr,
7350 &cur->stack[spi].spilled_ptr,
7351 idmap))
7352 /* when explored and current stack slot are both storing
7353 * spilled registers, check that stored pointers types
7354 * are the same as well.
7355 * Ex: explored safe path could have stored
7356 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
7357 * but current path has stored:
7358 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
7359 * such verifier states are not equivalent.
7360 * return false to continue verification of this path
7361 */
7362 return false;
7363 }
7364 return true;
7365}
7366
Joe Stringerfd978bf72018-10-02 13:35:35 -07007367static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
7368{
7369 if (old->acquired_refs != cur->acquired_refs)
7370 return false;
7371 return !memcmp(old->refs, cur->refs,
7372 sizeof(*old->refs) * old->acquired_refs);
7373}
7374
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007375/* compare two verifier states
7376 *
7377 * all states stored in state_list are known to be valid, since
7378 * verifier reached 'bpf_exit' instruction through them
7379 *
7380 * this function is called when verifier exploring different branches of
7381 * execution popped from the state stack. If it sees an old state that has
7382 * more strict register state and more strict stack state then this execution
7383 * branch doesn't need to be explored further, since verifier already
7384 * concluded that more strict state leads to valid finish.
7385 *
7386 * Therefore two states are equivalent if register state is more conservative
7387 * and explored stack state is more conservative than the current one.
7388 * Example:
7389 * explored current
7390 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
7391 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
7392 *
7393 * In other words if current stack state (one being explored) has more
7394 * valid slots than old one that already passed validation, it means
7395 * the verifier can stop exploring and conclude that current state is valid too
7396 *
7397 * Similarly with registers. If explored state has register type as invalid
7398 * whereas register type in current state is meaningful, it means that
7399 * the current state will reach 'bpf_exit' instruction safely
7400 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007401static bool func_states_equal(struct bpf_func_state *old,
7402 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007403{
Edward Creef1174f72017-08-07 15:26:19 +01007404 struct idpair *idmap;
7405 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007406 int i;
7407
Edward Creef1174f72017-08-07 15:26:19 +01007408 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
7409 /* If we failed to allocate the idmap, just say it's not safe */
7410 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007411 return false;
Edward Creef1174f72017-08-07 15:26:19 +01007412
7413 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +01007414 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +01007415 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007416 }
7417
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007418 if (!stacksafe(old, cur, idmap))
7419 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -07007420
7421 if (!refsafe(old, cur))
7422 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +01007423 ret = true;
7424out_free:
7425 kfree(idmap);
7426 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007427}
7428
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007429static bool states_equal(struct bpf_verifier_env *env,
7430 struct bpf_verifier_state *old,
7431 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +01007432{
Edward Creedc503a82017-08-15 20:34:35 +01007433 int i;
7434
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007435 if (old->curframe != cur->curframe)
7436 return false;
7437
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007438 /* Verification state from speculative execution simulation
7439 * must never prune a non-speculative execution one.
7440 */
7441 if (old->speculative && !cur->speculative)
7442 return false;
7443
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08007444 if (old->active_spin_lock != cur->active_spin_lock)
7445 return false;
7446
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007447 /* for states to be equal callsites have to be the same
7448 * and all frame states need to be equivalent
7449 */
7450 for (i = 0; i <= old->curframe; i++) {
7451 if (old->frame[i]->callsite != cur->frame[i]->callsite)
7452 return false;
7453 if (!func_states_equal(old->frame[i], cur->frame[i]))
7454 return false;
7455 }
7456 return true;
7457}
7458
Jiong Wang5327ed32019-05-24 23:25:12 +01007459/* Return 0 if no propagation happened. Return negative error code if error
7460 * happened. Otherwise, return the propagated bit.
7461 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007462static int propagate_liveness_reg(struct bpf_verifier_env *env,
7463 struct bpf_reg_state *reg,
7464 struct bpf_reg_state *parent_reg)
7465{
Jiong Wang5327ed32019-05-24 23:25:12 +01007466 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
7467 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007468 int err;
7469
Jiong Wang5327ed32019-05-24 23:25:12 +01007470 /* When comes here, read flags of PARENT_REG or REG could be any of
7471 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
7472 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
7473 */
7474 if (parent_flag == REG_LIVE_READ64 ||
7475 /* Or if there is no read flag from REG. */
7476 !flag ||
7477 /* Or if the read flag from REG is the same as PARENT_REG. */
7478 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007479 return 0;
7480
Jiong Wang5327ed32019-05-24 23:25:12 +01007481 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007482 if (err)
7483 return err;
7484
Jiong Wang5327ed32019-05-24 23:25:12 +01007485 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007486}
7487
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007488/* A write screens off any subsequent reads; but write marks come from the
7489 * straight-line code between a state and its parent. When we arrive at an
7490 * equivalent state (jump target or such) we didn't arrive by the straight-line
7491 * code, so read marks in the state must propagate to the parent regardless
7492 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +01007493 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007494 */
7495static int propagate_liveness(struct bpf_verifier_env *env,
7496 const struct bpf_verifier_state *vstate,
7497 struct bpf_verifier_state *vparent)
7498{
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007499 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007500 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007501 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007502
7503 if (vparent->curframe != vstate->curframe) {
7504 WARN(1, "propagate_live: parent frame %d current frame %d\n",
7505 vparent->curframe, vstate->curframe);
7506 return -EFAULT;
7507 }
Edward Creedc503a82017-08-15 20:34:35 +01007508 /* Propagate read liveness of registers... */
7509 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -07007510 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007511 parent = vparent->frame[frame];
7512 state = vstate->frame[frame];
7513 parent_reg = parent->regs;
7514 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -07007515 /* We don't need to worry about FP liveness, it's read-only */
7516 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007517 err = propagate_liveness_reg(env, &state_reg[i],
7518 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +01007519 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007520 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +01007521 if (err == REG_LIVE_READ64)
7522 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +01007523 }
Edward Creedc503a82017-08-15 20:34:35 +01007524
Jiong Wang1b04aee2019-04-12 22:59:34 +01007525 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007526 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
7527 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007528 parent_reg = &parent->stack[i].spilled_ptr;
7529 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01007530 err = propagate_liveness_reg(env, state_reg,
7531 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +01007532 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01007533 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007534 }
Edward Creedc503a82017-08-15 20:34:35 +01007535 }
Jiong Wang5327ed32019-05-24 23:25:12 +01007536 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01007537}
7538
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07007539/* find precise scalars in the previous equivalent state and
7540 * propagate them into the current state
7541 */
7542static int propagate_precision(struct bpf_verifier_env *env,
7543 const struct bpf_verifier_state *old)
7544{
7545 struct bpf_reg_state *state_reg;
7546 struct bpf_func_state *state;
7547 int i, err = 0;
7548
7549 state = old->frame[old->curframe];
7550 state_reg = state->regs;
7551 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
7552 if (state_reg->type != SCALAR_VALUE ||
7553 !state_reg->precise)
7554 continue;
7555 if (env->log.level & BPF_LOG_LEVEL2)
7556 verbose(env, "propagating r%d\n", i);
7557 err = mark_chain_precision(env, i);
7558 if (err < 0)
7559 return err;
7560 }
7561
7562 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
7563 if (state->stack[i].slot_type[0] != STACK_SPILL)
7564 continue;
7565 state_reg = &state->stack[i].spilled_ptr;
7566 if (state_reg->type != SCALAR_VALUE ||
7567 !state_reg->precise)
7568 continue;
7569 if (env->log.level & BPF_LOG_LEVEL2)
7570 verbose(env, "propagating fp%d\n",
7571 (-i - 1) * BPF_REG_SIZE);
7572 err = mark_chain_precision_stack(env, i);
7573 if (err < 0)
7574 return err;
7575 }
7576 return 0;
7577}
7578
Alexei Starovoitov25897262019-06-15 12:12:20 -07007579static bool states_maybe_looping(struct bpf_verifier_state *old,
7580 struct bpf_verifier_state *cur)
7581{
7582 struct bpf_func_state *fold, *fcur;
7583 int i, fr = cur->curframe;
7584
7585 if (old->curframe != fr)
7586 return false;
7587
7588 fold = old->frame[fr];
7589 fcur = cur->frame[fr];
7590 for (i = 0; i < MAX_BPF_REG; i++)
7591 if (memcmp(&fold->regs[i], &fcur->regs[i],
7592 offsetof(struct bpf_reg_state, parent)))
7593 return false;
7594 return true;
7595}
7596
7597
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007598static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007599{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007600 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007601 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +01007602 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08007603 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -07007604 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007605
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007606 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007607 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007608 /* this 'insn_idx' instruction wasn't marked, so we will not
7609 * be doing state search here
7610 */
7611 return 0;
7612
Alexei Starovoitov25897262019-06-15 12:12:20 -07007613 /* bpf progs typically have pruning point every 4 instructions
7614 * http://vger.kernel.org/bpfconf2019.html#session-1
7615 * Do not add new state for future pruning if the verifier hasn't seen
7616 * at least 2 jumps and at least 8 instructions.
7617 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
7618 * In tests that amounts to up to 50% reduction into total verifier
7619 * memory consumption and 20% verifier time speedup.
7620 */
7621 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
7622 env->insn_processed - env->prev_insn_processed >= 8)
7623 add_new_state = true;
7624
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007625 pprev = explored_state(env, insn_idx);
7626 sl = *pprev;
7627
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08007628 clean_live_states(env, insn_idx, cur);
7629
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07007630 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007631 states_cnt++;
7632 if (sl->state.insn_idx != insn_idx)
7633 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -07007634 if (sl->state.branches) {
7635 if (states_maybe_looping(&sl->state, cur) &&
7636 states_equal(env, &sl->state, cur)) {
7637 verbose_linfo(env, insn_idx, "; ");
7638 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
7639 return -EINVAL;
7640 }
7641 /* if the verifier is processing a loop, avoid adding new state
7642 * too often, since different loop iterations have distinct
7643 * states and may not help future pruning.
7644 * This threshold shouldn't be too low to make sure that
7645 * a loop with large bound will be rejected quickly.
7646 * The most abusive loop will be:
7647 * r1 += 1
7648 * if r1 < 1000000 goto pc-2
7649 * 1M insn_procssed limit / 100 == 10k peak states.
7650 * This threshold shouldn't be too high either, since states
7651 * at the end of the loop are likely to be useful in pruning.
7652 */
7653 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
7654 env->insn_processed - env->prev_insn_processed < 100)
7655 add_new_state = false;
7656 goto miss;
7657 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007658 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007659 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007660 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +01007661 * prune the search.
7662 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +01007663 * If we have any write marks in env->cur_state, they
7664 * will prevent corresponding reads in the continuation
7665 * from reaching our parent (an explored_state). Our
7666 * own state will get the read marks recorded, but
7667 * they'll be immediately forgotten as we're pruning
7668 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007669 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007670 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07007671
7672 /* if previous state reached the exit with precision and
7673 * current state is equivalent to it (except precsion marks)
7674 * the precision needs to be propagated back in
7675 * the current state.
7676 */
7677 err = err ? : push_jmp_history(env, cur);
7678 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007679 if (err)
7680 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007681 return 1;
Edward Creedc503a82017-08-15 20:34:35 +01007682 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07007683miss:
7684 /* when new state is not going to be added do not increase miss count.
7685 * Otherwise several loop iterations will remove the state
7686 * recorded earlier. The goal of these heuristics is to have
7687 * states from some iterations of the loop (some in the beginning
7688 * and some at the end) to help pruning.
7689 */
7690 if (add_new_state)
7691 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007692 /* heuristic to determine whether this state is beneficial
7693 * to keep checking from state equivalence point of view.
7694 * Higher numbers increase max_states_per_insn and verification time,
7695 * but do not meaningfully decrease insn_processed.
7696 */
7697 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
7698 /* the state is unlikely to be useful. Remove it to
7699 * speed up verification
7700 */
7701 *pprev = sl->next;
7702 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07007703 u32 br = sl->state.branches;
7704
7705 WARN_ONCE(br,
7706 "BUG live_done but branches_to_explore %d\n",
7707 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007708 free_verifier_state(&sl->state, false);
7709 kfree(sl);
7710 env->peak_states--;
7711 } else {
7712 /* cannot free this state, since parentage chain may
7713 * walk it later. Add it for free_list instead to
7714 * be freed at the end of verification
7715 */
7716 sl->next = env->free_list;
7717 env->free_list = sl;
7718 }
7719 sl = *pprev;
7720 continue;
7721 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007722next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07007723 pprev = &sl->next;
7724 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007725 }
7726
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007727 if (env->max_states_per_insn < states_cnt)
7728 env->max_states_per_insn = states_cnt;
7729
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08007730 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007731 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08007732
Alexei Starovoitov25897262019-06-15 12:12:20 -07007733 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007734 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -07007735
7736 /* There were no equivalent states, remember the current one.
7737 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007738 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -07007739 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007740 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -07007741 * again on the way to bpf_exit.
7742 * When looping the sl->state.branches will be > 0 and this state
7743 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007744 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007745 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007746 if (!new_sl)
7747 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007748 env->total_states++;
7749 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -07007750 env->prev_jmps_processed = env->jmps_processed;
7751 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007752
7753 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +01007754 new = &new_sl->state;
7755 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07007756 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +01007757 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07007758 kfree(new_sl);
7759 return err;
7760 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07007761 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -07007762 WARN_ONCE(new->branches != 1,
7763 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007764
Alexei Starovoitov25897262019-06-15 12:12:20 -07007765 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007766 cur->first_insn_idx = insn_idx;
7767 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -07007768 new_sl->next = *explored_state(env, insn_idx);
7769 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -08007770 /* connect new state to parentage chain. Current frame needs all
7771 * registers connected. Only r6 - r9 of the callers are alive (pushed
7772 * to the stack implicitly by JITs) so in callers' frames connect just
7773 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
7774 * the state of the call instruction (with WRITTEN set), and r0 comes
7775 * from callee with its full parentage chain, anyway.
7776 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +01007777 /* clear write marks in current state: the writes we did are not writes
7778 * our child did, so they don't screen off its reads from us.
7779 * (There are no read marks in current state, because reads always mark
7780 * their parent and current state never has children yet. Only
7781 * explored_states can get read marks.)
7782 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -07007783 for (j = 0; j <= cur->curframe; j++) {
7784 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
7785 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
7786 for (i = 0; i < BPF_REG_FP; i++)
7787 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
7788 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007789
7790 /* all stack frames are accessible from callee, clear them all */
7791 for (j = 0; j <= cur->curframe; j++) {
7792 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +01007793 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007794
Edward Cree679c7822018-08-22 20:02:19 +01007795 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08007796 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01007797 frame->stack[i].spilled_ptr.parent =
7798 &newframe->stack[i].spilled_ptr;
7799 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007800 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007801 return 0;
7802}
7803
Joe Stringerc64b7982018-10-02 13:35:33 -07007804/* Return true if it's OK to have the same insn return a different type. */
7805static bool reg_type_mismatch_ok(enum bpf_reg_type type)
7806{
7807 switch (type) {
7808 case PTR_TO_CTX:
7809 case PTR_TO_SOCKET:
7810 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08007811 case PTR_TO_SOCK_COMMON:
7812 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08007813 case PTR_TO_TCP_SOCK:
7814 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07007815 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -07007816 case PTR_TO_BTF_ID:
Joe Stringerc64b7982018-10-02 13:35:33 -07007817 return false;
7818 default:
7819 return true;
7820 }
7821}
7822
7823/* If an instruction was previously used with particular pointer types, then we
7824 * need to be careful to avoid cases such as the below, where it may be ok
7825 * for one branch accessing the pointer, but not ok for the other branch:
7826 *
7827 * R1 = sock_ptr
7828 * goto X;
7829 * ...
7830 * R1 = some_other_valid_ptr;
7831 * goto X;
7832 * ...
7833 * R2 = *(u32 *)(R1 + 0);
7834 */
7835static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
7836{
7837 return src != prev && (!reg_type_mismatch_ok(src) ||
7838 !reg_type_mismatch_ok(prev));
7839}
7840
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007841static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007842{
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08007843 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007844 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007845 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007846 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007847 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007848 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007849
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007850 for (;;) {
7851 struct bpf_insn *insn;
7852 u8 class;
7853 int err;
7854
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007855 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007856 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007857 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007858 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007859 return -EFAULT;
7860 }
7861
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007862 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007863 class = BPF_CLASS(insn->code);
7864
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007865 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007866 verbose(env,
7867 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007868 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007869 return -E2BIG;
7870 }
7871
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007872 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007873 if (err < 0)
7874 return err;
7875 if (err == 1) {
7876 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007877 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007878 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007879 verbose(env, "\nfrom %d to %d%s: safe\n",
7880 env->prev_insn_idx, env->insn_idx,
7881 env->cur_state->speculative ?
7882 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007883 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007884 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07007885 }
7886 goto process_bpf_exit;
7887 }
7888
Alexei Starovoitovc3494802018-12-03 22:46:04 -08007889 if (signal_pending(current))
7890 return -EAGAIN;
7891
Daniel Borkmann3c2ce602017-05-18 03:00:06 +02007892 if (need_resched())
7893 cond_resched();
7894
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007895 if (env->log.level & BPF_LOG_LEVEL2 ||
7896 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
7897 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007898 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -07007899 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007900 verbose(env, "\nfrom %d to %d%s:",
7901 env->prev_insn_idx, env->insn_idx,
7902 env->cur_state->speculative ?
7903 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007904 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007905 do_print_state = false;
7906 }
7907
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07007908 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01007909 const struct bpf_insn_cbs cbs = {
7910 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +01007911 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +01007912 };
7913
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007914 verbose_linfo(env, env->insn_idx, "; ");
7915 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +01007916 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007917 }
7918
Jakub Kicinskicae19272017-12-27 18:39:05 -08007919 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007920 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
7921 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -08007922 if (err)
7923 return err;
7924 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +01007925
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007926 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08007927 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007928 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -07007929
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007930 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007931 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007932 if (err)
7933 return err;
7934
7935 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007936 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007937
7938 /* check for reserved fields is already done */
7939
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007940 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007941 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007942 if (err)
7943 return err;
7944
Edward Creedc503a82017-08-15 20:34:35 +01007945 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007946 if (err)
7947 return err;
7948
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -07007949 src_reg_type = regs[insn->src_reg].type;
7950
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007951 /* check that memory (src_reg + off) is readable,
7952 * the state of dst_reg will be updated by this func
7953 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007954 err = check_mem_access(env, env->insn_idx, insn->src_reg,
7955 insn->off, BPF_SIZE(insn->code),
7956 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007957 if (err)
7958 return err;
7959
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007960 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007961
7962 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007963 /* saw a valid insn
7964 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007965 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007966 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007967 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007968
Joe Stringerc64b7982018-10-02 13:35:33 -07007969 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007970 /* ABuser program is trying to use the same insn
7971 * dst_reg = *(u32*) (src_reg + off)
7972 * with different pointer types:
7973 * src_reg == ctx in one branch and
7974 * src_reg == stack|map in some other branch.
7975 * Reject it.
7976 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007977 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07007978 return -EINVAL;
7979 }
7980
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007981 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01007982 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07007983
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007984 if (BPF_MODE(insn->code) == BPF_XADD) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007985 err = check_xadd(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007986 if (err)
7987 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01007988 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007989 continue;
7990 }
7991
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007992 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007993 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007994 if (err)
7995 return err;
7996 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007997 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007998 if (err)
7999 return err;
8000
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008001 dst_reg_type = regs[insn->dst_reg].type;
8002
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008003 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008004 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8005 insn->off, BPF_SIZE(insn->code),
8006 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008007 if (err)
8008 return err;
8009
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008010 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01008011
8012 if (*prev_dst_type == NOT_INIT) {
8013 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -07008014 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008015 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008016 return -EINVAL;
8017 }
8018
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008019 } else if (class == BPF_ST) {
8020 if (BPF_MODE(insn->code) != BPF_MEM ||
8021 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008022 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008023 return -EINVAL;
8024 }
8025 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01008026 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008027 if (err)
8028 return err;
8029
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01008030 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -07008031 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02008032 insn->dst_reg,
8033 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01008034 return -EACCES;
8035 }
8036
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008037 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008038 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8039 insn->off, BPF_SIZE(insn->code),
8040 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008041 if (err)
8042 return err;
8043
Jiong Wang092ed092019-01-26 12:26:01 -05008044 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008045 u8 opcode = BPF_OP(insn->code);
8046
Alexei Starovoitov25897262019-06-15 12:12:20 -07008047 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008048 if (opcode == BPF_CALL) {
8049 if (BPF_SRC(insn->code) != BPF_K ||
8050 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008051 (insn->src_reg != BPF_REG_0 &&
8052 insn->src_reg != BPF_PSEUDO_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -05008053 insn->dst_reg != BPF_REG_0 ||
8054 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008055 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008056 return -EINVAL;
8057 }
8058
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008059 if (env->cur_state->active_spin_lock &&
8060 (insn->src_reg == BPF_PSEUDO_CALL ||
8061 insn->imm != BPF_FUNC_spin_unlock)) {
8062 verbose(env, "function calls are not allowed while holding a lock\n");
8063 return -EINVAL;
8064 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008065 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008066 err = check_func_call(env, insn, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008067 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008068 err = check_helper_call(env, insn->imm, env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008069 if (err)
8070 return err;
8071
8072 } else if (opcode == BPF_JA) {
8073 if (BPF_SRC(insn->code) != BPF_K ||
8074 insn->imm != 0 ||
8075 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05008076 insn->dst_reg != BPF_REG_0 ||
8077 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008078 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008079 return -EINVAL;
8080 }
8081
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008082 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008083 continue;
8084
8085 } else if (opcode == BPF_EXIT) {
8086 if (BPF_SRC(insn->code) != BPF_K ||
8087 insn->imm != 0 ||
8088 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -05008089 insn->dst_reg != BPF_REG_0 ||
8090 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008091 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008092 return -EINVAL;
8093 }
8094
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008095 if (env->cur_state->active_spin_lock) {
8096 verbose(env, "bpf_spin_unlock is missing\n");
8097 return -EINVAL;
8098 }
8099
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008100 if (state->curframe) {
8101 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008102 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008103 if (err)
8104 return err;
8105 do_print_state = true;
8106 continue;
8107 }
8108
Joe Stringerfd978bf72018-10-02 13:35:35 -07008109 err = check_reference_leak(env);
8110 if (err)
8111 return err;
8112
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008113 err = check_return_code(env);
8114 if (err)
8115 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008116process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -07008117 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008118 err = pop_stack(env, &prev_insn_idx,
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008119 &env->insn_idx);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008120 if (err < 0) {
8121 if (err != -ENOENT)
8122 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008123 break;
8124 } else {
8125 do_print_state = true;
8126 continue;
8127 }
8128 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008129 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008130 if (err)
8131 return err;
8132 }
8133 } else if (class == BPF_LD) {
8134 u8 mode = BPF_MODE(insn->code);
8135
8136 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008137 err = check_ld_abs(env, insn);
8138 if (err)
8139 return err;
8140
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008141 } else if (mode == BPF_IMM) {
8142 err = check_ld_imm(env, insn);
8143 if (err)
8144 return err;
8145
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008146 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008147 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008148 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008149 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008150 return -EINVAL;
8151 }
8152 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008153 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008154 return -EINVAL;
8155 }
8156
Daniel Borkmannc08435e2019-01-03 00:58:27 +01008157 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008158 }
8159
8160 return 0;
8161}
8162
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07008163static int check_map_prealloc(struct bpf_map *map)
8164{
8165 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07008166 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8167 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07008168 !(map->map_flags & BPF_F_NO_PREALLOC);
8169}
8170
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008171static bool is_tracing_prog_type(enum bpf_prog_type type)
8172{
8173 switch (type) {
8174 case BPF_PROG_TYPE_KPROBE:
8175 case BPF_PROG_TYPE_TRACEPOINT:
8176 case BPF_PROG_TYPE_PERF_EVENT:
8177 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8178 return true;
8179 default:
8180 return false;
8181 }
8182}
8183
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01008184static bool is_preallocated_map(struct bpf_map *map)
8185{
8186 if (!check_map_prealloc(map))
8187 return false;
8188 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
8189 return false;
8190 return true;
8191}
8192
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008193static int check_map_prog_compatibility(struct bpf_verifier_env *env,
8194 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07008195 struct bpf_prog *prog)
8196
8197{
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01008198 /*
8199 * Validate that trace type programs use preallocated hash maps.
8200 *
8201 * For programs attached to PERF events this is mandatory as the
8202 * perf NMI can hit any arbitrary code sequence.
8203 *
8204 * All other trace types using preallocated hash maps are unsafe as
8205 * well because tracepoint or kprobes can be inside locked regions
8206 * of the memory allocator or at a place where a recursion into the
8207 * memory allocator would see inconsistent state.
8208 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01008209 * On RT enabled kernels run-time allocation of all trace type
8210 * programs is strictly prohibited due to lock type constraints. On
8211 * !RT kernels it is allowed for backwards compatibility reasons for
8212 * now, but warnings are emitted so developers are made aware of
8213 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07008214 */
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01008215 if (is_tracing_prog_type(prog->type) && !is_preallocated_map(map)) {
8216 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008217 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07008218 return -EINVAL;
8219 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +01008220 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8221 verbose(env, "trace type programs can only use preallocated hash map\n");
8222 return -EINVAL;
8223 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +01008224 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
8225 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 -07008226 }
Jakub Kicinskia3884572018-01-11 20:29:09 -08008227
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008228 if ((is_tracing_prog_type(prog->type) ||
8229 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
8230 map_value_has_spin_lock(map)) {
8231 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
8232 return -EINVAL;
8233 }
8234
Jakub Kicinskia3884572018-01-11 20:29:09 -08008235 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -07008236 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -08008237 verbose(env, "offload device mismatch between prog and map\n");
8238 return -EINVAL;
8239 }
8240
Martin KaFai Lau85d33df2020-01-08 16:35:05 -08008241 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
8242 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
8243 return -EINVAL;
8244 }
8245
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07008246 return 0;
8247}
8248
Roman Gushchinb741f162018-09-28 14:45:43 +00008249static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
8250{
8251 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
8252 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
8253}
8254
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008255/* look for pseudo eBPF instructions that access map FDs and
8256 * replace them with actual map pointers
8257 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008258static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008259{
8260 struct bpf_insn *insn = env->prog->insnsi;
8261 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07008262 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008263
Daniel Borkmannf1f77142017-01-13 23:38:15 +01008264 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +01008265 if (err)
8266 return err;
8267
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008268 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008269 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008270 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008271 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008272 return -EINVAL;
8273 }
8274
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008275 if (BPF_CLASS(insn->code) == BPF_STX &&
8276 ((BPF_MODE(insn->code) != BPF_MEM &&
8277 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008278 verbose(env, "BPF_STX uses reserved fields\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008279 return -EINVAL;
8280 }
8281
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008282 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008283 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008284 struct bpf_map *map;
8285 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008286 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008287
8288 if (i == insn_cnt - 1 || insn[1].code != 0 ||
8289 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
8290 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008291 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008292 return -EINVAL;
8293 }
8294
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008295 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008296 /* valid generic load 64-bit imm */
8297 goto next_insn;
8298
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008299 /* In final convert_pseudo_ld_imm64() step, this is
8300 * converted into regular 64-bit imm load insn.
8301 */
8302 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
8303 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
8304 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
8305 insn[1].imm != 0)) {
8306 verbose(env,
8307 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008308 return -EINVAL;
8309 }
8310
Daniel Borkmann20182392019-03-04 21:08:53 +01008311 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +01008312 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008313 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008314 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +01008315 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008316 return PTR_ERR(map);
8317 }
8318
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008319 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -07008320 if (err) {
8321 fdput(f);
8322 return err;
8323 }
8324
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008325 aux = &env->insn_aux_data[i];
8326 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8327 addr = (unsigned long)map;
8328 } else {
8329 u32 off = insn[1].imm;
8330
8331 if (off >= BPF_MAX_VAR_OFF) {
8332 verbose(env, "direct value offset of %u is not allowed\n", off);
8333 fdput(f);
8334 return -EINVAL;
8335 }
8336
8337 if (!map->ops->map_direct_value_addr) {
8338 verbose(env, "no direct value access support for this map type\n");
8339 fdput(f);
8340 return -EINVAL;
8341 }
8342
8343 err = map->ops->map_direct_value_addr(map, &addr, off);
8344 if (err) {
8345 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
8346 map->value_size, off);
8347 fdput(f);
8348 return err;
8349 }
8350
8351 aux->map_off = off;
8352 addr += off;
8353 }
8354
8355 insn[0].imm = (u32)addr;
8356 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008357
8358 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008359 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008360 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008361 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008362 fdput(f);
8363 goto next_insn;
8364 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008365 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008366
8367 if (env->used_map_cnt >= MAX_USED_MAPS) {
8368 fdput(f);
8369 return -E2BIG;
8370 }
8371
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008372 /* hold the map. If the program is rejected by verifier,
8373 * the map will be released by release_maps() or it
8374 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -07008375 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008376 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -08008377 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008378
8379 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -07008380 env->used_maps[env->used_map_cnt++] = map;
8381
Roman Gushchinb741f162018-09-28 14:45:43 +00008382 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +01008383 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +00008384 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -07008385 fdput(f);
8386 return -EBUSY;
8387 }
8388
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008389 fdput(f);
8390next_insn:
8391 insn++;
8392 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +01008393 continue;
8394 }
8395
8396 /* Basic sanity check before we invest more work here. */
8397 if (!bpf_opcode_in_insntable(insn->code)) {
8398 verbose(env, "unknown opcode %02x\n", insn->code);
8399 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008400 }
8401 }
8402
8403 /* now all pseudo BPF_LD_IMM64 instructions load valid
8404 * 'struct bpf_map *' into a register instead of user map_fd.
8405 * These pointers will be used later by verifier to validate map access.
8406 */
8407 return 0;
8408}
8409
8410/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008411static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008412{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +01008413 __bpf_free_used_maps(env->prog->aux, env->used_maps,
8414 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008415}
8416
8417/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008418static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -07008419{
8420 struct bpf_insn *insn = env->prog->insnsi;
8421 int insn_cnt = env->prog->len;
8422 int i;
8423
8424 for (i = 0; i < insn_cnt; i++, insn++)
8425 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
8426 insn->src_reg = 0;
8427}
8428
Alexei Starovoitov80419022017-03-15 18:26:41 -07008429/* single env->prog->insni[off] instruction was replaced with the range
8430 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
8431 * [0, off) and [off, end) to new locations, so the patched range stays zero
8432 */
Jiong Wangb325fbc2019-05-24 23:25:13 +01008433static int adjust_insn_aux_data(struct bpf_verifier_env *env,
8434 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -07008435{
8436 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +01008437 struct bpf_insn *insn = new_prog->insnsi;
8438 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -08008439 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -07008440
Jiong Wangb325fbc2019-05-24 23:25:13 +01008441 /* aux info at OFF always needs adjustment, no matter fast path
8442 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
8443 * original insn at old prog.
8444 */
8445 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
8446
Alexei Starovoitov80419022017-03-15 18:26:41 -07008447 if (cnt == 1)
8448 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +01008449 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -07008450 new_data = vzalloc(array_size(prog_len,
8451 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -07008452 if (!new_data)
8453 return -ENOMEM;
8454 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
8455 memcpy(new_data + off + cnt - 1, old_data + off,
8456 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +01008457 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008458 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +01008459 new_data[i].zext_dst = insn_has_def32(env, insn + i);
8460 }
Alexei Starovoitov80419022017-03-15 18:26:41 -07008461 env->insn_aux_data = new_data;
8462 vfree(old_data);
8463 return 0;
8464}
8465
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008466static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
8467{
8468 int i;
8469
8470 if (len == 1)
8471 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -04008472 /* NOTE: fake 'exit' subprog should be updated as well. */
8473 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +00008474 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008475 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -04008476 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008477 }
8478}
8479
Alexei Starovoitov80419022017-03-15 18:26:41 -07008480static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
8481 const struct bpf_insn *patch, u32 len)
8482{
8483 struct bpf_prog *new_prog;
8484
8485 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -07008486 if (IS_ERR(new_prog)) {
8487 if (PTR_ERR(new_prog) == -ERANGE)
8488 verbose(env,
8489 "insn %d cannot be patched due to 16-bit range\n",
8490 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -07008491 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -07008492 }
Jiong Wangb325fbc2019-05-24 23:25:13 +01008493 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -07008494 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008495 adjust_subprog_starts(env, off, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -07008496 return new_prog;
8497}
8498
Jakub Kicinski52875a02019-01-22 22:45:20 -08008499static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
8500 u32 off, u32 cnt)
8501{
8502 int i, j;
8503
8504 /* find first prog starting at or after off (first to remove) */
8505 for (i = 0; i < env->subprog_cnt; i++)
8506 if (env->subprog_info[i].start >= off)
8507 break;
8508 /* find first prog starting at or after off + cnt (first to stay) */
8509 for (j = i; j < env->subprog_cnt; j++)
8510 if (env->subprog_info[j].start >= off + cnt)
8511 break;
8512 /* if j doesn't start exactly at off + cnt, we are just removing
8513 * the front of previous prog
8514 */
8515 if (env->subprog_info[j].start != off + cnt)
8516 j--;
8517
8518 if (j > i) {
8519 struct bpf_prog_aux *aux = env->prog->aux;
8520 int move;
8521
8522 /* move fake 'exit' subprog as well */
8523 move = env->subprog_cnt + 1 - j;
8524
8525 memmove(env->subprog_info + i,
8526 env->subprog_info + j,
8527 sizeof(*env->subprog_info) * move);
8528 env->subprog_cnt -= j - i;
8529
8530 /* remove func_info */
8531 if (aux->func_info) {
8532 move = aux->func_info_cnt - j;
8533
8534 memmove(aux->func_info + i,
8535 aux->func_info + j,
8536 sizeof(*aux->func_info) * move);
8537 aux->func_info_cnt -= j - i;
8538 /* func_info->insn_off is set after all code rewrites,
8539 * in adjust_btf_func() - no need to adjust
8540 */
8541 }
8542 } else {
8543 /* convert i from "first prog to remove" to "first to adjust" */
8544 if (env->subprog_info[i].start == off)
8545 i++;
8546 }
8547
8548 /* update fake 'exit' subprog as well */
8549 for (; i <= env->subprog_cnt; i++)
8550 env->subprog_info[i].start -= cnt;
8551
8552 return 0;
8553}
8554
8555static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
8556 u32 cnt)
8557{
8558 struct bpf_prog *prog = env->prog;
8559 u32 i, l_off, l_cnt, nr_linfo;
8560 struct bpf_line_info *linfo;
8561
8562 nr_linfo = prog->aux->nr_linfo;
8563 if (!nr_linfo)
8564 return 0;
8565
8566 linfo = prog->aux->linfo;
8567
8568 /* find first line info to remove, count lines to be removed */
8569 for (i = 0; i < nr_linfo; i++)
8570 if (linfo[i].insn_off >= off)
8571 break;
8572
8573 l_off = i;
8574 l_cnt = 0;
8575 for (; i < nr_linfo; i++)
8576 if (linfo[i].insn_off < off + cnt)
8577 l_cnt++;
8578 else
8579 break;
8580
8581 /* First live insn doesn't match first live linfo, it needs to "inherit"
8582 * last removed linfo. prog is already modified, so prog->len == off
8583 * means no live instructions after (tail of the program was removed).
8584 */
8585 if (prog->len != off && l_cnt &&
8586 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
8587 l_cnt--;
8588 linfo[--i].insn_off = off + cnt;
8589 }
8590
8591 /* remove the line info which refer to the removed instructions */
8592 if (l_cnt) {
8593 memmove(linfo + l_off, linfo + i,
8594 sizeof(*linfo) * (nr_linfo - i));
8595
8596 prog->aux->nr_linfo -= l_cnt;
8597 nr_linfo = prog->aux->nr_linfo;
8598 }
8599
8600 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
8601 for (i = l_off; i < nr_linfo; i++)
8602 linfo[i].insn_off -= cnt;
8603
8604 /* fix up all subprogs (incl. 'exit') which start >= off */
8605 for (i = 0; i <= env->subprog_cnt; i++)
8606 if (env->subprog_info[i].linfo_idx > l_off) {
8607 /* program may have started in the removed region but
8608 * may not be fully removed
8609 */
8610 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
8611 env->subprog_info[i].linfo_idx -= l_cnt;
8612 else
8613 env->subprog_info[i].linfo_idx = l_off;
8614 }
8615
8616 return 0;
8617}
8618
8619static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
8620{
8621 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8622 unsigned int orig_prog_len = env->prog->len;
8623 int err;
8624
Jakub Kicinski08ca90a2019-01-22 22:45:24 -08008625 if (bpf_prog_is_dev_bound(env->prog->aux))
8626 bpf_prog_offload_remove_insns(env, off, cnt);
8627
Jakub Kicinski52875a02019-01-22 22:45:20 -08008628 err = bpf_remove_insns(env->prog, off, cnt);
8629 if (err)
8630 return err;
8631
8632 err = adjust_subprog_starts_after_remove(env, off, cnt);
8633 if (err)
8634 return err;
8635
8636 err = bpf_adj_linfo_after_remove(env, off, cnt);
8637 if (err)
8638 return err;
8639
8640 memmove(aux_data + off, aux_data + off + cnt,
8641 sizeof(*aux_data) * (orig_prog_len - off - cnt));
8642
8643 return 0;
8644}
8645
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01008646/* The verifier does more data flow analysis than llvm and will not
8647 * explore branches that are dead at run time. Malicious programs can
8648 * have dead code too. Therefore replace all dead at-run-time code
8649 * with 'ja -1'.
8650 *
8651 * Just nops are not optimal, e.g. if they would sit at the end of the
8652 * program and through another bug we would manage to jump there, then
8653 * we'd execute beyond program memory otherwise. Returning exception
8654 * code also wouldn't work since we can have subprogs where the dead
8655 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -08008656 */
8657static void sanitize_dead_code(struct bpf_verifier_env *env)
8658{
8659 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01008660 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -08008661 struct bpf_insn *insn = env->prog->insnsi;
8662 const int insn_cnt = env->prog->len;
8663 int i;
8664
8665 for (i = 0; i < insn_cnt; i++) {
8666 if (aux_data[i].seen)
8667 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +01008668 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -08008669 }
8670}
8671
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08008672static bool insn_is_cond_jump(u8 code)
8673{
8674 u8 op;
8675
Jiong Wang092ed092019-01-26 12:26:01 -05008676 if (BPF_CLASS(code) == BPF_JMP32)
8677 return true;
8678
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08008679 if (BPF_CLASS(code) != BPF_JMP)
8680 return false;
8681
8682 op = BPF_OP(code);
8683 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
8684}
8685
8686static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
8687{
8688 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8689 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8690 struct bpf_insn *insn = env->prog->insnsi;
8691 const int insn_cnt = env->prog->len;
8692 int i;
8693
8694 for (i = 0; i < insn_cnt; i++, insn++) {
8695 if (!insn_is_cond_jump(insn->code))
8696 continue;
8697
8698 if (!aux_data[i + 1].seen)
8699 ja.off = insn->off;
8700 else if (!aux_data[i + 1 + insn->off].seen)
8701 ja.off = 0;
8702 else
8703 continue;
8704
Jakub Kicinski08ca90a2019-01-22 22:45:24 -08008705 if (bpf_prog_is_dev_bound(env->prog->aux))
8706 bpf_prog_offload_replace_insn(env, i, &ja);
8707
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -08008708 memcpy(insn, &ja, sizeof(ja));
8709 }
8710}
8711
Jakub Kicinski52875a02019-01-22 22:45:20 -08008712static int opt_remove_dead_code(struct bpf_verifier_env *env)
8713{
8714 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8715 int insn_cnt = env->prog->len;
8716 int i, err;
8717
8718 for (i = 0; i < insn_cnt; i++) {
8719 int j;
8720
8721 j = 0;
8722 while (i + j < insn_cnt && !aux_data[i + j].seen)
8723 j++;
8724 if (!j)
8725 continue;
8726
8727 err = verifier_remove_insns(env, i, j);
8728 if (err)
8729 return err;
8730 insn_cnt = env->prog->len;
8731 }
8732
8733 return 0;
8734}
8735
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -08008736static int opt_remove_nops(struct bpf_verifier_env *env)
8737{
8738 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8739 struct bpf_insn *insn = env->prog->insnsi;
8740 int insn_cnt = env->prog->len;
8741 int i, err;
8742
8743 for (i = 0; i < insn_cnt; i++) {
8744 if (memcmp(&insn[i], &ja, sizeof(ja)))
8745 continue;
8746
8747 err = verifier_remove_insns(env, i, 1);
8748 if (err)
8749 return err;
8750 insn_cnt--;
8751 i--;
8752 }
8753
8754 return 0;
8755}
8756
Jiong Wangd6c23082019-05-24 23:25:18 +01008757static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
8758 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008759{
Jiong Wangd6c23082019-05-24 23:25:18 +01008760 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008761 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +01008762 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008763 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008764 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +01008765 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008766
Jiong Wangd6c23082019-05-24 23:25:18 +01008767 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008768 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +01008769 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
8770 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
8771 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008772 for (i = 0; i < len; i++) {
8773 int adj_idx = i + delta;
8774 struct bpf_insn insn;
8775
Jiong Wangd6c23082019-05-24 23:25:18 +01008776 insn = insns[adj_idx];
8777 if (!aux[adj_idx].zext_dst) {
8778 u8 code, class;
8779 u32 imm_rnd;
8780
8781 if (!rnd_hi32)
8782 continue;
8783
8784 code = insn.code;
8785 class = BPF_CLASS(code);
8786 if (insn_no_def(&insn))
8787 continue;
8788
8789 /* NOTE: arg "reg" (the fourth one) is only used for
8790 * BPF_STX which has been ruled out in above
8791 * check, it is safe to pass NULL here.
8792 */
8793 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
8794 if (class == BPF_LD &&
8795 BPF_MODE(code) == BPF_IMM)
8796 i++;
8797 continue;
8798 }
8799
8800 /* ctx load could be transformed into wider load. */
8801 if (class == BPF_LDX &&
8802 aux[adj_idx].ptr_type == PTR_TO_CTX)
8803 continue;
8804
8805 imm_rnd = get_random_int();
8806 rnd_hi32_patch[0] = insn;
8807 rnd_hi32_patch[1].imm = imm_rnd;
8808 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
8809 patch = rnd_hi32_patch;
8810 patch_len = 4;
8811 goto apply_patch_buffer;
8812 }
8813
8814 if (!bpf_jit_needs_zext())
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008815 continue;
8816
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008817 zext_patch[0] = insn;
8818 zext_patch[1].dst_reg = insn.dst_reg;
8819 zext_patch[1].src_reg = insn.dst_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +01008820 patch = zext_patch;
8821 patch_len = 2;
8822apply_patch_buffer:
8823 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008824 if (!new_prog)
8825 return -ENOMEM;
8826 env->prog = new_prog;
8827 insns = new_prog->insnsi;
8828 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +01008829 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +01008830 }
8831
8832 return 0;
8833}
8834
Joe Stringerc64b7982018-10-02 13:35:33 -07008835/* convert load instructions that access fields of a context type into a
8836 * sequence of instructions that access fields of the underlying structure:
8837 * struct __sk_buff -> struct sk_buff
8838 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008839 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008840static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008841{
Jakub Kicinski00176a32017-10-16 16:40:54 -07008842 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +02008843 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01008844 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008845 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -08008846 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008847 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008848 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +02008849 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008850
Daniel Borkmannb09928b2018-10-24 22:05:49 +02008851 if (ops->gen_prologue || env->seen_direct_write) {
8852 if (!ops->gen_prologue) {
8853 verbose(env, "bpf verifier is misconfigured\n");
8854 return -EINVAL;
8855 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008856 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
8857 env->prog);
8858 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008859 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008860 return -EINVAL;
8861 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -07008862 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008863 if (!new_prog)
8864 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -07008865
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008866 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01008867 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008868 }
8869 }
8870
Joe Stringerc64b7982018-10-02 13:35:33 -07008871 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008872 return 0;
8873
Jakub Kicinski3df126f2016-09-21 11:43:56 +01008874 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +02008875
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008876 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -07008877 bpf_convert_ctx_access_t convert_ctx_access;
8878
Daniel Borkmann62c79892017-01-12 11:51:33 +01008879 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
8880 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
8881 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -07008882 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008883 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +01008884 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
8885 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
8886 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -07008887 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07008888 type = BPF_WRITE;
8889 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008890 continue;
8891
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07008892 if (type == BPF_WRITE &&
8893 env->insn_aux_data[i + delta].sanitize_stack_off) {
8894 struct bpf_insn patch[] = {
8895 /* Sanitize suspicious stack slot with zero.
8896 * There are no memory dependencies for this store,
8897 * since it's only using frame pointer and immediate
8898 * constant of zero
8899 */
8900 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
8901 env->insn_aux_data[i + delta].sanitize_stack_off,
8902 0),
8903 /* the original STX instruction will immediately
8904 * overwrite the same stack slot with appropriate value
8905 */
8906 *insn,
8907 };
8908
8909 cnt = ARRAY_SIZE(patch);
8910 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
8911 if (!new_prog)
8912 return -ENOMEM;
8913
8914 delta += cnt - 1;
8915 env->prog = new_prog;
8916 insn = new_prog->insnsi + i + delta;
8917 continue;
8918 }
8919
Joe Stringerc64b7982018-10-02 13:35:33 -07008920 switch (env->insn_aux_data[i + delta].ptr_type) {
8921 case PTR_TO_CTX:
8922 if (!ops->convert_ctx_access)
8923 continue;
8924 convert_ctx_access = ops->convert_ctx_access;
8925 break;
8926 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08008927 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -07008928 convert_ctx_access = bpf_sock_convert_ctx_access;
8929 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08008930 case PTR_TO_TCP_SOCK:
8931 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
8932 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07008933 case PTR_TO_XDP_SOCK:
8934 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
8935 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -07008936 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008937 if (type == BPF_READ) {
8938 insn->code = BPF_LDX | BPF_PROBE_MEM |
8939 BPF_SIZE((insn)->code);
8940 env->prog->aux->num_exentries++;
8941 } else if (env->prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -07008942 verbose(env, "Writes through BTF pointers are not allowed\n");
8943 return -EINVAL;
8944 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -07008945 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -07008946 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008947 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -07008948 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008949
Yonghong Song31fd8582017-06-13 15:52:13 -07008950 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +02008951 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -07008952
8953 /* If the read access is a narrower load of the field,
8954 * convert to a 4/8-byte load, to minimum program type specific
8955 * convert_ctx_access changes. If conversion is successful,
8956 * we will apply proper mask to the result.
8957 */
Daniel Borkmannf96da092017-07-02 02:13:27 +02008958 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -08008959 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
8960 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -07008961 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02008962 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -07008963
Daniel Borkmannf96da092017-07-02 02:13:27 +02008964 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008965 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +02008966 return -EINVAL;
8967 }
8968
8969 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -07008970 if (ctx_field_size == 4)
8971 size_code = BPF_W;
8972 else if (ctx_field_size == 8)
8973 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +02008974
Daniel Borkmannbc231052018-06-02 23:06:39 +02008975 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -07008976 insn->code = BPF_LDX | BPF_MEM | size_code;
8977 }
Daniel Borkmannf96da092017-07-02 02:13:27 +02008978
8979 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -07008980 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
8981 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +02008982 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
8983 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008984 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07008985 return -EINVAL;
8986 }
Daniel Borkmannf96da092017-07-02 02:13:27 +02008987
8988 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +02008989 u8 shift = bpf_ctx_narrow_access_offset(
8990 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -08008991 if (ctx_field_size <= 4) {
8992 if (shift)
8993 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
8994 insn->dst_reg,
8995 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -07008996 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +02008997 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -08008998 } else {
8999 if (shift)
9000 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
9001 insn->dst_reg,
9002 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -07009003 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +02009004 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -08009005 }
Yonghong Song31fd8582017-06-13 15:52:13 -07009006 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009007
Alexei Starovoitov80419022017-03-15 18:26:41 -07009008 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009009 if (!new_prog)
9010 return -ENOMEM;
9011
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009012 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009013
9014 /* keep walking new program and skip insns we just inserted */
9015 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009016 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009017 }
9018
9019 return 0;
9020}
9021
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009022static int jit_subprogs(struct bpf_verifier_env *env)
9023{
9024 struct bpf_prog *prog = env->prog, **func, *tmp;
9025 int i, j, subprog_start, subprog_end = 0, len, subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +01009026 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009027 void *old_bpf_func;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009028 int err;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009029
Jiong Wangf910cef2018-05-02 16:17:17 -04009030 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009031 return 0;
9032
Daniel Borkmann7105e822017-12-20 13:42:57 +01009033 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009034 if (insn->code != (BPF_JMP | BPF_CALL) ||
9035 insn->src_reg != BPF_PSEUDO_CALL)
9036 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009037 /* Upon error here we cannot fall back to interpreter but
9038 * need a hard reject of the program. Thus -EFAULT is
9039 * propagated in any case.
9040 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009041 subprog = find_subprog(env, i + insn->imm + 1);
9042 if (subprog < 0) {
9043 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
9044 i + insn->imm + 1);
9045 return -EFAULT;
9046 }
9047 /* temporarily remember subprog id inside insn instead of
9048 * aux_data, since next loop will split up all insns into funcs
9049 */
Jiong Wangf910cef2018-05-02 16:17:17 -04009050 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009051 /* remember original imm in case JIT fails and fallback
9052 * to interpreter will be needed
9053 */
9054 env->insn_aux_data[i].call_imm = insn->imm;
9055 /* point imm to __bpf_call_base+1 from JITs point of view */
9056 insn->imm = 1;
9057 }
9058
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009059 err = bpf_prog_alloc_jited_linfo(prog);
9060 if (err)
9061 goto out_undo_insn;
9062
9063 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -07009064 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009065 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009066 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009067
Jiong Wangf910cef2018-05-02 16:17:17 -04009068 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009069 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04009070 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009071
9072 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -08009073 /* BPF_PROG_RUN doesn't call subprogs directly,
9074 * hence main prog stats include the runtime of subprogs.
9075 * subprogs don't have IDs and not reachable via prog_get_next_id
9076 * func[i]->aux->stats will never be accessed and stays NULL
9077 */
9078 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009079 if (!func[i])
9080 goto out_free;
9081 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
9082 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +01009083 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009084 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +01009085 if (bpf_prog_calc_tag(func[i]))
9086 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009087 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009088 func[i]->aux->func_idx = i;
9089 /* the btf and func_info will be freed only at prog->aux */
9090 func[i]->aux->btf = prog->aux->btf;
9091 func[i]->aux->func_info = prog->aux->func_info;
9092
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009093 /* Use bpf_prog_F_tag to indicate functions in stack traces.
9094 * Long term would need debug info to populate names
9095 */
9096 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -04009097 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009098 func[i]->jit_requested = 1;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009099 func[i]->aux->linfo = prog->aux->linfo;
9100 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
9101 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
9102 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009103 func[i] = bpf_int_jit_compile(func[i]);
9104 if (!func[i]->jited) {
9105 err = -ENOTSUPP;
9106 goto out_free;
9107 }
9108 cond_resched();
9109 }
9110 /* at this point all bpf functions were successfully JITed
9111 * now populate all bpf_calls with correct addresses and
9112 * run last pass of JIT
9113 */
Jiong Wangf910cef2018-05-02 16:17:17 -04009114 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009115 insn = func[i]->insnsi;
9116 for (j = 0; j < func[i]->len; j++, insn++) {
9117 if (insn->code != (BPF_JMP | BPF_CALL) ||
9118 insn->src_reg != BPF_PSEUDO_CALL)
9119 continue;
9120 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +09009121 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
9122 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009123 }
Sandipan Das2162fed2018-05-24 12:26:45 +05309124
9125 /* we use the aux data to keep a list of the start addresses
9126 * of the JITed images for each function in the program
9127 *
9128 * for some architectures, such as powerpc64, the imm field
9129 * might not be large enough to hold the offset of the start
9130 * address of the callee's JITed image from __bpf_call_base
9131 *
9132 * in such cases, we can lookup the start address of a callee
9133 * by using its subprog id, available from the off field of
9134 * the call instruction, as an index for this list
9135 */
9136 func[i]->aux->func = func;
9137 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009138 }
Jiong Wangf910cef2018-05-02 16:17:17 -04009139 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009140 old_bpf_func = func[i]->bpf_func;
9141 tmp = bpf_int_jit_compile(func[i]);
9142 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
9143 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009144 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009145 goto out_free;
9146 }
9147 cond_resched();
9148 }
9149
9150 /* finally lock prog and jit images for all functions and
9151 * populate kallsysm
9152 */
Jiong Wangf910cef2018-05-02 16:17:17 -04009153 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009154 bpf_prog_lock_ro(func[i]);
9155 bpf_prog_kallsyms_add(func[i]);
9156 }
Daniel Borkmann7105e822017-12-20 13:42:57 +01009157
9158 /* Last step: make now unused interpreter insns from main
9159 * prog consistent for later dump requests, so they can
9160 * later look the same as if they were interpreted only.
9161 */
9162 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01009163 if (insn->code != (BPF_JMP | BPF_CALL) ||
9164 insn->src_reg != BPF_PSEUDO_CALL)
9165 continue;
9166 insn->off = env->insn_aux_data[i].call_imm;
9167 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +05309168 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +01009169 }
9170
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009171 prog->jited = 1;
9172 prog->bpf_func = func[0]->bpf_func;
9173 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -04009174 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009175 bpf_prog_free_unused_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009176 return 0;
9177out_free:
Jiong Wangf910cef2018-05-02 16:17:17 -04009178 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009179 if (func[i])
9180 bpf_jit_free(func[i]);
9181 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009182out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009183 /* cleanup main prog to be interpreted */
9184 prog->jit_requested = 0;
9185 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9186 if (insn->code != (BPF_JMP | BPF_CALL) ||
9187 insn->src_reg != BPF_PSEUDO_CALL)
9188 continue;
9189 insn->off = 0;
9190 insn->imm = env->insn_aux_data[i].call_imm;
9191 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009192 bpf_prog_free_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009193 return err;
9194}
9195
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009196static int fixup_call_args(struct bpf_verifier_env *env)
9197{
David S. Miller19d28fb2018-01-11 21:27:54 -05009198#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009199 struct bpf_prog *prog = env->prog;
9200 struct bpf_insn *insn = prog->insnsi;
9201 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -05009202#endif
Quentin Monnete4052d02018-10-07 12:56:58 +01009203 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009204
Quentin Monnete4052d02018-10-07 12:56:58 +01009205 if (env->prog->jit_requested &&
9206 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -05009207 err = jit_subprogs(env);
9208 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -08009209 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +02009210 if (err == -EFAULT)
9211 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -05009212 }
9213#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009214 for (i = 0; i < prog->len; i++, insn++) {
9215 if (insn->code != (BPF_JMP | BPF_CALL) ||
9216 insn->src_reg != BPF_PSEUDO_CALL)
9217 continue;
9218 depth = get_callee_stack_depth(env, insn, i);
9219 if (depth < 0)
9220 return depth;
9221 bpf_patch_call_args(insn, depth);
9222 }
David S. Miller19d28fb2018-01-11 21:27:54 -05009223 err = 0;
9224#endif
9225 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08009226}
9227
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009228/* fixup insn->imm field of bpf_call instructions
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009229 * and inline eligible helpers as explicit sequence of BPF instructions
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009230 *
9231 * this function is called after eBPF program passed verification
9232 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009233static int fixup_bpf_calls(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009234{
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009235 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009236 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009237 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009238 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009239 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +02009240 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009241 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009242 struct bpf_insn insn_buf[16];
9243 struct bpf_prog *new_prog;
9244 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009245 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009246
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009247 for (i = 0; i < insn_cnt; i++, insn++) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +01009248 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
9249 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9250 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -08009251 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +01009252 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
9253 struct bpf_insn mask_and_div[] = {
9254 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9255 /* Rx div 0 -> 0 */
9256 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
9257 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
9258 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
9259 *insn,
9260 };
9261 struct bpf_insn mask_and_mod[] = {
9262 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9263 /* Rx mod 0 -> Rx */
9264 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
9265 *insn,
9266 };
9267 struct bpf_insn *patchlet;
9268
9269 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9270 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
9271 patchlet = mask_and_div + (is64 ? 1 : 0);
9272 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
9273 } else {
9274 patchlet = mask_and_mod + (is64 ? 1 : 0);
9275 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
9276 }
9277
9278 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -08009279 if (!new_prog)
9280 return -ENOMEM;
9281
9282 delta += cnt - 1;
9283 env->prog = prog = new_prog;
9284 insn = new_prog->insnsi + i + delta;
9285 continue;
9286 }
9287
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02009288 if (BPF_CLASS(insn->code) == BPF_LD &&
9289 (BPF_MODE(insn->code) == BPF_ABS ||
9290 BPF_MODE(insn->code) == BPF_IND)) {
9291 cnt = env->ops->gen_ld_abs(insn, insn_buf);
9292 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9293 verbose(env, "bpf verifier is misconfigured\n");
9294 return -EINVAL;
9295 }
9296
9297 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9298 if (!new_prog)
9299 return -ENOMEM;
9300
9301 delta += cnt - 1;
9302 env->prog = prog = new_prog;
9303 insn = new_prog->insnsi + i + delta;
9304 continue;
9305 }
9306
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009307 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
9308 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
9309 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
9310 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
9311 struct bpf_insn insn_buf[16];
9312 struct bpf_insn *patch = &insn_buf[0];
9313 bool issrc, isneg;
9314 u32 off_reg;
9315
9316 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +01009317 if (!aux->alu_state ||
9318 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009319 continue;
9320
9321 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
9322 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
9323 BPF_ALU_SANITIZE_SRC;
9324
9325 off_reg = issrc ? insn->src_reg : insn->dst_reg;
9326 if (isneg)
9327 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9328 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
9329 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
9330 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
9331 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
9332 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
9333 if (issrc) {
9334 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
9335 off_reg);
9336 insn->src_reg = BPF_REG_AX;
9337 } else {
9338 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
9339 BPF_REG_AX);
9340 }
9341 if (isneg)
9342 insn->code = insn->code == code_add ?
9343 code_sub : code_add;
9344 *patch++ = *insn;
9345 if (issrc && isneg)
9346 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9347 cnt = patch - insn_buf;
9348
9349 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9350 if (!new_prog)
9351 return -ENOMEM;
9352
9353 delta += cnt - 1;
9354 env->prog = prog = new_prog;
9355 insn = new_prog->insnsi + i + delta;
9356 continue;
9357 }
9358
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009359 if (insn->code != (BPF_JMP | BPF_CALL))
9360 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009361 if (insn->src_reg == BPF_PSEUDO_CALL)
9362 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009363
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009364 if (insn->imm == BPF_FUNC_get_route_realm)
9365 prog->dst_needed = 1;
9366 if (insn->imm == BPF_FUNC_get_prandom_u32)
9367 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -05009368 if (insn->imm == BPF_FUNC_override_return)
9369 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009370 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -04009371 /* If we tail call into other programs, we
9372 * cannot make any assumptions since they can
9373 * be replaced dynamically during runtime in
9374 * the program array.
9375 */
9376 prog->cb_access = 1;
Alexei Starovoitov80a58d02017-05-30 13:31:30 -07009377 env->prog->aux->stack_depth = MAX_BPF_STACK;
Jiong Wange6478152018-11-08 04:08:42 -05009378 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -04009379
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009380 /* mark bpf_tail_call as different opcode to avoid
9381 * conditional branch in the interpeter for every normal
9382 * call and to prevent accidental JITing by JIT compiler
9383 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009384 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009385 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -07009386 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -08009387
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009388 aux = &env->insn_aux_data[i + delta];
Daniel Borkmanncc52d912019-12-19 22:19:50 +01009389 if (env->allow_ptr_leaks && !expect_blinding &&
9390 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009391 !bpf_map_key_poisoned(aux) &&
9392 !bpf_map_ptr_poisoned(aux) &&
9393 !bpf_map_ptr_unpriv(aux)) {
9394 struct bpf_jit_poke_descriptor desc = {
9395 .reason = BPF_POKE_REASON_TAIL_CALL,
9396 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
9397 .tail_call.key = bpf_map_key_immediate(aux),
9398 };
9399
9400 ret = bpf_jit_add_poke_descriptor(prog, &desc);
9401 if (ret < 0) {
9402 verbose(env, "adding tail call poke descriptor failed\n");
9403 return ret;
9404 }
9405
9406 insn->imm = ret + 1;
9407 continue;
9408 }
9409
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009410 if (!bpf_map_ptr_unpriv(aux))
9411 continue;
9412
Alexei Starovoitovb2157392018-01-07 17:33:02 -08009413 /* instead of changing every JIT dealing with tail_call
9414 * emit two extra insns:
9415 * if (index >= max_entries) goto out;
9416 * index &= array->index_mask;
9417 * to avoid out-of-bounds cpu speculation
9418 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009419 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +00009420 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -08009421 return -EINVAL;
9422 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009423
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009424 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -08009425 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
9426 map_ptr->max_entries, 2);
9427 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
9428 container_of(map_ptr,
9429 struct bpf_array,
9430 map)->index_mask);
9431 insn_buf[2] = *insn;
9432 cnt = 3;
9433 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9434 if (!new_prog)
9435 return -ENOMEM;
9436
9437 delta += cnt - 1;
9438 env->prog = prog = new_prog;
9439 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009440 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009441 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009442
Daniel Borkmann89c63072017-08-19 03:12:45 +02009443 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +02009444 * and other inlining handlers are currently limited to 64 bit
9445 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +02009446 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -08009447 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02009448 (insn->imm == BPF_FUNC_map_lookup_elem ||
9449 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +02009450 insn->imm == BPF_FUNC_map_delete_elem ||
9451 insn->imm == BPF_FUNC_map_push_elem ||
9452 insn->imm == BPF_FUNC_map_pop_elem ||
9453 insn->imm == BPF_FUNC_map_peek_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02009454 aux = &env->insn_aux_data[i + delta];
9455 if (bpf_map_ptr_poisoned(aux))
9456 goto patch_call_imm;
9457
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009458 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +02009459 ops = map_ptr->ops;
9460 if (insn->imm == BPF_FUNC_map_lookup_elem &&
9461 ops->map_gen_lookup) {
9462 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
9463 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9464 verbose(env, "bpf verifier is misconfigured\n");
9465 return -EINVAL;
9466 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009467
Daniel Borkmann09772d92018-06-02 23:06:35 +02009468 new_prog = bpf_patch_insn_data(env, i + delta,
9469 insn_buf, cnt);
9470 if (!new_prog)
9471 return -ENOMEM;
9472
9473 delta += cnt - 1;
9474 env->prog = prog = new_prog;
9475 insn = new_prog->insnsi + i + delta;
9476 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009477 }
9478
Daniel Borkmann09772d92018-06-02 23:06:35 +02009479 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
9480 (void *(*)(struct bpf_map *map, void *key))NULL));
9481 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
9482 (int (*)(struct bpf_map *map, void *key))NULL));
9483 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
9484 (int (*)(struct bpf_map *map, void *key, void *value,
9485 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +02009486 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
9487 (int (*)(struct bpf_map *map, void *value,
9488 u64 flags))NULL));
9489 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
9490 (int (*)(struct bpf_map *map, void *value))NULL));
9491 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
9492 (int (*)(struct bpf_map *map, void *value))NULL));
9493
Daniel Borkmann09772d92018-06-02 23:06:35 +02009494 switch (insn->imm) {
9495 case BPF_FUNC_map_lookup_elem:
9496 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
9497 __bpf_call_base;
9498 continue;
9499 case BPF_FUNC_map_update_elem:
9500 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
9501 __bpf_call_base;
9502 continue;
9503 case BPF_FUNC_map_delete_elem:
9504 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
9505 __bpf_call_base;
9506 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +02009507 case BPF_FUNC_map_push_elem:
9508 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
9509 __bpf_call_base;
9510 continue;
9511 case BPF_FUNC_map_pop_elem:
9512 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
9513 __bpf_call_base;
9514 continue;
9515 case BPF_FUNC_map_peek_elem:
9516 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
9517 __bpf_call_base;
9518 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +02009519 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009520
Daniel Borkmann09772d92018-06-02 23:06:35 +02009521 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009522 }
9523
Martin KaFai Lau5576b992020-01-22 15:36:46 -08009524 if (prog->jit_requested && BITS_PER_LONG == 64 &&
9525 insn->imm == BPF_FUNC_jiffies64) {
9526 struct bpf_insn ld_jiffies_addr[2] = {
9527 BPF_LD_IMM64(BPF_REG_0,
9528 (unsigned long)&jiffies),
9529 };
9530
9531 insn_buf[0] = ld_jiffies_addr[0];
9532 insn_buf[1] = ld_jiffies_addr[1];
9533 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
9534 BPF_REG_0, 0);
9535 cnt = 3;
9536
9537 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
9538 cnt);
9539 if (!new_prog)
9540 return -ENOMEM;
9541
9542 delta += cnt - 1;
9543 env->prog = prog = new_prog;
9544 insn = new_prog->insnsi + i + delta;
9545 continue;
9546 }
9547
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -07009548patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -07009549 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009550 /* all functions that have prototype and verifier allowed
9551 * programs to call them, must be real in-kernel functions
9552 */
9553 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009554 verbose(env,
9555 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009556 func_id_name(insn->imm), insn->imm);
9557 return -EFAULT;
9558 }
9559 insn->imm = fn->func - __bpf_call_base;
9560 }
9561
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01009562 /* Since poke tab is now finalized, publish aux to tracker. */
9563 for (i = 0; i < prog->aux->size_poke_tab; i++) {
9564 map_ptr = prog->aux->poke_tab[i].tail_call.map;
9565 if (!map_ptr->ops->map_poke_track ||
9566 !map_ptr->ops->map_poke_untrack ||
9567 !map_ptr->ops->map_poke_run) {
9568 verbose(env, "bpf verifier is misconfigured\n");
9569 return -EINVAL;
9570 }
9571
9572 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
9573 if (ret < 0) {
9574 verbose(env, "tracking tail call prog failed\n");
9575 return ret;
9576 }
9577 }
9578
Alexei Starovoitov79741b32017-03-15 18:26:40 -07009579 return 0;
9580}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -07009581
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009582static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009583{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009584 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009585 int i;
9586
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009587 sl = env->free_list;
9588 while (sl) {
9589 sln = sl->next;
9590 free_verifier_state(&sl->state, false);
9591 kfree(sl);
9592 sl = sln;
9593 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009594 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009595
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009596 if (!env->explored_states)
9597 return;
9598
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009599 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009600 sl = env->explored_states[i];
9601
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009602 while (sl) {
9603 sln = sl->next;
9604 free_verifier_state(&sl->state, false);
9605 kfree(sl);
9606 sl = sln;
9607 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009608 env->explored_states[i] = NULL;
9609 }
9610}
9611
9612/* The verifier is using insn_aux_data[] to store temporary data during
9613 * verification and to store information for passes that run after the
9614 * verification like dead code sanitization. do_check_common() for subprogram N
9615 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
9616 * temporary data after do_check_common() finds that subprogram N cannot be
9617 * verified independently. pass_cnt counts the number of times
9618 * do_check_common() was run and insn->aux->seen tells the pass number
9619 * insn_aux_data was touched. These variables are compared to clear temporary
9620 * data from failed pass. For testing and experiments do_check_common() can be
9621 * run multiple times even when prior attempt to verify is unsuccessful.
9622 */
9623static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
9624{
9625 struct bpf_insn *insn = env->prog->insnsi;
9626 struct bpf_insn_aux_data *aux;
9627 int i, class;
9628
9629 for (i = 0; i < env->prog->len; i++) {
9630 class = BPF_CLASS(insn[i].code);
9631 if (class != BPF_LDX && class != BPF_STX)
9632 continue;
9633 aux = &env->insn_aux_data[i];
9634 if (aux->seen != env->pass_cnt)
9635 continue;
9636 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
9637 }
9638}
9639
9640static int do_check_common(struct bpf_verifier_env *env, int subprog)
9641{
9642 struct bpf_verifier_state *state;
9643 struct bpf_reg_state *regs;
9644 int ret, i;
9645
9646 env->prev_linfo = NULL;
9647 env->pass_cnt++;
9648
9649 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
9650 if (!state)
9651 return -ENOMEM;
9652 state->curframe = 0;
9653 state->speculative = false;
9654 state->branches = 1;
9655 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
9656 if (!state->frame[0]) {
9657 kfree(state);
9658 return -ENOMEM;
9659 }
9660 env->cur_state = state;
9661 init_func_state(env, state->frame[0],
9662 BPF_MAIN_FUNC /* callsite */,
9663 0 /* frameno */,
9664 subprog);
9665
9666 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -08009667 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009668 ret = btf_prepare_func_args(env, subprog, regs);
9669 if (ret)
9670 goto out;
9671 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
9672 if (regs[i].type == PTR_TO_CTX)
9673 mark_reg_known_zero(env, regs, i);
9674 else if (regs[i].type == SCALAR_VALUE)
9675 mark_reg_unknown(env, regs, i);
9676 }
9677 } else {
9678 /* 1st arg to a function */
9679 regs[BPF_REG_1].type = PTR_TO_CTX;
9680 mark_reg_known_zero(env, regs, BPF_REG_1);
9681 ret = btf_check_func_arg_match(env, subprog, regs);
9682 if (ret == -EFAULT)
9683 /* unlikely verifier bug. abort.
9684 * ret == 0 and ret < 0 are sadly acceptable for
9685 * main() function due to backward compatibility.
9686 * Like socket filter program may be written as:
9687 * int bpf_prog(struct pt_regs *ctx)
9688 * and never dereference that ctx in the program.
9689 * 'struct pt_regs' is a type mismatch for socket
9690 * filter that should be using 'struct __sk_buff'.
9691 */
9692 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009693 }
9694
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009695 ret = do_check(env);
9696out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -08009697 /* check for NULL is necessary, since cur_state can be freed inside
9698 * do_check() under memory pressure.
9699 */
9700 if (env->cur_state) {
9701 free_verifier_state(env->cur_state, true);
9702 env->cur_state = NULL;
9703 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009704 while (!pop_stack(env, NULL, NULL));
9705 free_states(env);
9706 if (ret)
9707 /* clean aux data in case subprog was rejected */
9708 sanitize_insn_aux_data(env);
9709 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009710}
9711
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009712/* Verify all global functions in a BPF program one by one based on their BTF.
9713 * All global functions must pass verification. Otherwise the whole program is rejected.
9714 * Consider:
9715 * int bar(int);
9716 * int foo(int f)
9717 * {
9718 * return bar(f);
9719 * }
9720 * int bar(int b)
9721 * {
9722 * ...
9723 * }
9724 * foo() will be verified first for R1=any_scalar_value. During verification it
9725 * will be assumed that bar() already verified successfully and call to bar()
9726 * from foo() will be checked for type match only. Later bar() will be verified
9727 * independently to check that it's safe for R1=any_scalar_value.
9728 */
9729static int do_check_subprogs(struct bpf_verifier_env *env)
9730{
9731 struct bpf_prog_aux *aux = env->prog->aux;
9732 int i, ret;
9733
9734 if (!aux->func_info)
9735 return 0;
9736
9737 for (i = 1; i < env->subprog_cnt; i++) {
9738 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
9739 continue;
9740 env->insn_idx = env->subprog_info[i].start;
9741 WARN_ON_ONCE(env->insn_idx == 0);
9742 ret = do_check_common(env, i);
9743 if (ret) {
9744 return ret;
9745 } else if (env->log.level & BPF_LOG_LEVEL) {
9746 verbose(env,
9747 "Func#%d is safe for any args that match its prototype\n",
9748 i);
9749 }
9750 }
9751 return 0;
9752}
9753
9754static int do_check_main(struct bpf_verifier_env *env)
9755{
9756 int ret;
9757
9758 env->insn_idx = 0;
9759 ret = do_check_common(env, 0);
9760 if (!ret)
9761 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
9762 return ret;
9763}
9764
9765
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009766static void print_verification_stats(struct bpf_verifier_env *env)
9767{
9768 int i;
9769
9770 if (env->log.level & BPF_LOG_STATS) {
9771 verbose(env, "verification time %lld usec\n",
9772 div_u64(env->verification_time, 1000));
9773 verbose(env, "stack depth ");
9774 for (i = 0; i < env->subprog_cnt; i++) {
9775 u32 depth = env->subprog_info[i].stack_depth;
9776
9777 verbose(env, "%d", depth);
9778 if (i + 1 < env->subprog_cnt)
9779 verbose(env, "+");
9780 }
9781 verbose(env, "\n");
9782 }
9783 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
9784 "total_states %d peak_states %d mark_read %d\n",
9785 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
9786 env->max_states_per_insn, env->total_states,
9787 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -07009788}
9789
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009790static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
9791{
9792 const struct btf_type *t, *func_proto;
9793 const struct bpf_struct_ops *st_ops;
9794 const struct btf_member *member;
9795 struct bpf_prog *prog = env->prog;
9796 u32 btf_id, member_idx;
9797 const char *mname;
9798
9799 btf_id = prog->aux->attach_btf_id;
9800 st_ops = bpf_struct_ops_find(btf_id);
9801 if (!st_ops) {
9802 verbose(env, "attach_btf_id %u is not a supported struct\n",
9803 btf_id);
9804 return -ENOTSUPP;
9805 }
9806
9807 t = st_ops->type;
9808 member_idx = prog->expected_attach_type;
9809 if (member_idx >= btf_type_vlen(t)) {
9810 verbose(env, "attach to invalid member idx %u of struct %s\n",
9811 member_idx, st_ops->name);
9812 return -EINVAL;
9813 }
9814
9815 member = &btf_type_member(t)[member_idx];
9816 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
9817 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
9818 NULL);
9819 if (!func_proto) {
9820 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
9821 mname, member_idx, st_ops->name);
9822 return -EINVAL;
9823 }
9824
9825 if (st_ops->check_member) {
9826 int err = st_ops->check_member(t, member);
9827
9828 if (err) {
9829 verbose(env, "attach to unsupported member %s of struct %s\n",
9830 mname, st_ops->name);
9831 return err;
9832 }
9833 }
9834
9835 prog->aux->attach_func_proto = func_proto;
9836 prog->aux->attach_func_name = mname;
9837 env->ops = st_ops->verifier_ops;
9838
9839 return 0;
9840}
KP Singh6ba43b72020-03-04 20:18:50 +01009841#define SECURITY_PREFIX "security_"
9842
9843static int check_attach_modify_return(struct bpf_verifier_env *env)
9844{
9845 struct bpf_prog *prog = env->prog;
9846 unsigned long addr = (unsigned long) prog->aux->trampoline->func.addr;
9847
KP Singh6ba43b72020-03-04 20:18:50 +01009848 /* This is expected to be cleaned up in the future with the KRSI effort
9849 * introducing the LSM_HOOK macro for cleaning up lsm_hooks.h.
9850 */
KP Singh69191752020-03-05 21:49:55 +01009851 if (within_error_injection_list(addr) ||
9852 !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
9853 sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +01009854 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +01009855
9856 verbose(env, "fmod_ret attach_btf_id %u (%s) is not modifiable\n",
9857 prog->aux->attach_btf_id, prog->aux->attach_func_name);
9858
9859 return -EINVAL;
9860}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009861
Martin KaFai Lau38207292019-10-24 17:18:11 -07009862static int check_attach_btf_id(struct bpf_verifier_env *env)
9863{
9864 struct bpf_prog *prog = env->prog;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -08009865 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009866 struct bpf_prog *tgt_prog = prog->aux->linked_prog;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009867 u32 btf_id = prog->aux->attach_btf_id;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009868 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009869 int ret = 0, subprog = -1, i;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -08009870 struct bpf_trampoline *tr;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009871 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009872 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009873 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009874 struct btf *btf;
Alexei Starovoitovfec56f52019-11-14 10:57:04 -08009875 long addr;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009876 u64 key;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009877
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009878 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
9879 return check_struct_ops_btf_id(env);
9880
KP Singh9e4e01d2020-03-29 01:43:52 +01009881 if (prog->type != BPF_PROG_TYPE_TRACING &&
9882 prog->type != BPF_PROG_TYPE_LSM &&
9883 !prog_extension)
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009884 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -07009885
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009886 if (!btf_id) {
9887 verbose(env, "Tracing programs must provide btf_id\n");
9888 return -EINVAL;
9889 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009890 btf = bpf_prog_get_target_btf(prog);
9891 if (!btf) {
9892 verbose(env,
9893 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
9894 return -EINVAL;
9895 }
9896 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009897 if (!t) {
9898 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
9899 return -EINVAL;
9900 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009901 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009902 if (!tname) {
9903 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
9904 return -EINVAL;
9905 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009906 if (tgt_prog) {
9907 struct bpf_prog_aux *aux = tgt_prog->aux;
9908
9909 for (i = 0; i < aux->func_info_cnt; i++)
9910 if (aux->func_info[i].type_id == btf_id) {
9911 subprog = i;
9912 break;
9913 }
9914 if (subprog == -1) {
9915 verbose(env, "Subprog %s doesn't exist\n", tname);
9916 return -EINVAL;
9917 }
9918 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -08009919 if (prog_extension) {
9920 if (conservative) {
9921 verbose(env,
9922 "Cannot replace static functions\n");
9923 return -EINVAL;
9924 }
9925 if (!prog->jit_requested) {
9926 verbose(env,
9927 "Extension programs should be JITed\n");
9928 return -EINVAL;
9929 }
9930 env->ops = bpf_verifier_ops[tgt_prog->type];
9931 }
9932 if (!tgt_prog->jited) {
9933 verbose(env, "Can attach to only JITed progs\n");
9934 return -EINVAL;
9935 }
9936 if (tgt_prog->type == prog->type) {
9937 /* Cannot fentry/fexit another fentry/fexit program.
9938 * Cannot attach program extension to another extension.
9939 * It's ok to attach fentry/fexit to extension program.
9940 */
9941 verbose(env, "Cannot recursively attach\n");
9942 return -EINVAL;
9943 }
9944 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
9945 prog_extension &&
9946 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
9947 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
9948 /* Program extensions can extend all program types
9949 * except fentry/fexit. The reason is the following.
9950 * The fentry/fexit programs are used for performance
9951 * analysis, stats and can be attached to any program
9952 * type except themselves. When extension program is
9953 * replacing XDP function it is necessary to allow
9954 * performance analysis of all functions. Both original
9955 * XDP program and its program extension. Hence
9956 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
9957 * allowed. If extending of fentry/fexit was allowed it
9958 * would be possible to create long call chain
9959 * fentry->extension->fentry->extension beyond
9960 * reasonable stack size. Hence extending fentry is not
9961 * allowed.
9962 */
9963 verbose(env, "Cannot extend fentry/fexit\n");
9964 return -EINVAL;
9965 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009966 key = ((u64)aux->id) << 32 | btf_id;
9967 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -08009968 if (prog_extension) {
9969 verbose(env, "Cannot replace kernel functions\n");
9970 return -EINVAL;
9971 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009972 key = btf_id;
9973 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009974
9975 switch (prog->expected_attach_type) {
9976 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009977 if (tgt_prog) {
9978 verbose(env,
9979 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
9980 return -EINVAL;
9981 }
Martin KaFai Lau38207292019-10-24 17:18:11 -07009982 if (!btf_type_is_typedef(t)) {
9983 verbose(env, "attach_btf_id %u is not a typedef\n",
9984 btf_id);
9985 return -EINVAL;
9986 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -07009987 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Martin KaFai Lau38207292019-10-24 17:18:11 -07009988 verbose(env, "attach_btf_id %u points to wrong type name %s\n",
9989 btf_id, tname);
9990 return -EINVAL;
9991 }
9992 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009993 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -07009994 if (!btf_type_is_ptr(t))
9995 /* should never happen in valid vmlinux build */
9996 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -08009997 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -07009998 if (!btf_type_is_func_proto(t))
9999 /* should never happen in valid vmlinux build */
10000 return -EINVAL;
10001
10002 /* remember two read only pointers that are valid for
10003 * the life time of the kernel
10004 */
10005 prog->aux->attach_func_name = tname;
10006 prog->aux->attach_func_proto = t;
10007 prog->aux->attach_btf_trace = true;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070010008 return 0;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080010009 default:
10010 if (!prog_extension)
10011 return -EINVAL;
10012 /* fallthrough */
KP Singhae240822020-03-04 20:18:49 +010010013 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010010014 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010015 case BPF_TRACE_FENTRY:
10016 case BPF_TRACE_FEXIT:
KP Singh9e4e01d2020-03-29 01:43:52 +010010017 prog->aux->attach_func_name = tname;
10018 if (prog->type == BPF_PROG_TYPE_LSM) {
10019 ret = bpf_lsm_verify_prog(&env->log, prog);
10020 if (ret < 0)
10021 return ret;
10022 }
10023
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010024 if (!btf_type_is_func(t)) {
10025 verbose(env, "attach_btf_id %u is not a function\n",
10026 btf_id);
10027 return -EINVAL;
10028 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080010029 if (prog_extension &&
10030 btf_check_type_match(env, prog, btf, t))
10031 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010032 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010033 if (!btf_type_is_func_proto(t))
10034 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010035 tr = bpf_trampoline_lookup(key);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010036 if (!tr)
10037 return -ENOMEM;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010038 /* t is either vmlinux type or another program's type */
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010039 prog->aux->attach_func_proto = t;
10040 mutex_lock(&tr->mutex);
10041 if (tr->func.addr) {
10042 prog->aux->trampoline = tr;
10043 goto out;
10044 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010045 if (tgt_prog && conservative) {
10046 prog->aux->attach_func_proto = NULL;
10047 t = NULL;
10048 }
10049 ret = btf_distill_func_proto(&env->log, btf, t,
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010050 tname, &tr->func.model);
10051 if (ret < 0)
10052 goto out;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010053 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080010054 if (subprog == 0)
10055 addr = (long) tgt_prog->bpf_func;
10056 else
10057 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080010058 } else {
10059 addr = kallsyms_lookup_name(tname);
10060 if (!addr) {
10061 verbose(env,
10062 "The address of function %s cannot be found\n",
10063 tname);
10064 ret = -ENOENT;
10065 goto out;
10066 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010067 }
10068 tr->func.addr = (void *)addr;
10069 prog->aux->trampoline = tr;
KP Singh6ba43b72020-03-04 20:18:50 +010010070
10071 if (prog->expected_attach_type == BPF_MODIFY_RETURN)
10072 ret = check_attach_modify_return(env);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080010073out:
10074 mutex_unlock(&tr->mutex);
10075 if (ret)
10076 bpf_trampoline_put(tr);
10077 return ret;
Martin KaFai Lau38207292019-10-24 17:18:11 -070010078 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070010079}
10080
Yonghong Song838e9692018-11-19 15:29:11 -080010081int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
10082 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070010083{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010084 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010085 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070010086 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080010087 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010088 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070010089
Arnd Bergmanneba0c922017-11-02 12:05:52 +010010090 /* no program is valid */
10091 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
10092 return -EINVAL;
10093
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010094 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010095 * allocate/free it every time bpf_check() is called
10096 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010097 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010098 if (!env)
10099 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010100 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010101
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080010102 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070010103 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080010104 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010105 ret = -ENOMEM;
10106 if (!env->insn_aux_data)
10107 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080010108 for (i = 0; i < len; i++)
10109 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010110 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070010111 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070010112 is_priv = capable(CAP_SYS_ADMIN);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010113
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070010114 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
10115 mutex_lock(&bpf_verifier_lock);
10116 if (!btf_vmlinux)
10117 btf_vmlinux = btf_parse_vmlinux();
10118 mutex_unlock(&bpf_verifier_lock);
10119 }
10120
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010121 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070010122 if (!is_priv)
10123 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010124
10125 if (attr->log_level || attr->log_buf || attr->log_size) {
10126 /* user requested verbose verifier output
10127 * and supplied buffer to store the verification trace
10128 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070010129 log->level = attr->log_level;
10130 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
10131 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010132
10133 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070010134 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070010135 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010136 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010137 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010138 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020010139
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070010140 if (IS_ERR(btf_vmlinux)) {
10141 /* Either gcc or pahole or kernel are broken. */
10142 verbose(env, "in-kernel BTF is malformed\n");
10143 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070010144 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070010145 }
10146
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020010147 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
10148 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070010149 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080010150 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
10151 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010152
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010153 env->allow_ptr_leaks = is_priv;
10154
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070010155 if (is_priv)
10156 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
10157
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010158 ret = replace_map_fd_with_map_ptr(env);
10159 if (ret < 0)
10160 goto skip_full_check;
10161
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070010162 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Quentin Monneta40a2632018-11-09 13:03:31 +000010163 ret = bpf_prog_offload_verifier_prep(env->prog);
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070010164 if (ret)
10165 goto skip_full_check;
10166 }
10167
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010168 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010169 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010170 GFP_USER);
10171 ret = -ENOMEM;
10172 if (!env->explored_states)
10173 goto skip_full_check;
10174
Martin KaFai Laud9762e82018-12-13 10:41:48 -080010175 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010176 if (ret < 0)
10177 goto skip_full_check;
10178
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010179 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080010180 if (ret < 0)
10181 goto skip_full_check;
10182
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080010183 ret = check_attach_btf_id(env);
10184 if (ret)
10185 goto skip_full_check;
10186
Martin KaFai Laud9762e82018-12-13 10:41:48 -080010187 ret = check_cfg(env);
10188 if (ret < 0)
10189 goto skip_full_check;
10190
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010191 ret = do_check_subprogs(env);
10192 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010193
Quentin Monnetc941ce92018-10-07 12:56:47 +010010194 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
10195 ret = bpf_prog_offload_finalize(env);
10196
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010197skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010198 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010199
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010200 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080010201 ret = check_max_stack_depth(env);
10202
Jakub Kicinski9b38c402018-12-19 22:13:06 -080010203 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010204 if (is_priv) {
10205 if (ret == 0)
10206 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080010207 if (ret == 0)
10208 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080010209 if (ret == 0)
10210 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080010211 } else {
10212 if (ret == 0)
10213 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010214 }
10215
Jakub Kicinski9b38c402018-12-19 22:13:06 -080010216 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010217 /* program is valid, convert *(u32*)(ctx + off) accesses */
10218 ret = convert_ctx_accesses(env);
10219
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010220 if (ret == 0)
Alexei Starovoitov79741b32017-03-15 18:26:40 -070010221 ret = fixup_bpf_calls(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070010222
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010223 /* do 32-bit optimization after insn patching has done so those patched
10224 * insns could be handled correctly.
10225 */
Jiong Wangd6c23082019-05-24 23:25:18 +010010226 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
10227 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
10228 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
10229 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010230 }
10231
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080010232 if (ret == 0)
10233 ret = fixup_call_args(env);
10234
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010235 env->verification_time = ktime_get_ns() - start_time;
10236 print_verification_stats(env);
10237
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010238 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010239 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010240 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010241 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010242 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010243 }
10244
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010245 if (ret == 0 && env->used_map_cnt) {
10246 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010247 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
10248 sizeof(env->used_maps[0]),
10249 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010250
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010251 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010252 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010253 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010254 }
10255
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010256 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010257 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010258 env->prog->aux->used_map_cnt = env->used_map_cnt;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010259
10260 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
10261 * bpf_ld_imm64 instructions
10262 */
10263 convert_pseudo_ld_imm64(env);
10264 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070010265
Yonghong Songba64e7d2018-11-24 23:20:44 -080010266 if (ret == 0)
10267 adjust_btf_func(env);
10268
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070010269err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010270 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010271 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070010272 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010273 */
10274 release_maps(env);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010275 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010276err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070010277 if (!is_priv)
10278 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010279 vfree(env->insn_aux_data);
10280err_free_env:
10281 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070010282 return ret;
10283}