]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - kernel/bpf/verifier.c
Merge branch 'bpf-jmp-seq-limit'
[mirror_ubuntu-hirsute-kernel.git] / kernel / bpf / verifier.c
CommitLineData
51580e79 1/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 2 * Copyright (c) 2016 Facebook
fd978bf7 3 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
51580e79
AS
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 2 of the GNU General Public
7 * License as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 */
838e9690 14#include <uapi/linux/btf.h>
51580e79
AS
15#include <linux/kernel.h>
16#include <linux/types.h>
17#include <linux/slab.h>
18#include <linux/bpf.h>
838e9690 19#include <linux/btf.h>
58e2af8b 20#include <linux/bpf_verifier.h>
51580e79
AS
21#include <linux/filter.h>
22#include <net/netlink.h>
23#include <linux/file.h>
24#include <linux/vmalloc.h>
ebb676da 25#include <linux/stringify.h>
cc8b0b92
AS
26#include <linux/bsearch.h>
27#include <linux/sort.h>
c195651e 28#include <linux/perf_event.h>
d9762e84 29#include <linux/ctype.h>
51580e79 30
f4ac7e0b
JK
31#include "disasm.h"
32
00176a34
JK
33static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34#define BPF_PROG_TYPE(_id, _name) \
35 [_id] = & _name ## _verifier_ops,
36#define BPF_MAP_TYPE(_id, _ops)
37#include <linux/bpf_types.h>
38#undef BPF_PROG_TYPE
39#undef BPF_MAP_TYPE
40};
41
51580e79
AS
42/* bpf_check() is a static code analyzer that walks eBPF program
43 * instruction by instruction and updates register/stack state.
44 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
45 *
46 * The first pass is depth-first-search to check that the program is a DAG.
47 * It rejects the following programs:
48 * - larger than BPF_MAXINSNS insns
49 * - if loop is present (detected via back-edge)
50 * - unreachable insns exist (shouldn't be a forest. program = one function)
51 * - out of bounds or malformed jumps
52 * The second pass is all possible path descent from the 1st insn.
53 * Since it's analyzing all pathes through the program, the length of the
eba38a96 54 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
55 * insn is less then 4K, but there are too many branches that change stack/regs.
56 * Number of 'branches to be analyzed' is limited to 1k
57 *
58 * On entry to each instruction, each register has a type, and the instruction
59 * changes the types of the registers depending on instruction semantics.
60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
61 * copied to R1.
62 *
63 * All registers are 64-bit.
64 * R0 - return register
65 * R1-R5 argument passing registers
66 * R6-R9 callee saved registers
67 * R10 - frame pointer read-only
68 *
69 * At the start of BPF program the register R1 contains a pointer to bpf_context
70 * and has type PTR_TO_CTX.
71 *
72 * Verifier tracks arithmetic operations on pointers in case:
73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
75 * 1st insn copies R10 (which has FRAME_PTR) type into R1
76 * and 2nd arithmetic instruction is pattern matched to recognize
77 * that it wants to construct a pointer to some element within stack.
78 * So after 2nd insn, the register R1 has type PTR_TO_STACK
79 * (and -20 constant is saved for further stack bounds checking).
80 * Meaning that this reg is a pointer to stack plus known immediate constant.
81 *
f1174f77 82 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 83 * means the register has some value, but it's not a valid pointer.
f1174f77 84 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
85 *
86 * When verifier sees load or store instructions the type of base register
c64b7983
JS
87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
88 * four pointer types recognized by check_mem_access() function.
51580e79
AS
89 *
90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
91 * and the range of [ptr, ptr + map's value_size) is accessible.
92 *
93 * registers used to pass values to function calls are checked against
94 * function argument constraints.
95 *
96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
97 * It means that the register type passed to this function must be
98 * PTR_TO_STACK and it will be used inside the function as
99 * 'pointer to map element key'
100 *
101 * For example the argument constraints for bpf_map_lookup_elem():
102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
103 * .arg1_type = ARG_CONST_MAP_PTR,
104 * .arg2_type = ARG_PTR_TO_MAP_KEY,
105 *
106 * ret_type says that this function returns 'pointer to map elem value or null'
107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
108 * 2nd argument should be a pointer to stack, which will be used inside
109 * the helper function as a pointer to map element key.
110 *
111 * On the kernel side the helper function looks like:
112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
113 * {
114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
115 * void *key = (void *) (unsigned long) r2;
116 * void *value;
117 *
118 * here kernel can access 'key' and 'map' pointers safely, knowing that
119 * [key, key + map->key_size) bytes are valid and were initialized on
120 * the stack of eBPF program.
121 * }
122 *
123 * Corresponding eBPF program may look like:
124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
128 * here verifier looks at prototype of map_lookup_elem() and sees:
129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
131 *
132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
134 * and were initialized prior to this call.
135 * If it's ok, then verifier allows this BPF_CALL insn and looks at
136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
138 * returns ether pointer to map value or NULL.
139 *
140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
141 * insn, the register holding that pointer in the true branch changes state to
142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
143 * branch. See check_cond_jmp_op().
144 *
145 * After the call R0 is set to return type of the function and registers R1-R5
146 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
147 *
148 * The following reference types represent a potential reference to a kernel
149 * resource which, after first being allocated, must be checked and freed by
150 * the BPF program:
151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
152 *
153 * When the verifier sees a helper call return a reference type, it allocates a
154 * pointer id for the reference and stores it in the current function state.
155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
157 * passes through a NULL-check conditional. For the branch wherein the state is
158 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
159 *
160 * For each helper function that allocates a reference, such as
161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
162 * bpf_sk_release(). When a reference type passes into the release function,
163 * the verifier also releases the reference. If any unchecked or unreleased
164 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
165 */
166
17a52670 167/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 168struct bpf_verifier_stack_elem {
17a52670
AS
169 /* verifer state is 'st'
170 * before processing instruction 'insn_idx'
171 * and after processing instruction 'prev_insn_idx'
172 */
58e2af8b 173 struct bpf_verifier_state st;
17a52670
AS
174 int insn_idx;
175 int prev_insn_idx;
58e2af8b 176 struct bpf_verifier_stack_elem *next;
cbd35700
AS
177};
178
b285fcb7 179#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 180#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 181
c93552c4
DB
182#define BPF_MAP_PTR_UNPRIV 1UL
183#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
184 POISON_POINTER_DELTA))
185#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
186
187static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
188{
189 return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
190}
191
192static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
193{
194 return aux->map_state & BPF_MAP_PTR_UNPRIV;
195}
196
197static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
198 const struct bpf_map *map, bool unpriv)
199{
200 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
201 unpriv |= bpf_map_ptr_unpriv(aux);
202 aux->map_state = (unsigned long)map |
203 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
204}
fad73a1a 205
33ff9823
DB
206struct bpf_call_arg_meta {
207 struct bpf_map *map_ptr;
435faee1 208 bool raw_mode;
36bbef52 209 bool pkt_access;
435faee1
DB
210 int regno;
211 int access_size;
849fa506
YS
212 s64 msize_smax_value;
213 u64 msize_umax_value;
1b986589 214 int ref_obj_id;
d83525ca 215 int func_id;
33ff9823
DB
216};
217
cbd35700
AS
218static DEFINE_MUTEX(bpf_verifier_lock);
219
d9762e84
MKL
220static const struct bpf_line_info *
221find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
222{
223 const struct bpf_line_info *linfo;
224 const struct bpf_prog *prog;
225 u32 i, nr_linfo;
226
227 prog = env->prog;
228 nr_linfo = prog->aux->nr_linfo;
229
230 if (!nr_linfo || insn_off >= prog->len)
231 return NULL;
232
233 linfo = prog->aux->linfo;
234 for (i = 1; i < nr_linfo; i++)
235 if (insn_off < linfo[i].insn_off)
236 break;
237
238 return &linfo[i - 1];
239}
240
77d2e05a
MKL
241void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
242 va_list args)
cbd35700 243{
a2a7d570 244 unsigned int n;
cbd35700 245
a2a7d570 246 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
247
248 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
249 "verifier log line truncated - local buffer too short\n");
250
251 n = min(log->len_total - log->len_used - 1, n);
252 log->kbuf[n] = '\0';
253
254 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
255 log->len_used += n;
256 else
257 log->ubuf = NULL;
cbd35700 258}
abe08840
JO
259
260/* log_level controls verbosity level of eBPF verifier.
261 * bpf_verifier_log_write() is used to dump the verification trace to the log,
262 * so the user can figure out what's wrong with the program
430e68d1 263 */
abe08840
JO
264__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
265 const char *fmt, ...)
266{
267 va_list args;
268
77d2e05a
MKL
269 if (!bpf_verifier_log_needed(&env->log))
270 return;
271
abe08840 272 va_start(args, fmt);
77d2e05a 273 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
274 va_end(args);
275}
276EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
277
278__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
279{
77d2e05a 280 struct bpf_verifier_env *env = private_data;
abe08840
JO
281 va_list args;
282
77d2e05a
MKL
283 if (!bpf_verifier_log_needed(&env->log))
284 return;
285
abe08840 286 va_start(args, fmt);
77d2e05a 287 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
288 va_end(args);
289}
cbd35700 290
d9762e84
MKL
291static const char *ltrim(const char *s)
292{
293 while (isspace(*s))
294 s++;
295
296 return s;
297}
298
299__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
300 u32 insn_off,
301 const char *prefix_fmt, ...)
302{
303 const struct bpf_line_info *linfo;
304
305 if (!bpf_verifier_log_needed(&env->log))
306 return;
307
308 linfo = find_linfo(env, insn_off);
309 if (!linfo || linfo == env->prev_linfo)
310 return;
311
312 if (prefix_fmt) {
313 va_list args;
314
315 va_start(args, prefix_fmt);
316 bpf_verifier_vlog(&env->log, prefix_fmt, args);
317 va_end(args);
318 }
319
320 verbose(env, "%s\n",
321 ltrim(btf_name_by_offset(env->prog->aux->btf,
322 linfo->line_off)));
323
324 env->prev_linfo = linfo;
325}
326
de8f3a83
DB
327static bool type_is_pkt_pointer(enum bpf_reg_type type)
328{
329 return type == PTR_TO_PACKET ||
330 type == PTR_TO_PACKET_META;
331}
332
46f8bc92
MKL
333static bool type_is_sk_pointer(enum bpf_reg_type type)
334{
335 return type == PTR_TO_SOCKET ||
655a51e5
MKL
336 type == PTR_TO_SOCK_COMMON ||
337 type == PTR_TO_TCP_SOCK;
46f8bc92
MKL
338}
339
840b9615
JS
340static bool reg_type_may_be_null(enum bpf_reg_type type)
341{
fd978bf7 342 return type == PTR_TO_MAP_VALUE_OR_NULL ||
46f8bc92 343 type == PTR_TO_SOCKET_OR_NULL ||
655a51e5
MKL
344 type == PTR_TO_SOCK_COMMON_OR_NULL ||
345 type == PTR_TO_TCP_SOCK_OR_NULL;
fd978bf7
JS
346}
347
d83525ca
AS
348static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
349{
350 return reg->type == PTR_TO_MAP_VALUE &&
351 map_value_has_spin_lock(reg->map_ptr);
352}
353
cba368c1
MKL
354static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
355{
356 return type == PTR_TO_SOCKET ||
357 type == PTR_TO_SOCKET_OR_NULL ||
358 type == PTR_TO_TCP_SOCK ||
359 type == PTR_TO_TCP_SOCK_OR_NULL;
360}
361
1b986589 362static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 363{
1b986589 364 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
365}
366
367/* Determine whether the function releases some resources allocated by another
368 * function call. The first reference type argument will be assumed to be
369 * released by release_reference().
370 */
371static bool is_release_function(enum bpf_func_id func_id)
372{
6acc9b43 373 return func_id == BPF_FUNC_sk_release;
840b9615
JS
374}
375
46f8bc92
MKL
376static bool is_acquire_function(enum bpf_func_id func_id)
377{
378 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01
LB
379 func_id == BPF_FUNC_sk_lookup_udp ||
380 func_id == BPF_FUNC_skc_lookup_tcp;
46f8bc92
MKL
381}
382
1b986589
MKL
383static bool is_ptr_cast_function(enum bpf_func_id func_id)
384{
385 return func_id == BPF_FUNC_tcp_sock ||
386 func_id == BPF_FUNC_sk_fullsock;
387}
388
17a52670
AS
389/* string representation of 'enum bpf_reg_type' */
390static const char * const reg_type_str[] = {
391 [NOT_INIT] = "?",
f1174f77 392 [SCALAR_VALUE] = "inv",
17a52670
AS
393 [PTR_TO_CTX] = "ctx",
394 [CONST_PTR_TO_MAP] = "map_ptr",
395 [PTR_TO_MAP_VALUE] = "map_value",
396 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 397 [PTR_TO_STACK] = "fp",
969bf05e 398 [PTR_TO_PACKET] = "pkt",
de8f3a83 399 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 400 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 401 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
402 [PTR_TO_SOCKET] = "sock",
403 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
404 [PTR_TO_SOCK_COMMON] = "sock_common",
405 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
406 [PTR_TO_TCP_SOCK] = "tcp_sock",
407 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 408 [PTR_TO_TP_BUFFER] = "tp_buffer",
17a52670
AS
409};
410
8efea21d
EC
411static char slot_type_char[] = {
412 [STACK_INVALID] = '?',
413 [STACK_SPILL] = 'r',
414 [STACK_MISC] = 'm',
415 [STACK_ZERO] = '0',
416};
417
4e92024a
AS
418static void print_liveness(struct bpf_verifier_env *env,
419 enum bpf_reg_liveness live)
420{
9242b5f5 421 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
422 verbose(env, "_");
423 if (live & REG_LIVE_READ)
424 verbose(env, "r");
425 if (live & REG_LIVE_WRITTEN)
426 verbose(env, "w");
9242b5f5
AS
427 if (live & REG_LIVE_DONE)
428 verbose(env, "D");
4e92024a
AS
429}
430
f4d7e40a
AS
431static struct bpf_func_state *func(struct bpf_verifier_env *env,
432 const struct bpf_reg_state *reg)
433{
434 struct bpf_verifier_state *cur = env->cur_state;
435
436 return cur->frame[reg->frameno];
437}
438
61bd5218 439static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 440 const struct bpf_func_state *state)
17a52670 441{
f4d7e40a 442 const struct bpf_reg_state *reg;
17a52670
AS
443 enum bpf_reg_type t;
444 int i;
445
f4d7e40a
AS
446 if (state->frameno)
447 verbose(env, " frame%d:", state->frameno);
17a52670 448 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
449 reg = &state->regs[i];
450 t = reg->type;
17a52670
AS
451 if (t == NOT_INIT)
452 continue;
4e92024a
AS
453 verbose(env, " R%d", i);
454 print_liveness(env, reg->live);
455 verbose(env, "=%s", reg_type_str[t]);
f1174f77
EC
456 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
457 tnum_is_const(reg->var_off)) {
458 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 459 verbose(env, "%lld", reg->var_off.value + reg->off);
f4d7e40a
AS
460 if (t == PTR_TO_STACK)
461 verbose(env, ",call_%d", func(env, reg)->callsite);
f1174f77 462 } else {
cba368c1
MKL
463 verbose(env, "(id=%d", reg->id);
464 if (reg_type_may_be_refcounted_or_null(t))
465 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 466 if (t != SCALAR_VALUE)
61bd5218 467 verbose(env, ",off=%d", reg->off);
de8f3a83 468 if (type_is_pkt_pointer(t))
61bd5218 469 verbose(env, ",r=%d", reg->range);
f1174f77
EC
470 else if (t == CONST_PTR_TO_MAP ||
471 t == PTR_TO_MAP_VALUE ||
472 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 473 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
474 reg->map_ptr->key_size,
475 reg->map_ptr->value_size);
7d1238f2
EC
476 if (tnum_is_const(reg->var_off)) {
477 /* Typically an immediate SCALAR_VALUE, but
478 * could be a pointer whose offset is too big
479 * for reg->off
480 */
61bd5218 481 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
482 } else {
483 if (reg->smin_value != reg->umin_value &&
484 reg->smin_value != S64_MIN)
61bd5218 485 verbose(env, ",smin_value=%lld",
7d1238f2
EC
486 (long long)reg->smin_value);
487 if (reg->smax_value != reg->umax_value &&
488 reg->smax_value != S64_MAX)
61bd5218 489 verbose(env, ",smax_value=%lld",
7d1238f2
EC
490 (long long)reg->smax_value);
491 if (reg->umin_value != 0)
61bd5218 492 verbose(env, ",umin_value=%llu",
7d1238f2
EC
493 (unsigned long long)reg->umin_value);
494 if (reg->umax_value != U64_MAX)
61bd5218 495 verbose(env, ",umax_value=%llu",
7d1238f2
EC
496 (unsigned long long)reg->umax_value);
497 if (!tnum_is_unknown(reg->var_off)) {
498 char tn_buf[48];
f1174f77 499
7d1238f2 500 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 501 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 502 }
f1174f77 503 }
61bd5218 504 verbose(env, ")");
f1174f77 505 }
17a52670 506 }
638f5b90 507 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
508 char types_buf[BPF_REG_SIZE + 1];
509 bool valid = false;
510 int j;
511
512 for (j = 0; j < BPF_REG_SIZE; j++) {
513 if (state->stack[i].slot_type[j] != STACK_INVALID)
514 valid = true;
515 types_buf[j] = slot_type_char[
516 state->stack[i].slot_type[j]];
517 }
518 types_buf[BPF_REG_SIZE] = 0;
519 if (!valid)
520 continue;
521 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
522 print_liveness(env, state->stack[i].spilled_ptr.live);
523 if (state->stack[i].slot_type[0] == STACK_SPILL)
4e92024a 524 verbose(env, "=%s",
638f5b90 525 reg_type_str[state->stack[i].spilled_ptr.type]);
8efea21d
EC
526 else
527 verbose(env, "=%s", types_buf);
17a52670 528 }
fd978bf7
JS
529 if (state->acquired_refs && state->refs[0].id) {
530 verbose(env, " refs=%d", state->refs[0].id);
531 for (i = 1; i < state->acquired_refs; i++)
532 if (state->refs[i].id)
533 verbose(env, ",%d", state->refs[i].id);
534 }
61bd5218 535 verbose(env, "\n");
17a52670
AS
536}
537
84dbf350
JS
538#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
539static int copy_##NAME##_state(struct bpf_func_state *dst, \
540 const struct bpf_func_state *src) \
541{ \
542 if (!src->FIELD) \
543 return 0; \
544 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
545 /* internal bug, make state invalid to reject the program */ \
546 memset(dst, 0, sizeof(*dst)); \
547 return -EFAULT; \
548 } \
549 memcpy(dst->FIELD, src->FIELD, \
550 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
551 return 0; \
638f5b90 552}
fd978bf7
JS
553/* copy_reference_state() */
554COPY_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
555/* copy_stack_state() */
556COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
557#undef COPY_STATE_FN
558
559#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
560static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
561 bool copy_old) \
562{ \
563 u32 old_size = state->COUNT; \
564 struct bpf_##NAME##_state *new_##FIELD; \
565 int slot = size / SIZE; \
566 \
567 if (size <= old_size || !size) { \
568 if (copy_old) \
569 return 0; \
570 state->COUNT = slot * SIZE; \
571 if (!size && old_size) { \
572 kfree(state->FIELD); \
573 state->FIELD = NULL; \
574 } \
575 return 0; \
576 } \
577 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
578 GFP_KERNEL); \
579 if (!new_##FIELD) \
580 return -ENOMEM; \
581 if (copy_old) { \
582 if (state->FIELD) \
583 memcpy(new_##FIELD, state->FIELD, \
584 sizeof(*new_##FIELD) * (old_size / SIZE)); \
585 memset(new_##FIELD + old_size / SIZE, 0, \
586 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
587 } \
588 state->COUNT = slot * SIZE; \
589 kfree(state->FIELD); \
590 state->FIELD = new_##FIELD; \
591 return 0; \
592}
fd978bf7
JS
593/* realloc_reference_state() */
594REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
595/* realloc_stack_state() */
596REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
597#undef REALLOC_STATE_FN
638f5b90
AS
598
599/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
600 * make it consume minimal amount of memory. check_stack_write() access from
f4d7e40a 601 * the program calls into realloc_func_state() to grow the stack size.
84dbf350
JS
602 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
603 * which realloc_stack_state() copies over. It points to previous
604 * bpf_verifier_state which is never reallocated.
638f5b90 605 */
fd978bf7
JS
606static int realloc_func_state(struct bpf_func_state *state, int stack_size,
607 int refs_size, bool copy_old)
638f5b90 608{
fd978bf7
JS
609 int err = realloc_reference_state(state, refs_size, copy_old);
610 if (err)
611 return err;
612 return realloc_stack_state(state, stack_size, copy_old);
613}
614
615/* Acquire a pointer id from the env and update the state->refs to include
616 * this new pointer reference.
617 * On success, returns a valid pointer id to associate with the register
618 * On failure, returns a negative errno.
638f5b90 619 */
fd978bf7 620static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 621{
fd978bf7
JS
622 struct bpf_func_state *state = cur_func(env);
623 int new_ofs = state->acquired_refs;
624 int id, err;
625
626 err = realloc_reference_state(state, state->acquired_refs + 1, true);
627 if (err)
628 return err;
629 id = ++env->id_gen;
630 state->refs[new_ofs].id = id;
631 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 632
fd978bf7
JS
633 return id;
634}
635
636/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 637static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
638{
639 int i, last_idx;
640
fd978bf7
JS
641 last_idx = state->acquired_refs - 1;
642 for (i = 0; i < state->acquired_refs; i++) {
643 if (state->refs[i].id == ptr_id) {
644 if (last_idx && i != last_idx)
645 memcpy(&state->refs[i], &state->refs[last_idx],
646 sizeof(*state->refs));
647 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
648 state->acquired_refs--;
638f5b90 649 return 0;
638f5b90 650 }
638f5b90 651 }
46f8bc92 652 return -EINVAL;
fd978bf7
JS
653}
654
655static int transfer_reference_state(struct bpf_func_state *dst,
656 struct bpf_func_state *src)
657{
658 int err = realloc_reference_state(dst, src->acquired_refs, false);
659 if (err)
660 return err;
661 err = copy_reference_state(dst, src);
662 if (err)
663 return err;
638f5b90
AS
664 return 0;
665}
666
f4d7e40a
AS
667static void free_func_state(struct bpf_func_state *state)
668{
5896351e
AS
669 if (!state)
670 return;
fd978bf7 671 kfree(state->refs);
f4d7e40a
AS
672 kfree(state->stack);
673 kfree(state);
674}
675
1969db47
AS
676static void free_verifier_state(struct bpf_verifier_state *state,
677 bool free_self)
638f5b90 678{
f4d7e40a
AS
679 int i;
680
681 for (i = 0; i <= state->curframe; i++) {
682 free_func_state(state->frame[i]);
683 state->frame[i] = NULL;
684 }
1969db47
AS
685 if (free_self)
686 kfree(state);
638f5b90
AS
687}
688
689/* copy verifier state from src to dst growing dst stack space
690 * when necessary to accommodate larger src stack
691 */
f4d7e40a
AS
692static int copy_func_state(struct bpf_func_state *dst,
693 const struct bpf_func_state *src)
638f5b90
AS
694{
695 int err;
696
fd978bf7
JS
697 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
698 false);
699 if (err)
700 return err;
701 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
702 err = copy_reference_state(dst, src);
638f5b90
AS
703 if (err)
704 return err;
638f5b90
AS
705 return copy_stack_state(dst, src);
706}
707
f4d7e40a
AS
708static int copy_verifier_state(struct bpf_verifier_state *dst_state,
709 const struct bpf_verifier_state *src)
710{
711 struct bpf_func_state *dst;
712 int i, err;
713
714 /* if dst has more stack frames then src frame, free them */
715 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
716 free_func_state(dst_state->frame[i]);
717 dst_state->frame[i] = NULL;
718 }
979d63d5 719 dst_state->speculative = src->speculative;
f4d7e40a 720 dst_state->curframe = src->curframe;
d83525ca 721 dst_state->active_spin_lock = src->active_spin_lock;
f4d7e40a
AS
722 for (i = 0; i <= src->curframe; i++) {
723 dst = dst_state->frame[i];
724 if (!dst) {
725 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
726 if (!dst)
727 return -ENOMEM;
728 dst_state->frame[i] = dst;
729 }
730 err = copy_func_state(dst, src->frame[i]);
731 if (err)
732 return err;
733 }
734 return 0;
735}
736
638f5b90
AS
737static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
738 int *insn_idx)
739{
740 struct bpf_verifier_state *cur = env->cur_state;
741 struct bpf_verifier_stack_elem *elem, *head = env->head;
742 int err;
17a52670
AS
743
744 if (env->head == NULL)
638f5b90 745 return -ENOENT;
17a52670 746
638f5b90
AS
747 if (cur) {
748 err = copy_verifier_state(cur, &head->st);
749 if (err)
750 return err;
751 }
752 if (insn_idx)
753 *insn_idx = head->insn_idx;
17a52670 754 if (prev_insn_idx)
638f5b90
AS
755 *prev_insn_idx = head->prev_insn_idx;
756 elem = head->next;
1969db47 757 free_verifier_state(&head->st, false);
638f5b90 758 kfree(head);
17a52670
AS
759 env->head = elem;
760 env->stack_size--;
638f5b90 761 return 0;
17a52670
AS
762}
763
58e2af8b 764static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
765 int insn_idx, int prev_insn_idx,
766 bool speculative)
17a52670 767{
638f5b90 768 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 769 struct bpf_verifier_stack_elem *elem;
638f5b90 770 int err;
17a52670 771
638f5b90 772 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
773 if (!elem)
774 goto err;
775
17a52670
AS
776 elem->insn_idx = insn_idx;
777 elem->prev_insn_idx = prev_insn_idx;
778 elem->next = env->head;
779 env->head = elem;
780 env->stack_size++;
1969db47
AS
781 err = copy_verifier_state(&elem->st, cur);
782 if (err)
783 goto err;
979d63d5 784 elem->st.speculative |= speculative;
b285fcb7
AS
785 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
786 verbose(env, "The sequence of %d jumps is too complex.\n",
787 env->stack_size);
17a52670
AS
788 goto err;
789 }
790 return &elem->st;
791err:
5896351e
AS
792 free_verifier_state(env->cur_state, true);
793 env->cur_state = NULL;
17a52670 794 /* pop all elements and return */
638f5b90 795 while (!pop_stack(env, NULL, NULL));
17a52670
AS
796 return NULL;
797}
798
799#define CALLER_SAVED_REGS 6
800static const int caller_saved[CALLER_SAVED_REGS] = {
801 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
802};
803
f1174f77
EC
804static void __mark_reg_not_init(struct bpf_reg_state *reg);
805
b03c9f9f
EC
806/* Mark the unknown part of a register (variable offset or scalar value) as
807 * known to have the value @imm.
808 */
809static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
810{
a9c676bc
AS
811 /* Clear id, off, and union(map_ptr, range) */
812 memset(((u8 *)reg) + sizeof(reg->type), 0,
813 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
b03c9f9f
EC
814 reg->var_off = tnum_const(imm);
815 reg->smin_value = (s64)imm;
816 reg->smax_value = (s64)imm;
817 reg->umin_value = imm;
818 reg->umax_value = imm;
819}
820
f1174f77
EC
821/* Mark the 'variable offset' part of a register as zero. This should be
822 * used only on registers holding a pointer type.
823 */
824static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 825{
b03c9f9f 826 __mark_reg_known(reg, 0);
f1174f77 827}
a9789ef9 828
cc2b14d5
AS
829static void __mark_reg_const_zero(struct bpf_reg_state *reg)
830{
831 __mark_reg_known(reg, 0);
cc2b14d5
AS
832 reg->type = SCALAR_VALUE;
833}
834
61bd5218
JK
835static void mark_reg_known_zero(struct bpf_verifier_env *env,
836 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
837{
838 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 839 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
840 /* Something bad happened, let's kill all regs */
841 for (regno = 0; regno < MAX_BPF_REG; regno++)
842 __mark_reg_not_init(regs + regno);
843 return;
844 }
845 __mark_reg_known_zero(regs + regno);
846}
847
de8f3a83
DB
848static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
849{
850 return type_is_pkt_pointer(reg->type);
851}
852
853static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
854{
855 return reg_is_pkt_pointer(reg) ||
856 reg->type == PTR_TO_PACKET_END;
857}
858
859/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
860static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
861 enum bpf_reg_type which)
862{
863 /* The register can already have a range from prior markings.
864 * This is fine as long as it hasn't been advanced from its
865 * origin.
866 */
867 return reg->type == which &&
868 reg->id == 0 &&
869 reg->off == 0 &&
870 tnum_equals_const(reg->var_off, 0);
871}
872
b03c9f9f
EC
873/* Attempts to improve min/max values based on var_off information */
874static void __update_reg_bounds(struct bpf_reg_state *reg)
875{
876 /* min signed is max(sign bit) | min(other bits) */
877 reg->smin_value = max_t(s64, reg->smin_value,
878 reg->var_off.value | (reg->var_off.mask & S64_MIN));
879 /* max signed is min(sign bit) | max(other bits) */
880 reg->smax_value = min_t(s64, reg->smax_value,
881 reg->var_off.value | (reg->var_off.mask & S64_MAX));
882 reg->umin_value = max(reg->umin_value, reg->var_off.value);
883 reg->umax_value = min(reg->umax_value,
884 reg->var_off.value | reg->var_off.mask);
885}
886
887/* Uses signed min/max values to inform unsigned, and vice-versa */
888static void __reg_deduce_bounds(struct bpf_reg_state *reg)
889{
890 /* Learn sign from signed bounds.
891 * If we cannot cross the sign boundary, then signed and unsigned bounds
892 * are the same, so combine. This works even in the negative case, e.g.
893 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
894 */
895 if (reg->smin_value >= 0 || reg->smax_value < 0) {
896 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
897 reg->umin_value);
898 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
899 reg->umax_value);
900 return;
901 }
902 /* Learn sign from unsigned bounds. Signed bounds cross the sign
903 * boundary, so we must be careful.
904 */
905 if ((s64)reg->umax_value >= 0) {
906 /* Positive. We can't learn anything from the smin, but smax
907 * is positive, hence safe.
908 */
909 reg->smin_value = reg->umin_value;
910 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
911 reg->umax_value);
912 } else if ((s64)reg->umin_value < 0) {
913 /* Negative. We can't learn anything from the smax, but smin
914 * is negative, hence safe.
915 */
916 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
917 reg->umin_value);
918 reg->smax_value = reg->umax_value;
919 }
920}
921
922/* Attempts to improve var_off based on unsigned min/max information */
923static void __reg_bound_offset(struct bpf_reg_state *reg)
924{
925 reg->var_off = tnum_intersect(reg->var_off,
926 tnum_range(reg->umin_value,
927 reg->umax_value));
928}
929
930/* Reset the min/max bounds of a register */
931static void __mark_reg_unbounded(struct bpf_reg_state *reg)
932{
933 reg->smin_value = S64_MIN;
934 reg->smax_value = S64_MAX;
935 reg->umin_value = 0;
936 reg->umax_value = U64_MAX;
937}
938
f1174f77
EC
939/* Mark a register as having a completely unknown (scalar) value. */
940static void __mark_reg_unknown(struct bpf_reg_state *reg)
941{
a9c676bc
AS
942 /*
943 * Clear type, id, off, and union(map_ptr, range) and
944 * padding between 'type' and union
945 */
946 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 947 reg->type = SCALAR_VALUE;
f1174f77 948 reg->var_off = tnum_unknown;
f4d7e40a 949 reg->frameno = 0;
b03c9f9f 950 __mark_reg_unbounded(reg);
f1174f77
EC
951}
952
61bd5218
JK
953static void mark_reg_unknown(struct bpf_verifier_env *env,
954 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
955{
956 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 957 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
958 /* Something bad happened, let's kill all regs except FP */
959 for (regno = 0; regno < BPF_REG_FP; regno++)
f1174f77
EC
960 __mark_reg_not_init(regs + regno);
961 return;
962 }
963 __mark_reg_unknown(regs + regno);
964}
965
966static void __mark_reg_not_init(struct bpf_reg_state *reg)
967{
968 __mark_reg_unknown(reg);
969 reg->type = NOT_INIT;
970}
971
61bd5218
JK
972static void mark_reg_not_init(struct bpf_verifier_env *env,
973 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
974{
975 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 976 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
977 /* Something bad happened, let's kill all regs except FP */
978 for (regno = 0; regno < BPF_REG_FP; regno++)
f1174f77
EC
979 __mark_reg_not_init(regs + regno);
980 return;
981 }
982 __mark_reg_not_init(regs + regno);
a9789ef9
DB
983}
984
61bd5218 985static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 986 struct bpf_func_state *state)
17a52670 987{
f4d7e40a 988 struct bpf_reg_state *regs = state->regs;
17a52670
AS
989 int i;
990
dc503a8a 991 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 992 mark_reg_not_init(env, regs, i);
dc503a8a 993 regs[i].live = REG_LIVE_NONE;
679c782d 994 regs[i].parent = NULL;
dc503a8a 995 }
17a52670
AS
996
997 /* frame pointer */
f1174f77 998 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 999 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1000 regs[BPF_REG_FP].frameno = state->frameno;
17a52670
AS
1001
1002 /* 1st arg to a function */
1003 regs[BPF_REG_1].type = PTR_TO_CTX;
61bd5218 1004 mark_reg_known_zero(env, regs, BPF_REG_1);
6760bf2d
DB
1005}
1006
f4d7e40a
AS
1007#define BPF_MAIN_FUNC (-1)
1008static void init_func_state(struct bpf_verifier_env *env,
1009 struct bpf_func_state *state,
1010 int callsite, int frameno, int subprogno)
1011{
1012 state->callsite = callsite;
1013 state->frameno = frameno;
1014 state->subprogno = subprogno;
1015 init_reg_state(env, state);
1016}
1017
17a52670
AS
1018enum reg_arg_type {
1019 SRC_OP, /* register is used as source operand */
1020 DST_OP, /* register is used as destination operand */
1021 DST_OP_NO_MARK /* same as above, check only, don't mark */
1022};
1023
cc8b0b92
AS
1024static int cmp_subprogs(const void *a, const void *b)
1025{
9c8105bd
JW
1026 return ((struct bpf_subprog_info *)a)->start -
1027 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1028}
1029
1030static int find_subprog(struct bpf_verifier_env *env, int off)
1031{
9c8105bd 1032 struct bpf_subprog_info *p;
cc8b0b92 1033
9c8105bd
JW
1034 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1035 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1036 if (!p)
1037 return -ENOENT;
9c8105bd 1038 return p - env->subprog_info;
cc8b0b92
AS
1039
1040}
1041
1042static int add_subprog(struct bpf_verifier_env *env, int off)
1043{
1044 int insn_cnt = env->prog->len;
1045 int ret;
1046
1047 if (off >= insn_cnt || off < 0) {
1048 verbose(env, "call to invalid destination\n");
1049 return -EINVAL;
1050 }
1051 ret = find_subprog(env, off);
1052 if (ret >= 0)
1053 return 0;
4cb3d99c 1054 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1055 verbose(env, "too many subprograms\n");
1056 return -E2BIG;
1057 }
9c8105bd
JW
1058 env->subprog_info[env->subprog_cnt++].start = off;
1059 sort(env->subprog_info, env->subprog_cnt,
1060 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
cc8b0b92
AS
1061 return 0;
1062}
1063
1064static int check_subprogs(struct bpf_verifier_env *env)
1065{
1066 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
9c8105bd 1067 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92
AS
1068 struct bpf_insn *insn = env->prog->insnsi;
1069 int insn_cnt = env->prog->len;
1070
f910cefa
JW
1071 /* Add entry function. */
1072 ret = add_subprog(env, 0);
1073 if (ret < 0)
1074 return ret;
1075
cc8b0b92
AS
1076 /* determine subprog starts. The end is one before the next starts */
1077 for (i = 0; i < insn_cnt; i++) {
1078 if (insn[i].code != (BPF_JMP | BPF_CALL))
1079 continue;
1080 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1081 continue;
1082 if (!env->allow_ptr_leaks) {
1083 verbose(env, "function calls to other bpf functions are allowed for root only\n");
1084 return -EPERM;
1085 }
cc8b0b92
AS
1086 ret = add_subprog(env, i + insn[i].imm + 1);
1087 if (ret < 0)
1088 return ret;
1089 }
1090
4cb3d99c
JW
1091 /* Add a fake 'exit' subprog which could simplify subprog iteration
1092 * logic. 'subprog_cnt' should not be increased.
1093 */
1094 subprog[env->subprog_cnt].start = insn_cnt;
1095
06ee7115 1096 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1097 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1098 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92
AS
1099
1100 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1101 subprog_start = subprog[cur_subprog].start;
1102 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1103 for (i = 0; i < insn_cnt; i++) {
1104 u8 code = insn[i].code;
1105
092ed096 1106 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1107 goto next;
1108 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1109 goto next;
1110 off = i + insn[i].off + 1;
1111 if (off < subprog_start || off >= subprog_end) {
1112 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1113 return -EINVAL;
1114 }
1115next:
1116 if (i == subprog_end - 1) {
1117 /* to avoid fall-through from one subprog into another
1118 * the last insn of the subprog should be either exit
1119 * or unconditional jump back
1120 */
1121 if (code != (BPF_JMP | BPF_EXIT) &&
1122 code != (BPF_JMP | BPF_JA)) {
1123 verbose(env, "last insn is not an exit or jmp\n");
1124 return -EINVAL;
1125 }
1126 subprog_start = subprog_end;
4cb3d99c
JW
1127 cur_subprog++;
1128 if (cur_subprog < env->subprog_cnt)
9c8105bd 1129 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1130 }
1131 }
1132 return 0;
1133}
1134
679c782d
EC
1135/* Parentage chain of this register (or stack slot) should take care of all
1136 * issues like callee-saved registers, stack slot allocation time, etc.
1137 */
f4d7e40a 1138static int mark_reg_read(struct bpf_verifier_env *env,
679c782d
EC
1139 const struct bpf_reg_state *state,
1140 struct bpf_reg_state *parent)
f4d7e40a
AS
1141{
1142 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1143 int cnt = 0;
dc503a8a
EC
1144
1145 while (parent) {
1146 /* if read wasn't screened by an earlier write ... */
679c782d 1147 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1148 break;
9242b5f5
AS
1149 if (parent->live & REG_LIVE_DONE) {
1150 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1151 reg_type_str[parent->type],
1152 parent->var_off.value, parent->off);
1153 return -EFAULT;
1154 }
25af32da
AS
1155 if (parent->live & REG_LIVE_READ)
1156 /* The parentage chain never changes and
1157 * this parent was already marked as LIVE_READ.
1158 * There is no need to keep walking the chain again and
1159 * keep re-marking all parents as LIVE_READ.
1160 * This case happens when the same register is read
1161 * multiple times without writes into it in-between.
1162 */
1163 break;
dc503a8a 1164 /* ... then we depend on parent's value */
679c782d 1165 parent->live |= REG_LIVE_READ;
dc503a8a
EC
1166 state = parent;
1167 parent = state->parent;
f4d7e40a 1168 writes = true;
06ee7115 1169 cnt++;
dc503a8a 1170 }
06ee7115
AS
1171
1172 if (env->longest_mark_read_walk < cnt)
1173 env->longest_mark_read_walk = cnt;
f4d7e40a 1174 return 0;
dc503a8a
EC
1175}
1176
1177static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
1178 enum reg_arg_type t)
1179{
f4d7e40a
AS
1180 struct bpf_verifier_state *vstate = env->cur_state;
1181 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c342dc10 1182 struct bpf_reg_state *reg, *regs = state->regs;
dc503a8a 1183
17a52670 1184 if (regno >= MAX_BPF_REG) {
61bd5218 1185 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
1186 return -EINVAL;
1187 }
1188
c342dc10 1189 reg = &regs[regno];
17a52670
AS
1190 if (t == SRC_OP) {
1191 /* check whether register used as source operand can be read */
c342dc10 1192 if (reg->type == NOT_INIT) {
61bd5218 1193 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
1194 return -EACCES;
1195 }
679c782d 1196 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
1197 if (regno == BPF_REG_FP)
1198 return 0;
1199
1200 return mark_reg_read(env, reg, reg->parent);
17a52670
AS
1201 } else {
1202 /* check whether register used as dest operand can be written to */
1203 if (regno == BPF_REG_FP) {
61bd5218 1204 verbose(env, "frame pointer is read only\n");
17a52670
AS
1205 return -EACCES;
1206 }
c342dc10 1207 reg->live |= REG_LIVE_WRITTEN;
17a52670 1208 if (t == DST_OP)
61bd5218 1209 mark_reg_unknown(env, regs, regno);
17a52670
AS
1210 }
1211 return 0;
1212}
1213
1be7f75d
AS
1214static bool is_spillable_regtype(enum bpf_reg_type type)
1215{
1216 switch (type) {
1217 case PTR_TO_MAP_VALUE:
1218 case PTR_TO_MAP_VALUE_OR_NULL:
1219 case PTR_TO_STACK:
1220 case PTR_TO_CTX:
969bf05e 1221 case PTR_TO_PACKET:
de8f3a83 1222 case PTR_TO_PACKET_META:
969bf05e 1223 case PTR_TO_PACKET_END:
d58e468b 1224 case PTR_TO_FLOW_KEYS:
1be7f75d 1225 case CONST_PTR_TO_MAP:
c64b7983
JS
1226 case PTR_TO_SOCKET:
1227 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
1228 case PTR_TO_SOCK_COMMON:
1229 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
1230 case PTR_TO_TCP_SOCK:
1231 case PTR_TO_TCP_SOCK_OR_NULL:
1be7f75d
AS
1232 return true;
1233 default:
1234 return false;
1235 }
1236}
1237
cc2b14d5
AS
1238/* Does this register contain a constant zero? */
1239static bool register_is_null(struct bpf_reg_state *reg)
1240{
1241 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1242}
1243
17a52670
AS
1244/* check_stack_read/write functions track spill/fill of registers,
1245 * stack boundary and alignment are checked in check_mem_access()
1246 */
61bd5218 1247static int check_stack_write(struct bpf_verifier_env *env,
f4d7e40a 1248 struct bpf_func_state *state, /* func where register points to */
af86ca4e 1249 int off, int size, int value_regno, int insn_idx)
17a52670 1250{
f4d7e40a 1251 struct bpf_func_state *cur; /* state of the current function */
638f5b90 1252 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
f4d7e40a 1253 enum bpf_reg_type type;
638f5b90 1254
f4d7e40a 1255 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 1256 state->acquired_refs, true);
638f5b90
AS
1257 if (err)
1258 return err;
9c399760
AS
1259 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1260 * so it's aligned access and [off, off + size) are within stack limits
1261 */
638f5b90
AS
1262 if (!env->allow_ptr_leaks &&
1263 state->stack[spi].slot_type[0] == STACK_SPILL &&
1264 size != BPF_REG_SIZE) {
1265 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1266 return -EACCES;
1267 }
17a52670 1268
f4d7e40a 1269 cur = env->cur_state->frame[env->cur_state->curframe];
17a52670 1270 if (value_regno >= 0 &&
f4d7e40a 1271 is_spillable_regtype((type = cur->regs[value_regno].type))) {
17a52670
AS
1272
1273 /* register containing pointer is being spilled into stack */
9c399760 1274 if (size != BPF_REG_SIZE) {
61bd5218 1275 verbose(env, "invalid size of register spill\n");
17a52670
AS
1276 return -EACCES;
1277 }
1278
f4d7e40a
AS
1279 if (state != cur && type == PTR_TO_STACK) {
1280 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1281 return -EINVAL;
1282 }
1283
17a52670 1284 /* save register state */
f4d7e40a 1285 state->stack[spi].spilled_ptr = cur->regs[value_regno];
638f5b90 1286 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
17a52670 1287
af86ca4e
AS
1288 for (i = 0; i < BPF_REG_SIZE; i++) {
1289 if (state->stack[spi].slot_type[i] == STACK_MISC &&
1290 !env->allow_ptr_leaks) {
1291 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
1292 int soff = (-spi - 1) * BPF_REG_SIZE;
1293
1294 /* detected reuse of integer stack slot with a pointer
1295 * which means either llvm is reusing stack slot or
1296 * an attacker is trying to exploit CVE-2018-3639
1297 * (speculative store bypass)
1298 * Have to sanitize that slot with preemptive
1299 * store of zero.
1300 */
1301 if (*poff && *poff != soff) {
1302 /* disallow programs where single insn stores
1303 * into two different stack slots, since verifier
1304 * cannot sanitize them
1305 */
1306 verbose(env,
1307 "insn %d cannot access two stack slots fp%d and fp%d",
1308 insn_idx, *poff, soff);
1309 return -EINVAL;
1310 }
1311 *poff = soff;
1312 }
638f5b90 1313 state->stack[spi].slot_type[i] = STACK_SPILL;
af86ca4e 1314 }
9c399760 1315 } else {
cc2b14d5
AS
1316 u8 type = STACK_MISC;
1317
679c782d
EC
1318 /* regular write of data into stack destroys any spilled ptr */
1319 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
1320 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
1321 if (state->stack[spi].slot_type[0] == STACK_SPILL)
1322 for (i = 0; i < BPF_REG_SIZE; i++)
1323 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 1324
cc2b14d5
AS
1325 /* only mark the slot as written if all 8 bytes were written
1326 * otherwise read propagation may incorrectly stop too soon
1327 * when stack slots are partially written.
1328 * This heuristic means that read propagation will be
1329 * conservative, since it will add reg_live_read marks
1330 * to stack slots all the way to first state when programs
1331 * writes+reads less than 8 bytes
1332 */
1333 if (size == BPF_REG_SIZE)
1334 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1335
1336 /* when we zero initialize stack slots mark them as such */
1337 if (value_regno >= 0 &&
1338 register_is_null(&cur->regs[value_regno]))
1339 type = STACK_ZERO;
1340
0bae2d4d 1341 /* Mark slots affected by this stack write. */
9c399760 1342 for (i = 0; i < size; i++)
638f5b90 1343 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 1344 type;
17a52670
AS
1345 }
1346 return 0;
1347}
1348
61bd5218 1349static int check_stack_read(struct bpf_verifier_env *env,
f4d7e40a
AS
1350 struct bpf_func_state *reg_state /* func where register points to */,
1351 int off, int size, int value_regno)
17a52670 1352{
f4d7e40a
AS
1353 struct bpf_verifier_state *vstate = env->cur_state;
1354 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90
AS
1355 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1356 u8 *stype;
17a52670 1357
f4d7e40a 1358 if (reg_state->allocated_stack <= slot) {
638f5b90
AS
1359 verbose(env, "invalid read from stack off %d+0 size %d\n",
1360 off, size);
1361 return -EACCES;
1362 }
f4d7e40a 1363 stype = reg_state->stack[spi].slot_type;
17a52670 1364
638f5b90 1365 if (stype[0] == STACK_SPILL) {
9c399760 1366 if (size != BPF_REG_SIZE) {
61bd5218 1367 verbose(env, "invalid size of register spill\n");
17a52670
AS
1368 return -EACCES;
1369 }
9c399760 1370 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 1371 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 1372 verbose(env, "corrupted spill memory\n");
17a52670
AS
1373 return -EACCES;
1374 }
1375 }
1376
dc503a8a 1377 if (value_regno >= 0) {
17a52670 1378 /* restore register state from stack */
f4d7e40a 1379 state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
2f18f62e
AS
1380 /* mark reg as written since spilled pointer state likely
1381 * has its liveness marks cleared by is_state_visited()
1382 * which resets stack/reg liveness for state transitions
1383 */
1384 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
dc503a8a 1385 }
679c782d
EC
1386 mark_reg_read(env, &reg_state->stack[spi].spilled_ptr,
1387 reg_state->stack[spi].spilled_ptr.parent);
17a52670
AS
1388 return 0;
1389 } else {
cc2b14d5
AS
1390 int zeros = 0;
1391
17a52670 1392 for (i = 0; i < size; i++) {
cc2b14d5
AS
1393 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1394 continue;
1395 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1396 zeros++;
1397 continue;
17a52670 1398 }
cc2b14d5
AS
1399 verbose(env, "invalid read from stack off %d+%d size %d\n",
1400 off, i, size);
1401 return -EACCES;
1402 }
679c782d
EC
1403 mark_reg_read(env, &reg_state->stack[spi].spilled_ptr,
1404 reg_state->stack[spi].spilled_ptr.parent);
cc2b14d5
AS
1405 if (value_regno >= 0) {
1406 if (zeros == size) {
1407 /* any size read into register is zero extended,
1408 * so the whole register == const_zero
1409 */
1410 __mark_reg_const_zero(&state->regs[value_regno]);
1411 } else {
1412 /* have read misc data from the stack */
1413 mark_reg_unknown(env, state->regs, value_regno);
1414 }
1415 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
17a52670 1416 }
17a52670
AS
1417 return 0;
1418 }
1419}
1420
e4298d25
DB
1421static int check_stack_access(struct bpf_verifier_env *env,
1422 const struct bpf_reg_state *reg,
1423 int off, int size)
1424{
1425 /* Stack accesses must be at a fixed offset, so that we
1426 * can determine what type of data were returned. See
1427 * check_stack_read().
1428 */
1429 if (!tnum_is_const(reg->var_off)) {
1430 char tn_buf[48];
1431
1432 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1fbd20f8 1433 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
e4298d25
DB
1434 tn_buf, off, size);
1435 return -EACCES;
1436 }
1437
1438 if (off >= 0 || off < -MAX_BPF_STACK) {
1439 verbose(env, "invalid stack off=%d size=%d\n", off, size);
1440 return -EACCES;
1441 }
1442
1443 return 0;
1444}
1445
591fe988
DB
1446static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
1447 int off, int size, enum bpf_access_type type)
1448{
1449 struct bpf_reg_state *regs = cur_regs(env);
1450 struct bpf_map *map = regs[regno].map_ptr;
1451 u32 cap = bpf_map_flags_to_cap(map);
1452
1453 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
1454 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
1455 map->value_size, off, size);
1456 return -EACCES;
1457 }
1458
1459 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
1460 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
1461 map->value_size, off, size);
1462 return -EACCES;
1463 }
1464
1465 return 0;
1466}
1467
17a52670 1468/* check read/write into map element returned by bpf_map_lookup_elem() */
f1174f77 1469static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 1470 int size, bool zero_size_allowed)
17a52670 1471{
638f5b90
AS
1472 struct bpf_reg_state *regs = cur_regs(env);
1473 struct bpf_map *map = regs[regno].map_ptr;
17a52670 1474
9fd29c08
YS
1475 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1476 off + size > map->value_size) {
61bd5218 1477 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
17a52670
AS
1478 map->value_size, off, size);
1479 return -EACCES;
1480 }
1481 return 0;
1482}
1483
f1174f77
EC
1484/* check read/write into a map element with possible variable offset */
1485static int check_map_access(struct bpf_verifier_env *env, u32 regno,
9fd29c08 1486 int off, int size, bool zero_size_allowed)
dbcfe5f7 1487{
f4d7e40a
AS
1488 struct bpf_verifier_state *vstate = env->cur_state;
1489 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
1490 struct bpf_reg_state *reg = &state->regs[regno];
1491 int err;
1492
f1174f77
EC
1493 /* We may have adjusted the register to this map value, so we
1494 * need to try adding each of min_value and max_value to off
1495 * to make sure our theoretical access will be safe.
dbcfe5f7 1496 */
06ee7115 1497 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 1498 print_verifier_state(env, state);
b7137c4e 1499
dbcfe5f7
GB
1500 /* The minimum value is only important with signed
1501 * comparisons where we can't assume the floor of a
1502 * value is 0. If we are using signed variables for our
1503 * index'es we need to make sure that whatever we use
1504 * will have a set floor within our range.
1505 */
b7137c4e
DB
1506 if (reg->smin_value < 0 &&
1507 (reg->smin_value == S64_MIN ||
1508 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1509 reg->smin_value + off < 0)) {
61bd5218 1510 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
1511 regno);
1512 return -EACCES;
1513 }
9fd29c08
YS
1514 err = __check_map_access(env, regno, reg->smin_value + off, size,
1515 zero_size_allowed);
dbcfe5f7 1516 if (err) {
61bd5218
JK
1517 verbose(env, "R%d min value is outside of the array range\n",
1518 regno);
dbcfe5f7
GB
1519 return err;
1520 }
1521
b03c9f9f
EC
1522 /* If we haven't set a max value then we need to bail since we can't be
1523 * sure we won't do bad things.
1524 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 1525 */
b03c9f9f 1526 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
61bd5218 1527 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
dbcfe5f7
GB
1528 regno);
1529 return -EACCES;
1530 }
9fd29c08
YS
1531 err = __check_map_access(env, regno, reg->umax_value + off, size,
1532 zero_size_allowed);
f1174f77 1533 if (err)
61bd5218
JK
1534 verbose(env, "R%d max value is outside of the array range\n",
1535 regno);
d83525ca
AS
1536
1537 if (map_value_has_spin_lock(reg->map_ptr)) {
1538 u32 lock = reg->map_ptr->spin_lock_off;
1539
1540 /* if any part of struct bpf_spin_lock can be touched by
1541 * load/store reject this program.
1542 * To check that [x1, x2) overlaps with [y1, y2)
1543 * it is sufficient to check x1 < y2 && y1 < x2.
1544 */
1545 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
1546 lock < reg->umax_value + off + size) {
1547 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
1548 return -EACCES;
1549 }
1550 }
f1174f77 1551 return err;
dbcfe5f7
GB
1552}
1553
969bf05e
AS
1554#define MAX_PACKET_OFF 0xffff
1555
58e2af8b 1556static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
1557 const struct bpf_call_arg_meta *meta,
1558 enum bpf_access_type t)
4acf6c0b 1559{
36bbef52 1560 switch (env->prog->type) {
5d66fa7d 1561 /* Program types only with direct read access go here! */
3a0af8fd
TG
1562 case BPF_PROG_TYPE_LWT_IN:
1563 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 1564 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 1565 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 1566 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 1567 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
1568 if (t == BPF_WRITE)
1569 return false;
7e57fbb2 1570 /* fallthrough */
5d66fa7d
DB
1571
1572 /* Program types with direct read + write access go here! */
36bbef52
DB
1573 case BPF_PROG_TYPE_SCHED_CLS:
1574 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 1575 case BPF_PROG_TYPE_XDP:
3a0af8fd 1576 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 1577 case BPF_PROG_TYPE_SK_SKB:
4f738adb 1578 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
1579 if (meta)
1580 return meta->pkt_access;
1581
1582 env->seen_direct_write = true;
4acf6c0b
BB
1583 return true;
1584 default:
1585 return false;
1586 }
1587}
1588
f1174f77 1589static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
9fd29c08 1590 int off, int size, bool zero_size_allowed)
969bf05e 1591{
638f5b90 1592 struct bpf_reg_state *regs = cur_regs(env);
58e2af8b 1593 struct bpf_reg_state *reg = &regs[regno];
969bf05e 1594
9fd29c08
YS
1595 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1596 (u64)off + size > reg->range) {
61bd5218 1597 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
d91b28ed 1598 off, size, regno, reg->id, reg->off, reg->range);
969bf05e
AS
1599 return -EACCES;
1600 }
1601 return 0;
1602}
1603
f1174f77 1604static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 1605 int size, bool zero_size_allowed)
f1174f77 1606{
638f5b90 1607 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
1608 struct bpf_reg_state *reg = &regs[regno];
1609 int err;
1610
1611 /* We may have added a variable offset to the packet pointer; but any
1612 * reg->range we have comes after that. We are only checking the fixed
1613 * offset.
1614 */
1615
1616 /* We don't allow negative numbers, because we aren't tracking enough
1617 * detail to prove they're safe.
1618 */
b03c9f9f 1619 if (reg->smin_value < 0) {
61bd5218 1620 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
1621 regno);
1622 return -EACCES;
1623 }
9fd29c08 1624 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
f1174f77 1625 if (err) {
61bd5218 1626 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
1627 return err;
1628 }
e647815a
JW
1629
1630 /* __check_packet_access has made sure "off + size - 1" is within u16.
1631 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
1632 * otherwise find_good_pkt_pointers would have refused to set range info
1633 * that __check_packet_access would have rejected this pkt access.
1634 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
1635 */
1636 env->prog->aux->max_pkt_offset =
1637 max_t(u32, env->prog->aux->max_pkt_offset,
1638 off + reg->umax_value + size - 1);
1639
f1174f77
EC
1640 return err;
1641}
1642
1643/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 1644static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
19de99f7 1645 enum bpf_access_type t, enum bpf_reg_type *reg_type)
17a52670 1646{
f96da094
DB
1647 struct bpf_insn_access_aux info = {
1648 .reg_type = *reg_type,
1649 };
31fd8581 1650
4f9218aa 1651 if (env->ops->is_valid_access &&
5e43f899 1652 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
1653 /* A non zero info.ctx_field_size indicates that this field is a
1654 * candidate for later verifier transformation to load the whole
1655 * field and then apply a mask when accessed with a narrower
1656 * access than actual ctx access size. A zero info.ctx_field_size
1657 * will only allow for whole field access and rejects any other
1658 * type of narrower access.
31fd8581 1659 */
23994631 1660 *reg_type = info.reg_type;
31fd8581 1661
4f9218aa 1662 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
32bbe007
AS
1663 /* remember the offset of last byte accessed in ctx */
1664 if (env->prog->aux->max_ctx_offset < off + size)
1665 env->prog->aux->max_ctx_offset = off + size;
17a52670 1666 return 0;
32bbe007 1667 }
17a52670 1668
61bd5218 1669 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
1670 return -EACCES;
1671}
1672
d58e468b
PP
1673static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
1674 int size)
1675{
1676 if (size < 0 || off < 0 ||
1677 (u64)off + size > sizeof(struct bpf_flow_keys)) {
1678 verbose(env, "invalid access to flow keys off=%d size=%d\n",
1679 off, size);
1680 return -EACCES;
1681 }
1682 return 0;
1683}
1684
5f456649
MKL
1685static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
1686 u32 regno, int off, int size,
1687 enum bpf_access_type t)
c64b7983
JS
1688{
1689 struct bpf_reg_state *regs = cur_regs(env);
1690 struct bpf_reg_state *reg = &regs[regno];
5f456649 1691 struct bpf_insn_access_aux info = {};
46f8bc92 1692 bool valid;
c64b7983
JS
1693
1694 if (reg->smin_value < 0) {
1695 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1696 regno);
1697 return -EACCES;
1698 }
1699
46f8bc92
MKL
1700 switch (reg->type) {
1701 case PTR_TO_SOCK_COMMON:
1702 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
1703 break;
1704 case PTR_TO_SOCKET:
1705 valid = bpf_sock_is_valid_access(off, size, t, &info);
1706 break;
655a51e5
MKL
1707 case PTR_TO_TCP_SOCK:
1708 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
1709 break;
46f8bc92
MKL
1710 default:
1711 valid = false;
c64b7983
JS
1712 }
1713
5f456649 1714
46f8bc92
MKL
1715 if (valid) {
1716 env->insn_aux_data[insn_idx].ctx_field_size =
1717 info.ctx_field_size;
1718 return 0;
1719 }
1720
1721 verbose(env, "R%d invalid %s access off=%d size=%d\n",
1722 regno, reg_type_str[reg->type], off, size);
1723
1724 return -EACCES;
c64b7983
JS
1725}
1726
4cabc5b1
DB
1727static bool __is_pointer_value(bool allow_ptr_leaks,
1728 const struct bpf_reg_state *reg)
1be7f75d 1729{
4cabc5b1 1730 if (allow_ptr_leaks)
1be7f75d
AS
1731 return false;
1732
f1174f77 1733 return reg->type != SCALAR_VALUE;
1be7f75d
AS
1734}
1735
2a159c6f
DB
1736static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
1737{
1738 return cur_regs(env) + regno;
1739}
1740
4cabc5b1
DB
1741static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1742{
2a159c6f 1743 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
1744}
1745
f37a8cb8
DB
1746static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1747{
2a159c6f 1748 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 1749
46f8bc92
MKL
1750 return reg->type == PTR_TO_CTX;
1751}
1752
1753static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
1754{
1755 const struct bpf_reg_state *reg = reg_state(env, regno);
1756
1757 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
1758}
1759
ca369602
DB
1760static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1761{
2a159c6f 1762 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
1763
1764 return type_is_pkt_pointer(reg->type);
1765}
1766
4b5defde
DB
1767static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
1768{
1769 const struct bpf_reg_state *reg = reg_state(env, regno);
1770
1771 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
1772 return reg->type == PTR_TO_FLOW_KEYS;
1773}
1774
61bd5218
JK
1775static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1776 const struct bpf_reg_state *reg,
d1174416 1777 int off, int size, bool strict)
969bf05e 1778{
f1174f77 1779 struct tnum reg_off;
e07b98d9 1780 int ip_align;
d1174416
DM
1781
1782 /* Byte size accesses are always allowed. */
1783 if (!strict || size == 1)
1784 return 0;
1785
e4eda884
DM
1786 /* For platforms that do not have a Kconfig enabling
1787 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1788 * NET_IP_ALIGN is universally set to '2'. And on platforms
1789 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1790 * to this code only in strict mode where we want to emulate
1791 * the NET_IP_ALIGN==2 checking. Therefore use an
1792 * unconditional IP align value of '2'.
e07b98d9 1793 */
e4eda884 1794 ip_align = 2;
f1174f77
EC
1795
1796 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1797 if (!tnum_is_aligned(reg_off, size)) {
1798 char tn_buf[48];
1799
1800 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
1801 verbose(env,
1802 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 1803 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
1804 return -EACCES;
1805 }
79adffcd 1806
969bf05e
AS
1807 return 0;
1808}
1809
61bd5218
JK
1810static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1811 const struct bpf_reg_state *reg,
f1174f77
EC
1812 const char *pointer_desc,
1813 int off, int size, bool strict)
79adffcd 1814{
f1174f77
EC
1815 struct tnum reg_off;
1816
1817 /* Byte size accesses are always allowed. */
1818 if (!strict || size == 1)
1819 return 0;
1820
1821 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1822 if (!tnum_is_aligned(reg_off, size)) {
1823 char tn_buf[48];
1824
1825 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 1826 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 1827 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
1828 return -EACCES;
1829 }
1830
969bf05e
AS
1831 return 0;
1832}
1833
e07b98d9 1834static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
1835 const struct bpf_reg_state *reg, int off,
1836 int size, bool strict_alignment_once)
79adffcd 1837{
ca369602 1838 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 1839 const char *pointer_desc = "";
d1174416 1840
79adffcd
DB
1841 switch (reg->type) {
1842 case PTR_TO_PACKET:
de8f3a83
DB
1843 case PTR_TO_PACKET_META:
1844 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1845 * right in front, treat it the very same way.
1846 */
61bd5218 1847 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
1848 case PTR_TO_FLOW_KEYS:
1849 pointer_desc = "flow keys ";
1850 break;
f1174f77
EC
1851 case PTR_TO_MAP_VALUE:
1852 pointer_desc = "value ";
1853 break;
1854 case PTR_TO_CTX:
1855 pointer_desc = "context ";
1856 break;
1857 case PTR_TO_STACK:
1858 pointer_desc = "stack ";
a5ec6ae1
JH
1859 /* The stack spill tracking logic in check_stack_write()
1860 * and check_stack_read() relies on stack accesses being
1861 * aligned.
1862 */
1863 strict = true;
f1174f77 1864 break;
c64b7983
JS
1865 case PTR_TO_SOCKET:
1866 pointer_desc = "sock ";
1867 break;
46f8bc92
MKL
1868 case PTR_TO_SOCK_COMMON:
1869 pointer_desc = "sock_common ";
1870 break;
655a51e5
MKL
1871 case PTR_TO_TCP_SOCK:
1872 pointer_desc = "tcp_sock ";
1873 break;
79adffcd 1874 default:
f1174f77 1875 break;
79adffcd 1876 }
61bd5218
JK
1877 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1878 strict);
79adffcd
DB
1879}
1880
f4d7e40a
AS
1881static int update_stack_depth(struct bpf_verifier_env *env,
1882 const struct bpf_func_state *func,
1883 int off)
1884{
9c8105bd 1885 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
1886
1887 if (stack >= -off)
1888 return 0;
1889
1890 /* update known max for given subprogram */
9c8105bd 1891 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
1892 return 0;
1893}
f4d7e40a 1894
70a87ffe
AS
1895/* starting from main bpf function walk all instructions of the function
1896 * and recursively walk all callees that given function can call.
1897 * Ignore jump and exit insns.
1898 * Since recursion is prevented by check_cfg() this algorithm
1899 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1900 */
1901static int check_max_stack_depth(struct bpf_verifier_env *env)
1902{
9c8105bd
JW
1903 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
1904 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 1905 struct bpf_insn *insn = env->prog->insnsi;
70a87ffe
AS
1906 int ret_insn[MAX_CALL_FRAMES];
1907 int ret_prog[MAX_CALL_FRAMES];
f4d7e40a 1908
70a87ffe
AS
1909process_func:
1910 /* round up to 32-bytes, since this is granularity
1911 * of interpreter stack size
1912 */
9c8105bd 1913 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 1914 if (depth > MAX_BPF_STACK) {
f4d7e40a 1915 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 1916 frame + 1, depth);
f4d7e40a
AS
1917 return -EACCES;
1918 }
70a87ffe 1919continue_func:
4cb3d99c 1920 subprog_end = subprog[idx + 1].start;
70a87ffe
AS
1921 for (; i < subprog_end; i++) {
1922 if (insn[i].code != (BPF_JMP | BPF_CALL))
1923 continue;
1924 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1925 continue;
1926 /* remember insn and function to return to */
1927 ret_insn[frame] = i + 1;
9c8105bd 1928 ret_prog[frame] = idx;
70a87ffe
AS
1929
1930 /* find the callee */
1931 i = i + insn[i].imm + 1;
9c8105bd
JW
1932 idx = find_subprog(env, i);
1933 if (idx < 0) {
70a87ffe
AS
1934 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1935 i);
1936 return -EFAULT;
1937 }
70a87ffe
AS
1938 frame++;
1939 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
1940 verbose(env, "the call stack of %d frames is too deep !\n",
1941 frame);
1942 return -E2BIG;
70a87ffe
AS
1943 }
1944 goto process_func;
1945 }
1946 /* end of for() loop means the last insn of the 'subprog'
1947 * was reached. Doesn't matter whether it was JA or EXIT
1948 */
1949 if (frame == 0)
1950 return 0;
9c8105bd 1951 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
1952 frame--;
1953 i = ret_insn[frame];
9c8105bd 1954 idx = ret_prog[frame];
70a87ffe 1955 goto continue_func;
f4d7e40a
AS
1956}
1957
19d28fbd 1958#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
1959static int get_callee_stack_depth(struct bpf_verifier_env *env,
1960 const struct bpf_insn *insn, int idx)
1961{
1962 int start = idx + insn->imm + 1, subprog;
1963
1964 subprog = find_subprog(env, start);
1965 if (subprog < 0) {
1966 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1967 start);
1968 return -EFAULT;
1969 }
9c8105bd 1970 return env->subprog_info[subprog].stack_depth;
1ea47e01 1971}
19d28fbd 1972#endif
1ea47e01 1973
58990d1f
DB
1974static int check_ctx_reg(struct bpf_verifier_env *env,
1975 const struct bpf_reg_state *reg, int regno)
1976{
1977 /* Access to ctx or passing it to a helper is only allowed in
1978 * its original, unmodified form.
1979 */
1980
1981 if (reg->off) {
1982 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1983 regno, reg->off);
1984 return -EACCES;
1985 }
1986
1987 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1988 char tn_buf[48];
1989
1990 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1991 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
1992 return -EACCES;
1993 }
1994
1995 return 0;
1996}
1997
9df1c28b
MM
1998static int check_tp_buffer_access(struct bpf_verifier_env *env,
1999 const struct bpf_reg_state *reg,
2000 int regno, int off, int size)
2001{
2002 if (off < 0) {
2003 verbose(env,
2004 "R%d invalid tracepoint buffer access: off=%d, size=%d",
2005 regno, off, size);
2006 return -EACCES;
2007 }
2008 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2009 char tn_buf[48];
2010
2011 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2012 verbose(env,
2013 "R%d invalid variable buffer offset: off=%d, var_off=%s",
2014 regno, off, tn_buf);
2015 return -EACCES;
2016 }
2017 if (off + size > env->prog->aux->max_tp_access)
2018 env->prog->aux->max_tp_access = off + size;
2019
2020 return 0;
2021}
2022
2023
0c17d1d2
JH
2024/* truncate register to smaller size (in bytes)
2025 * must be called with size < BPF_REG_SIZE
2026 */
2027static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
2028{
2029 u64 mask;
2030
2031 /* clear high bits in bit representation */
2032 reg->var_off = tnum_cast(reg->var_off, size);
2033
2034 /* fix arithmetic bounds */
2035 mask = ((u64)1 << (size * 8)) - 1;
2036 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
2037 reg->umin_value &= mask;
2038 reg->umax_value &= mask;
2039 } else {
2040 reg->umin_value = 0;
2041 reg->umax_value = mask;
2042 }
2043 reg->smin_value = reg->umin_value;
2044 reg->smax_value = reg->umax_value;
2045}
2046
17a52670
AS
2047/* check whether memory at (regno + off) is accessible for t = (read | write)
2048 * if t==write, value_regno is a register which value is stored into memory
2049 * if t==read, value_regno is a register which will receive the value from memory
2050 * if t==write && value_regno==-1, some unknown value is stored into memory
2051 * if t==read && value_regno==-1, don't care what we read from memory
2052 */
ca369602
DB
2053static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
2054 int off, int bpf_size, enum bpf_access_type t,
2055 int value_regno, bool strict_alignment_once)
17a52670 2056{
638f5b90
AS
2057 struct bpf_reg_state *regs = cur_regs(env);
2058 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 2059 struct bpf_func_state *state;
17a52670
AS
2060 int size, err = 0;
2061
2062 size = bpf_size_to_bytes(bpf_size);
2063 if (size < 0)
2064 return size;
2065
f1174f77 2066 /* alignment checks will add in reg->off themselves */
ca369602 2067 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
2068 if (err)
2069 return err;
17a52670 2070
f1174f77
EC
2071 /* for access checks, reg->off is just part of off */
2072 off += reg->off;
2073
2074 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
2075 if (t == BPF_WRITE && value_regno >= 0 &&
2076 is_pointer_value(env, value_regno)) {
61bd5218 2077 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
2078 return -EACCES;
2079 }
591fe988
DB
2080 err = check_map_access_type(env, regno, off, size, t);
2081 if (err)
2082 return err;
9fd29c08 2083 err = check_map_access(env, regno, off, size, false);
17a52670 2084 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 2085 mark_reg_unknown(env, regs, value_regno);
17a52670 2086
1a0dc1ac 2087 } else if (reg->type == PTR_TO_CTX) {
f1174f77 2088 enum bpf_reg_type reg_type = SCALAR_VALUE;
19de99f7 2089
1be7f75d
AS
2090 if (t == BPF_WRITE && value_regno >= 0 &&
2091 is_pointer_value(env, value_regno)) {
61bd5218 2092 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
2093 return -EACCES;
2094 }
f1174f77 2095
58990d1f
DB
2096 err = check_ctx_reg(env, reg, regno);
2097 if (err < 0)
2098 return err;
2099
31fd8581 2100 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
969bf05e 2101 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 2102 /* ctx access returns either a scalar, or a
de8f3a83
DB
2103 * PTR_TO_PACKET[_META,_END]. In the latter
2104 * case, we know the offset is zero.
f1174f77 2105 */
46f8bc92 2106 if (reg_type == SCALAR_VALUE) {
638f5b90 2107 mark_reg_unknown(env, regs, value_regno);
46f8bc92 2108 } else {
638f5b90 2109 mark_reg_known_zero(env, regs,
61bd5218 2110 value_regno);
46f8bc92
MKL
2111 if (reg_type_may_be_null(reg_type))
2112 regs[value_regno].id = ++env->id_gen;
2113 }
638f5b90 2114 regs[value_regno].type = reg_type;
969bf05e 2115 }
17a52670 2116
f1174f77 2117 } else if (reg->type == PTR_TO_STACK) {
f1174f77 2118 off += reg->var_off.value;
e4298d25
DB
2119 err = check_stack_access(env, reg, off, size);
2120 if (err)
2121 return err;
8726679a 2122
f4d7e40a
AS
2123 state = func(env, reg);
2124 err = update_stack_depth(env, state, off);
2125 if (err)
2126 return err;
8726679a 2127
638f5b90 2128 if (t == BPF_WRITE)
61bd5218 2129 err = check_stack_write(env, state, off, size,
af86ca4e 2130 value_regno, insn_idx);
638f5b90 2131 else
61bd5218
JK
2132 err = check_stack_read(env, state, off, size,
2133 value_regno);
de8f3a83 2134 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 2135 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 2136 verbose(env, "cannot write into packet\n");
969bf05e
AS
2137 return -EACCES;
2138 }
4acf6c0b
BB
2139 if (t == BPF_WRITE && value_regno >= 0 &&
2140 is_pointer_value(env, value_regno)) {
61bd5218
JK
2141 verbose(env, "R%d leaks addr into packet\n",
2142 value_regno);
4acf6c0b
BB
2143 return -EACCES;
2144 }
9fd29c08 2145 err = check_packet_access(env, regno, off, size, false);
969bf05e 2146 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 2147 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
2148 } else if (reg->type == PTR_TO_FLOW_KEYS) {
2149 if (t == BPF_WRITE && value_regno >= 0 &&
2150 is_pointer_value(env, value_regno)) {
2151 verbose(env, "R%d leaks addr into flow keys\n",
2152 value_regno);
2153 return -EACCES;
2154 }
2155
2156 err = check_flow_keys_access(env, off, size);
2157 if (!err && t == BPF_READ && value_regno >= 0)
2158 mark_reg_unknown(env, regs, value_regno);
46f8bc92 2159 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 2160 if (t == BPF_WRITE) {
46f8bc92
MKL
2161 verbose(env, "R%d cannot write into %s\n",
2162 regno, reg_type_str[reg->type]);
c64b7983
JS
2163 return -EACCES;
2164 }
5f456649 2165 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
2166 if (!err && value_regno >= 0)
2167 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
2168 } else if (reg->type == PTR_TO_TP_BUFFER) {
2169 err = check_tp_buffer_access(env, reg, regno, off, size);
2170 if (!err && t == BPF_READ && value_regno >= 0)
2171 mark_reg_unknown(env, regs, value_regno);
17a52670 2172 } else {
61bd5218
JK
2173 verbose(env, "R%d invalid mem access '%s'\n", regno,
2174 reg_type_str[reg->type]);
17a52670
AS
2175 return -EACCES;
2176 }
969bf05e 2177
f1174f77 2178 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 2179 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 2180 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 2181 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 2182 }
17a52670
AS
2183 return err;
2184}
2185
31fd8581 2186static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 2187{
17a52670
AS
2188 int err;
2189
2190 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
2191 insn->imm != 0) {
61bd5218 2192 verbose(env, "BPF_XADD uses reserved fields\n");
17a52670
AS
2193 return -EINVAL;
2194 }
2195
2196 /* check src1 operand */
dc503a8a 2197 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
2198 if (err)
2199 return err;
2200
2201 /* check src2 operand */
dc503a8a 2202 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
2203 if (err)
2204 return err;
2205
6bdf6abc 2206 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 2207 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
2208 return -EACCES;
2209 }
2210
ca369602 2211 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 2212 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
2213 is_flow_key_reg(env, insn->dst_reg) ||
2214 is_sk_reg(env, insn->dst_reg)) {
ca369602 2215 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
2a159c6f
DB
2216 insn->dst_reg,
2217 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
2218 return -EACCES;
2219 }
2220
17a52670 2221 /* check whether atomic_add can read the memory */
31fd8581 2222 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 2223 BPF_SIZE(insn->code), BPF_READ, -1, true);
17a52670
AS
2224 if (err)
2225 return err;
2226
2227 /* check whether atomic_add can write into the same memory */
31fd8581 2228 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 2229 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
17a52670
AS
2230}
2231
2011fccf
AI
2232static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
2233 int off, int access_size,
2234 bool zero_size_allowed)
2235{
2236 struct bpf_reg_state *reg = reg_state(env, regno);
2237
2238 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
2239 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
2240 if (tnum_is_const(reg->var_off)) {
2241 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
2242 regno, off, access_size);
2243 } else {
2244 char tn_buf[48];
2245
2246 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2247 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
2248 regno, tn_buf, access_size);
2249 }
2250 return -EACCES;
2251 }
2252 return 0;
2253}
2254
17a52670
AS
2255/* when register 'regno' is passed into function that will read 'access_size'
2256 * bytes from that pointer, make sure that it's within stack boundary
f1174f77
EC
2257 * and all elements of stack are initialized.
2258 * Unlike most pointer bounds-checking functions, this one doesn't take an
2259 * 'off' argument, so it has to add in reg->off itself.
17a52670 2260 */
58e2af8b 2261static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
2262 int access_size, bool zero_size_allowed,
2263 struct bpf_call_arg_meta *meta)
17a52670 2264{
2a159c6f 2265 struct bpf_reg_state *reg = reg_state(env, regno);
f4d7e40a 2266 struct bpf_func_state *state = func(env, reg);
2011fccf 2267 int err, min_off, max_off, i, slot, spi;
17a52670 2268
914cb781 2269 if (reg->type != PTR_TO_STACK) {
f1174f77 2270 /* Allow zero-byte read from NULL, regardless of pointer type */
8e2fe1d9 2271 if (zero_size_allowed && access_size == 0 &&
914cb781 2272 register_is_null(reg))
8e2fe1d9
DB
2273 return 0;
2274
61bd5218 2275 verbose(env, "R%d type=%s expected=%s\n", regno,
914cb781 2276 reg_type_str[reg->type],
8e2fe1d9 2277 reg_type_str[PTR_TO_STACK]);
17a52670 2278 return -EACCES;
8e2fe1d9 2279 }
17a52670 2280
2011fccf
AI
2281 if (tnum_is_const(reg->var_off)) {
2282 min_off = max_off = reg->var_off.value + reg->off;
2283 err = __check_stack_boundary(env, regno, min_off, access_size,
2284 zero_size_allowed);
2285 if (err)
2286 return err;
2287 } else {
088ec26d
AI
2288 /* Variable offset is prohibited for unprivileged mode for
2289 * simplicity since it requires corresponding support in
2290 * Spectre masking for stack ALU.
2291 * See also retrieve_ptr_limit().
2292 */
2293 if (!env->allow_ptr_leaks) {
2294 char tn_buf[48];
f1174f77 2295
088ec26d
AI
2296 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2297 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
2298 regno, tn_buf);
2299 return -EACCES;
2300 }
f2bcd05e
AI
2301 /* Only initialized buffer on stack is allowed to be accessed
2302 * with variable offset. With uninitialized buffer it's hard to
2303 * guarantee that whole memory is marked as initialized on
2304 * helper return since specific bounds are unknown what may
2305 * cause uninitialized stack leaking.
2306 */
2307 if (meta && meta->raw_mode)
2308 meta = NULL;
2309
107c26a7
AI
2310 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
2311 reg->smax_value <= -BPF_MAX_VAR_OFF) {
2312 verbose(env, "R%d unbounded indirect variable offset stack access\n",
2313 regno);
2314 return -EACCES;
2315 }
2011fccf 2316 min_off = reg->smin_value + reg->off;
107c26a7 2317 max_off = reg->smax_value + reg->off;
2011fccf
AI
2318 err = __check_stack_boundary(env, regno, min_off, access_size,
2319 zero_size_allowed);
107c26a7
AI
2320 if (err) {
2321 verbose(env, "R%d min value is outside of stack bound\n",
2322 regno);
2011fccf 2323 return err;
107c26a7 2324 }
2011fccf
AI
2325 err = __check_stack_boundary(env, regno, max_off, access_size,
2326 zero_size_allowed);
107c26a7
AI
2327 if (err) {
2328 verbose(env, "R%d max value is outside of stack bound\n",
2329 regno);
2011fccf 2330 return err;
107c26a7 2331 }
17a52670
AS
2332 }
2333
435faee1
DB
2334 if (meta && meta->raw_mode) {
2335 meta->access_size = access_size;
2336 meta->regno = regno;
2337 return 0;
2338 }
2339
2011fccf 2340 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
2341 u8 *stype;
2342
2011fccf 2343 slot = -i - 1;
638f5b90 2344 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
2345 if (state->allocated_stack <= slot)
2346 goto err;
2347 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2348 if (*stype == STACK_MISC)
2349 goto mark;
2350 if (*stype == STACK_ZERO) {
2351 /* helper can write anything into the stack */
2352 *stype = STACK_MISC;
2353 goto mark;
17a52670 2354 }
cc2b14d5 2355err:
2011fccf
AI
2356 if (tnum_is_const(reg->var_off)) {
2357 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
2358 min_off, i - min_off, access_size);
2359 } else {
2360 char tn_buf[48];
2361
2362 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2363 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
2364 tn_buf, i - min_off, access_size);
2365 }
cc2b14d5
AS
2366 return -EACCES;
2367mark:
2368 /* reading any byte out of 8-byte 'spill_slot' will cause
2369 * the whole slot to be marked as 'read'
2370 */
679c782d
EC
2371 mark_reg_read(env, &state->stack[spi].spilled_ptr,
2372 state->stack[spi].spilled_ptr.parent);
17a52670 2373 }
2011fccf 2374 return update_stack_depth(env, state, min_off);
17a52670
AS
2375}
2376
06c1c049
GB
2377static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
2378 int access_size, bool zero_size_allowed,
2379 struct bpf_call_arg_meta *meta)
2380{
638f5b90 2381 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 2382
f1174f77 2383 switch (reg->type) {
06c1c049 2384 case PTR_TO_PACKET:
de8f3a83 2385 case PTR_TO_PACKET_META:
9fd29c08
YS
2386 return check_packet_access(env, regno, reg->off, access_size,
2387 zero_size_allowed);
06c1c049 2388 case PTR_TO_MAP_VALUE:
591fe988
DB
2389 if (check_map_access_type(env, regno, reg->off, access_size,
2390 meta && meta->raw_mode ? BPF_WRITE :
2391 BPF_READ))
2392 return -EACCES;
9fd29c08
YS
2393 return check_map_access(env, regno, reg->off, access_size,
2394 zero_size_allowed);
f1174f77 2395 default: /* scalar_value|ptr_to_stack or invalid ptr */
06c1c049
GB
2396 return check_stack_boundary(env, regno, access_size,
2397 zero_size_allowed, meta);
2398 }
2399}
2400
d83525ca
AS
2401/* Implementation details:
2402 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
2403 * Two bpf_map_lookups (even with the same key) will have different reg->id.
2404 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
2405 * value_or_null->value transition, since the verifier only cares about
2406 * the range of access to valid map value pointer and doesn't care about actual
2407 * address of the map element.
2408 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
2409 * reg->id > 0 after value_or_null->value transition. By doing so
2410 * two bpf_map_lookups will be considered two different pointers that
2411 * point to different bpf_spin_locks.
2412 * The verifier allows taking only one bpf_spin_lock at a time to avoid
2413 * dead-locks.
2414 * Since only one bpf_spin_lock is allowed the checks are simpler than
2415 * reg_is_refcounted() logic. The verifier needs to remember only
2416 * one spin_lock instead of array of acquired_refs.
2417 * cur_state->active_spin_lock remembers which map value element got locked
2418 * and clears it after bpf_spin_unlock.
2419 */
2420static int process_spin_lock(struct bpf_verifier_env *env, int regno,
2421 bool is_lock)
2422{
2423 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
2424 struct bpf_verifier_state *cur = env->cur_state;
2425 bool is_const = tnum_is_const(reg->var_off);
2426 struct bpf_map *map = reg->map_ptr;
2427 u64 val = reg->var_off.value;
2428
2429 if (reg->type != PTR_TO_MAP_VALUE) {
2430 verbose(env, "R%d is not a pointer to map_value\n", regno);
2431 return -EINVAL;
2432 }
2433 if (!is_const) {
2434 verbose(env,
2435 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
2436 regno);
2437 return -EINVAL;
2438 }
2439 if (!map->btf) {
2440 verbose(env,
2441 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
2442 map->name);
2443 return -EINVAL;
2444 }
2445 if (!map_value_has_spin_lock(map)) {
2446 if (map->spin_lock_off == -E2BIG)
2447 verbose(env,
2448 "map '%s' has more than one 'struct bpf_spin_lock'\n",
2449 map->name);
2450 else if (map->spin_lock_off == -ENOENT)
2451 verbose(env,
2452 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
2453 map->name);
2454 else
2455 verbose(env,
2456 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
2457 map->name);
2458 return -EINVAL;
2459 }
2460 if (map->spin_lock_off != val + reg->off) {
2461 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
2462 val + reg->off);
2463 return -EINVAL;
2464 }
2465 if (is_lock) {
2466 if (cur->active_spin_lock) {
2467 verbose(env,
2468 "Locking two bpf_spin_locks are not allowed\n");
2469 return -EINVAL;
2470 }
2471 cur->active_spin_lock = reg->id;
2472 } else {
2473 if (!cur->active_spin_lock) {
2474 verbose(env, "bpf_spin_unlock without taking a lock\n");
2475 return -EINVAL;
2476 }
2477 if (cur->active_spin_lock != reg->id) {
2478 verbose(env, "bpf_spin_unlock of different lock\n");
2479 return -EINVAL;
2480 }
2481 cur->active_spin_lock = 0;
2482 }
2483 return 0;
2484}
2485
90133415
DB
2486static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
2487{
2488 return type == ARG_PTR_TO_MEM ||
2489 type == ARG_PTR_TO_MEM_OR_NULL ||
2490 type == ARG_PTR_TO_UNINIT_MEM;
2491}
2492
2493static bool arg_type_is_mem_size(enum bpf_arg_type type)
2494{
2495 return type == ARG_CONST_SIZE ||
2496 type == ARG_CONST_SIZE_OR_ZERO;
2497}
2498
57c3bb72
AI
2499static bool arg_type_is_int_ptr(enum bpf_arg_type type)
2500{
2501 return type == ARG_PTR_TO_INT ||
2502 type == ARG_PTR_TO_LONG;
2503}
2504
2505static int int_ptr_type_to_size(enum bpf_arg_type type)
2506{
2507 if (type == ARG_PTR_TO_INT)
2508 return sizeof(u32);
2509 else if (type == ARG_PTR_TO_LONG)
2510 return sizeof(u64);
2511
2512 return -EINVAL;
2513}
2514
58e2af8b 2515static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
33ff9823
DB
2516 enum bpf_arg_type arg_type,
2517 struct bpf_call_arg_meta *meta)
17a52670 2518{
638f5b90 2519 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6841de8b 2520 enum bpf_reg_type expected_type, type = reg->type;
17a52670
AS
2521 int err = 0;
2522
80f1d68c 2523 if (arg_type == ARG_DONTCARE)
17a52670
AS
2524 return 0;
2525
dc503a8a
EC
2526 err = check_reg_arg(env, regno, SRC_OP);
2527 if (err)
2528 return err;
17a52670 2529
1be7f75d
AS
2530 if (arg_type == ARG_ANYTHING) {
2531 if (is_pointer_value(env, regno)) {
61bd5218
JK
2532 verbose(env, "R%d leaks addr into helper function\n",
2533 regno);
1be7f75d
AS
2534 return -EACCES;
2535 }
80f1d68c 2536 return 0;
1be7f75d 2537 }
80f1d68c 2538
de8f3a83 2539 if (type_is_pkt_pointer(type) &&
3a0af8fd 2540 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 2541 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
2542 return -EACCES;
2543 }
2544
8e2fe1d9 2545 if (arg_type == ARG_PTR_TO_MAP_KEY ||
2ea864c5 2546 arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
2547 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
2548 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
17a52670 2549 expected_type = PTR_TO_STACK;
6ac99e8f
MKL
2550 if (register_is_null(reg) &&
2551 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
2552 /* final test in check_stack_boundary() */;
2553 else if (!type_is_pkt_pointer(type) &&
2554 type != PTR_TO_MAP_VALUE &&
2555 type != expected_type)
6841de8b 2556 goto err_type;
39f19ebb
AS
2557 } else if (arg_type == ARG_CONST_SIZE ||
2558 arg_type == ARG_CONST_SIZE_OR_ZERO) {
f1174f77
EC
2559 expected_type = SCALAR_VALUE;
2560 if (type != expected_type)
6841de8b 2561 goto err_type;
17a52670
AS
2562 } else if (arg_type == ARG_CONST_MAP_PTR) {
2563 expected_type = CONST_PTR_TO_MAP;
6841de8b
AS
2564 if (type != expected_type)
2565 goto err_type;
608cd71a
AS
2566 } else if (arg_type == ARG_PTR_TO_CTX) {
2567 expected_type = PTR_TO_CTX;
6841de8b
AS
2568 if (type != expected_type)
2569 goto err_type;
58990d1f
DB
2570 err = check_ctx_reg(env, reg, regno);
2571 if (err < 0)
2572 return err;
46f8bc92
MKL
2573 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
2574 expected_type = PTR_TO_SOCK_COMMON;
2575 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
2576 if (!type_is_sk_pointer(type))
2577 goto err_type;
1b986589
MKL
2578 if (reg->ref_obj_id) {
2579 if (meta->ref_obj_id) {
2580 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
2581 regno, reg->ref_obj_id,
2582 meta->ref_obj_id);
2583 return -EFAULT;
2584 }
2585 meta->ref_obj_id = reg->ref_obj_id;
fd978bf7 2586 }
6ac99e8f
MKL
2587 } else if (arg_type == ARG_PTR_TO_SOCKET) {
2588 expected_type = PTR_TO_SOCKET;
2589 if (type != expected_type)
2590 goto err_type;
d83525ca
AS
2591 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
2592 if (meta->func_id == BPF_FUNC_spin_lock) {
2593 if (process_spin_lock(env, regno, true))
2594 return -EACCES;
2595 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
2596 if (process_spin_lock(env, regno, false))
2597 return -EACCES;
2598 } else {
2599 verbose(env, "verifier internal error\n");
2600 return -EFAULT;
2601 }
90133415 2602 } else if (arg_type_is_mem_ptr(arg_type)) {
8e2fe1d9
DB
2603 expected_type = PTR_TO_STACK;
2604 /* One exception here. In case function allows for NULL to be
f1174f77 2605 * passed in as argument, it's a SCALAR_VALUE type. Final test
8e2fe1d9
DB
2606 * happens during stack boundary checking.
2607 */
914cb781 2608 if (register_is_null(reg) &&
db1ac496 2609 arg_type == ARG_PTR_TO_MEM_OR_NULL)
6841de8b 2610 /* final test in check_stack_boundary() */;
de8f3a83
DB
2611 else if (!type_is_pkt_pointer(type) &&
2612 type != PTR_TO_MAP_VALUE &&
f1174f77 2613 type != expected_type)
6841de8b 2614 goto err_type;
39f19ebb 2615 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
57c3bb72
AI
2616 } else if (arg_type_is_int_ptr(arg_type)) {
2617 expected_type = PTR_TO_STACK;
2618 if (!type_is_pkt_pointer(type) &&
2619 type != PTR_TO_MAP_VALUE &&
2620 type != expected_type)
2621 goto err_type;
17a52670 2622 } else {
61bd5218 2623 verbose(env, "unsupported arg_type %d\n", arg_type);
17a52670
AS
2624 return -EFAULT;
2625 }
2626
17a52670
AS
2627 if (arg_type == ARG_CONST_MAP_PTR) {
2628 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 2629 meta->map_ptr = reg->map_ptr;
17a52670
AS
2630 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
2631 /* bpf_map_xxx(..., map_ptr, ..., key) call:
2632 * check that [key, key + map->key_size) are within
2633 * stack limits and initialized
2634 */
33ff9823 2635 if (!meta->map_ptr) {
17a52670
AS
2636 /* in function declaration map_ptr must come before
2637 * map_key, so that it's verified and known before
2638 * we have to check map_key here. Otherwise it means
2639 * that kernel subsystem misconfigured verifier
2640 */
61bd5218 2641 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
2642 return -EACCES;
2643 }
d71962f3
PC
2644 err = check_helper_mem_access(env, regno,
2645 meta->map_ptr->key_size, false,
2646 NULL);
2ea864c5 2647 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
2648 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
2649 !register_is_null(reg)) ||
2ea864c5 2650 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
2651 /* bpf_map_xxx(..., map_ptr, ..., value) call:
2652 * check [value, value + map->value_size) validity
2653 */
33ff9823 2654 if (!meta->map_ptr) {
17a52670 2655 /* kernel subsystem misconfigured verifier */
61bd5218 2656 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
2657 return -EACCES;
2658 }
2ea864c5 2659 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
2660 err = check_helper_mem_access(env, regno,
2661 meta->map_ptr->value_size, false,
2ea864c5 2662 meta);
90133415 2663 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 2664 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 2665
849fa506
YS
2666 /* remember the mem_size which may be used later
2667 * to refine return values.
2668 */
2669 meta->msize_smax_value = reg->smax_value;
2670 meta->msize_umax_value = reg->umax_value;
2671
f1174f77
EC
2672 /* The register is SCALAR_VALUE; the access check
2673 * happens using its boundaries.
06c1c049 2674 */
f1174f77 2675 if (!tnum_is_const(reg->var_off))
06c1c049
GB
2676 /* For unprivileged variable accesses, disable raw
2677 * mode so that the program is required to
2678 * initialize all the memory that the helper could
2679 * just partially fill up.
2680 */
2681 meta = NULL;
2682
b03c9f9f 2683 if (reg->smin_value < 0) {
61bd5218 2684 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
2685 regno);
2686 return -EACCES;
2687 }
06c1c049 2688
b03c9f9f 2689 if (reg->umin_value == 0) {
f1174f77
EC
2690 err = check_helper_mem_access(env, regno - 1, 0,
2691 zero_size_allowed,
2692 meta);
06c1c049
GB
2693 if (err)
2694 return err;
06c1c049 2695 }
f1174f77 2696
b03c9f9f 2697 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 2698 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
2699 regno);
2700 return -EACCES;
2701 }
2702 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 2703 reg->umax_value,
f1174f77 2704 zero_size_allowed, meta);
57c3bb72
AI
2705 } else if (arg_type_is_int_ptr(arg_type)) {
2706 int size = int_ptr_type_to_size(arg_type);
2707
2708 err = check_helper_mem_access(env, regno, size, false, meta);
2709 if (err)
2710 return err;
2711 err = check_ptr_alignment(env, reg, 0, size, true);
17a52670
AS
2712 }
2713
2714 return err;
6841de8b 2715err_type:
61bd5218 2716 verbose(env, "R%d type=%s expected=%s\n", regno,
6841de8b
AS
2717 reg_type_str[type], reg_type_str[expected_type]);
2718 return -EACCES;
17a52670
AS
2719}
2720
61bd5218
JK
2721static int check_map_func_compatibility(struct bpf_verifier_env *env,
2722 struct bpf_map *map, int func_id)
35578d79 2723{
35578d79
KX
2724 if (!map)
2725 return 0;
2726
6aff67c8
AS
2727 /* We need a two way check, first is from map perspective ... */
2728 switch (map->map_type) {
2729 case BPF_MAP_TYPE_PROG_ARRAY:
2730 if (func_id != BPF_FUNC_tail_call)
2731 goto error;
2732 break;
2733 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2734 if (func_id != BPF_FUNC_perf_event_read &&
908432ca
YS
2735 func_id != BPF_FUNC_perf_event_output &&
2736 func_id != BPF_FUNC_perf_event_read_value)
6aff67c8
AS
2737 goto error;
2738 break;
2739 case BPF_MAP_TYPE_STACK_TRACE:
2740 if (func_id != BPF_FUNC_get_stackid)
2741 goto error;
2742 break;
4ed8ec52 2743 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 2744 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 2745 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
2746 goto error;
2747 break;
cd339431 2748 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 2749 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
2750 if (func_id != BPF_FUNC_get_local_storage)
2751 goto error;
2752 break;
546ac1ff
JF
2753 /* devmap returns a pointer to a live net_device ifindex that we cannot
2754 * allow to be modified from bpf side. So do not allow lookup elements
2755 * for now.
2756 */
2757 case BPF_MAP_TYPE_DEVMAP:
2ddf71e2 2758 if (func_id != BPF_FUNC_redirect_map)
546ac1ff
JF
2759 goto error;
2760 break;
fbfc504a
BT
2761 /* Restrict bpf side of cpumap and xskmap, open when use-cases
2762 * appear.
2763 */
6710e112 2764 case BPF_MAP_TYPE_CPUMAP:
fbfc504a 2765 case BPF_MAP_TYPE_XSKMAP:
6710e112
JDB
2766 if (func_id != BPF_FUNC_redirect_map)
2767 goto error;
2768 break;
56f668df 2769 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 2770 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
2771 if (func_id != BPF_FUNC_map_lookup_elem)
2772 goto error;
16a43625 2773 break;
174a79ff
JF
2774 case BPF_MAP_TYPE_SOCKMAP:
2775 if (func_id != BPF_FUNC_sk_redirect_map &&
2776 func_id != BPF_FUNC_sock_map_update &&
4f738adb
JF
2777 func_id != BPF_FUNC_map_delete_elem &&
2778 func_id != BPF_FUNC_msg_redirect_map)
174a79ff
JF
2779 goto error;
2780 break;
81110384
JF
2781 case BPF_MAP_TYPE_SOCKHASH:
2782 if (func_id != BPF_FUNC_sk_redirect_hash &&
2783 func_id != BPF_FUNC_sock_hash_update &&
2784 func_id != BPF_FUNC_map_delete_elem &&
2785 func_id != BPF_FUNC_msg_redirect_hash)
2786 goto error;
2787 break;
2dbb9b9e
MKL
2788 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2789 if (func_id != BPF_FUNC_sk_select_reuseport)
2790 goto error;
2791 break;
f1a2e44a
MV
2792 case BPF_MAP_TYPE_QUEUE:
2793 case BPF_MAP_TYPE_STACK:
2794 if (func_id != BPF_FUNC_map_peek_elem &&
2795 func_id != BPF_FUNC_map_pop_elem &&
2796 func_id != BPF_FUNC_map_push_elem)
2797 goto error;
2798 break;
6ac99e8f
MKL
2799 case BPF_MAP_TYPE_SK_STORAGE:
2800 if (func_id != BPF_FUNC_sk_storage_get &&
2801 func_id != BPF_FUNC_sk_storage_delete)
2802 goto error;
2803 break;
6aff67c8
AS
2804 default:
2805 break;
2806 }
2807
2808 /* ... and second from the function itself. */
2809 switch (func_id) {
2810 case BPF_FUNC_tail_call:
2811 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2812 goto error;
f910cefa 2813 if (env->subprog_cnt > 1) {
f4d7e40a
AS
2814 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2815 return -EINVAL;
2816 }
6aff67c8
AS
2817 break;
2818 case BPF_FUNC_perf_event_read:
2819 case BPF_FUNC_perf_event_output:
908432ca 2820 case BPF_FUNC_perf_event_read_value:
6aff67c8
AS
2821 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2822 goto error;
2823 break;
2824 case BPF_FUNC_get_stackid:
2825 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2826 goto error;
2827 break;
60d20f91 2828 case BPF_FUNC_current_task_under_cgroup:
747ea55e 2829 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
2830 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2831 goto error;
2832 break;
97f91a7c 2833 case BPF_FUNC_redirect_map:
9c270af3 2834 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
fbfc504a
BT
2835 map->map_type != BPF_MAP_TYPE_CPUMAP &&
2836 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
2837 goto error;
2838 break;
174a79ff 2839 case BPF_FUNC_sk_redirect_map:
4f738adb 2840 case BPF_FUNC_msg_redirect_map:
81110384 2841 case BPF_FUNC_sock_map_update:
174a79ff
JF
2842 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2843 goto error;
2844 break;
81110384
JF
2845 case BPF_FUNC_sk_redirect_hash:
2846 case BPF_FUNC_msg_redirect_hash:
2847 case BPF_FUNC_sock_hash_update:
2848 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
2849 goto error;
2850 break;
cd339431 2851 case BPF_FUNC_get_local_storage:
b741f163
RG
2852 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
2853 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
2854 goto error;
2855 break;
2dbb9b9e
MKL
2856 case BPF_FUNC_sk_select_reuseport:
2857 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
2858 goto error;
2859 break;
f1a2e44a
MV
2860 case BPF_FUNC_map_peek_elem:
2861 case BPF_FUNC_map_pop_elem:
2862 case BPF_FUNC_map_push_elem:
2863 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
2864 map->map_type != BPF_MAP_TYPE_STACK)
2865 goto error;
2866 break;
6ac99e8f
MKL
2867 case BPF_FUNC_sk_storage_get:
2868 case BPF_FUNC_sk_storage_delete:
2869 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
2870 goto error;
2871 break;
6aff67c8
AS
2872 default:
2873 break;
35578d79
KX
2874 }
2875
2876 return 0;
6aff67c8 2877error:
61bd5218 2878 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 2879 map->map_type, func_id_name(func_id), func_id);
6aff67c8 2880 return -EINVAL;
35578d79
KX
2881}
2882
90133415 2883static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
2884{
2885 int count = 0;
2886
39f19ebb 2887 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 2888 count++;
39f19ebb 2889 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 2890 count++;
39f19ebb 2891 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 2892 count++;
39f19ebb 2893 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 2894 count++;
39f19ebb 2895 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
2896 count++;
2897
90133415
DB
2898 /* We only support one arg being in raw mode at the moment,
2899 * which is sufficient for the helper functions we have
2900 * right now.
2901 */
2902 return count <= 1;
2903}
2904
2905static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2906 enum bpf_arg_type arg_next)
2907{
2908 return (arg_type_is_mem_ptr(arg_curr) &&
2909 !arg_type_is_mem_size(arg_next)) ||
2910 (!arg_type_is_mem_ptr(arg_curr) &&
2911 arg_type_is_mem_size(arg_next));
2912}
2913
2914static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2915{
2916 /* bpf_xxx(..., buf, len) call will access 'len'
2917 * bytes from memory 'buf'. Both arg types need
2918 * to be paired, so make sure there's no buggy
2919 * helper function specification.
2920 */
2921 if (arg_type_is_mem_size(fn->arg1_type) ||
2922 arg_type_is_mem_ptr(fn->arg5_type) ||
2923 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2924 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2925 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2926 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2927 return false;
2928
2929 return true;
2930}
2931
1b986589 2932static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
2933{
2934 int count = 0;
2935
1b986589 2936 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 2937 count++;
1b986589 2938 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 2939 count++;
1b986589 2940 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 2941 count++;
1b986589 2942 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 2943 count++;
1b986589 2944 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
2945 count++;
2946
1b986589
MKL
2947 /* A reference acquiring function cannot acquire
2948 * another refcounted ptr.
2949 */
2950 if (is_acquire_function(func_id) && count)
2951 return false;
2952
fd978bf7
JS
2953 /* We only support one arg being unreferenced at the moment,
2954 * which is sufficient for the helper functions we have right now.
2955 */
2956 return count <= 1;
2957}
2958
1b986589 2959static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
2960{
2961 return check_raw_mode_ok(fn) &&
fd978bf7 2962 check_arg_pair_ok(fn) &&
1b986589 2963 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
2964}
2965
de8f3a83
DB
2966/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2967 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 2968 */
f4d7e40a
AS
2969static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2970 struct bpf_func_state *state)
969bf05e 2971{
58e2af8b 2972 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
2973 int i;
2974
2975 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 2976 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 2977 mark_reg_unknown(env, regs, i);
969bf05e 2978
f3709f69
JS
2979 bpf_for_each_spilled_reg(i, state, reg) {
2980 if (!reg)
969bf05e 2981 continue;
de8f3a83
DB
2982 if (reg_is_pkt_pointer_any(reg))
2983 __mark_reg_unknown(reg);
969bf05e
AS
2984 }
2985}
2986
f4d7e40a
AS
2987static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2988{
2989 struct bpf_verifier_state *vstate = env->cur_state;
2990 int i;
2991
2992 for (i = 0; i <= vstate->curframe; i++)
2993 __clear_all_pkt_pointers(env, vstate->frame[i]);
2994}
2995
fd978bf7 2996static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
2997 struct bpf_func_state *state,
2998 int ref_obj_id)
fd978bf7
JS
2999{
3000 struct bpf_reg_state *regs = state->regs, *reg;
3001 int i;
3002
3003 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 3004 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
3005 mark_reg_unknown(env, regs, i);
3006
3007 bpf_for_each_spilled_reg(i, state, reg) {
3008 if (!reg)
3009 continue;
1b986589 3010 if (reg->ref_obj_id == ref_obj_id)
fd978bf7
JS
3011 __mark_reg_unknown(reg);
3012 }
3013}
3014
3015/* The pointer with the specified id has released its reference to kernel
3016 * resources. Identify all copies of the same pointer and clear the reference.
3017 */
3018static int release_reference(struct bpf_verifier_env *env,
1b986589 3019 int ref_obj_id)
fd978bf7
JS
3020{
3021 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 3022 int err;
fd978bf7
JS
3023 int i;
3024
1b986589
MKL
3025 err = release_reference_state(cur_func(env), ref_obj_id);
3026 if (err)
3027 return err;
3028
fd978bf7 3029 for (i = 0; i <= vstate->curframe; i++)
1b986589 3030 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 3031
1b986589 3032 return 0;
fd978bf7
JS
3033}
3034
f4d7e40a
AS
3035static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
3036 int *insn_idx)
3037{
3038 struct bpf_verifier_state *state = env->cur_state;
3039 struct bpf_func_state *caller, *callee;
fd978bf7 3040 int i, err, subprog, target_insn;
f4d7e40a 3041
aada9ce6 3042 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 3043 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 3044 state->curframe + 2);
f4d7e40a
AS
3045 return -E2BIG;
3046 }
3047
3048 target_insn = *insn_idx + insn->imm;
3049 subprog = find_subprog(env, target_insn + 1);
3050 if (subprog < 0) {
3051 verbose(env, "verifier bug. No program starts at insn %d\n",
3052 target_insn + 1);
3053 return -EFAULT;
3054 }
3055
3056 caller = state->frame[state->curframe];
3057 if (state->frame[state->curframe + 1]) {
3058 verbose(env, "verifier bug. Frame %d already allocated\n",
3059 state->curframe + 1);
3060 return -EFAULT;
3061 }
3062
3063 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
3064 if (!callee)
3065 return -ENOMEM;
3066 state->frame[state->curframe + 1] = callee;
3067
3068 /* callee cannot access r0, r6 - r9 for reading and has to write
3069 * into its own stack before reading from it.
3070 * callee can read/write into caller's stack
3071 */
3072 init_func_state(env, callee,
3073 /* remember the callsite, it will be used by bpf_exit */
3074 *insn_idx /* callsite */,
3075 state->curframe + 1 /* frameno within this callchain */,
f910cefa 3076 subprog /* subprog number within this prog */);
f4d7e40a 3077
fd978bf7
JS
3078 /* Transfer references to the callee */
3079 err = transfer_reference_state(callee, caller);
3080 if (err)
3081 return err;
3082
679c782d
EC
3083 /* copy r1 - r5 args that callee can access. The copy includes parent
3084 * pointers, which connects us up to the liveness chain
3085 */
f4d7e40a
AS
3086 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3087 callee->regs[i] = caller->regs[i];
3088
679c782d 3089 /* after the call registers r0 - r5 were scratched */
f4d7e40a
AS
3090 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3091 mark_reg_not_init(env, caller->regs, caller_saved[i]);
3092 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3093 }
3094
3095 /* only increment it after check_reg_arg() finished */
3096 state->curframe++;
3097
3098 /* and go analyze first insn of the callee */
3099 *insn_idx = target_insn;
3100
06ee7115 3101 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
3102 verbose(env, "caller:\n");
3103 print_verifier_state(env, caller);
3104 verbose(env, "callee:\n");
3105 print_verifier_state(env, callee);
3106 }
3107 return 0;
3108}
3109
3110static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
3111{
3112 struct bpf_verifier_state *state = env->cur_state;
3113 struct bpf_func_state *caller, *callee;
3114 struct bpf_reg_state *r0;
fd978bf7 3115 int err;
f4d7e40a
AS
3116
3117 callee = state->frame[state->curframe];
3118 r0 = &callee->regs[BPF_REG_0];
3119 if (r0->type == PTR_TO_STACK) {
3120 /* technically it's ok to return caller's stack pointer
3121 * (or caller's caller's pointer) back to the caller,
3122 * since these pointers are valid. Only current stack
3123 * pointer will be invalid as soon as function exits,
3124 * but let's be conservative
3125 */
3126 verbose(env, "cannot return stack pointer to the caller\n");
3127 return -EINVAL;
3128 }
3129
3130 state->curframe--;
3131 caller = state->frame[state->curframe];
3132 /* return to the caller whatever r0 had in the callee */
3133 caller->regs[BPF_REG_0] = *r0;
3134
fd978bf7
JS
3135 /* Transfer references to the caller */
3136 err = transfer_reference_state(caller, callee);
3137 if (err)
3138 return err;
3139
f4d7e40a 3140 *insn_idx = callee->callsite + 1;
06ee7115 3141 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
3142 verbose(env, "returning from callee:\n");
3143 print_verifier_state(env, callee);
3144 verbose(env, "to caller at %d:\n", *insn_idx);
3145 print_verifier_state(env, caller);
3146 }
3147 /* clear everything in the callee */
3148 free_func_state(callee);
3149 state->frame[state->curframe + 1] = NULL;
3150 return 0;
3151}
3152
849fa506
YS
3153static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
3154 int func_id,
3155 struct bpf_call_arg_meta *meta)
3156{
3157 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
3158
3159 if (ret_type != RET_INTEGER ||
3160 (func_id != BPF_FUNC_get_stack &&
3161 func_id != BPF_FUNC_probe_read_str))
3162 return;
3163
3164 ret_reg->smax_value = meta->msize_smax_value;
3165 ret_reg->umax_value = meta->msize_umax_value;
3166 __reg_deduce_bounds(ret_reg);
3167 __reg_bound_offset(ret_reg);
3168}
3169
c93552c4
DB
3170static int
3171record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
3172 int func_id, int insn_idx)
3173{
3174 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 3175 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
3176
3177 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
3178 func_id != BPF_FUNC_map_lookup_elem &&
3179 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
3180 func_id != BPF_FUNC_map_delete_elem &&
3181 func_id != BPF_FUNC_map_push_elem &&
3182 func_id != BPF_FUNC_map_pop_elem &&
3183 func_id != BPF_FUNC_map_peek_elem)
c93552c4 3184 return 0;
09772d92 3185
591fe988 3186 if (map == NULL) {
c93552c4
DB
3187 verbose(env, "kernel subsystem misconfigured verifier\n");
3188 return -EINVAL;
3189 }
3190
591fe988
DB
3191 /* In case of read-only, some additional restrictions
3192 * need to be applied in order to prevent altering the
3193 * state of the map from program side.
3194 */
3195 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
3196 (func_id == BPF_FUNC_map_delete_elem ||
3197 func_id == BPF_FUNC_map_update_elem ||
3198 func_id == BPF_FUNC_map_push_elem ||
3199 func_id == BPF_FUNC_map_pop_elem)) {
3200 verbose(env, "write into map forbidden\n");
3201 return -EACCES;
3202 }
3203
c93552c4
DB
3204 if (!BPF_MAP_PTR(aux->map_state))
3205 bpf_map_ptr_store(aux, meta->map_ptr,
3206 meta->map_ptr->unpriv_array);
3207 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
3208 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
3209 meta->map_ptr->unpriv_array);
3210 return 0;
3211}
3212
fd978bf7
JS
3213static int check_reference_leak(struct bpf_verifier_env *env)
3214{
3215 struct bpf_func_state *state = cur_func(env);
3216 int i;
3217
3218 for (i = 0; i < state->acquired_refs; i++) {
3219 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
3220 state->refs[i].id, state->refs[i].insn_idx);
3221 }
3222 return state->acquired_refs ? -EINVAL : 0;
3223}
3224
f4d7e40a 3225static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 3226{
17a52670 3227 const struct bpf_func_proto *fn = NULL;
638f5b90 3228 struct bpf_reg_state *regs;
33ff9823 3229 struct bpf_call_arg_meta meta;
969bf05e 3230 bool changes_data;
17a52670
AS
3231 int i, err;
3232
3233 /* find function prototype */
3234 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
3235 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
3236 func_id);
17a52670
AS
3237 return -EINVAL;
3238 }
3239
00176a34 3240 if (env->ops->get_func_proto)
5e43f899 3241 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 3242 if (!fn) {
61bd5218
JK
3243 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
3244 func_id);
17a52670
AS
3245 return -EINVAL;
3246 }
3247
3248 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 3249 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 3250 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
3251 return -EINVAL;
3252 }
3253
04514d13 3254 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 3255 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
3256 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
3257 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
3258 func_id_name(func_id), func_id);
3259 return -EINVAL;
3260 }
969bf05e 3261
33ff9823 3262 memset(&meta, 0, sizeof(meta));
36bbef52 3263 meta.pkt_access = fn->pkt_access;
33ff9823 3264
1b986589 3265 err = check_func_proto(fn, func_id);
435faee1 3266 if (err) {
61bd5218 3267 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 3268 func_id_name(func_id), func_id);
435faee1
DB
3269 return err;
3270 }
3271
d83525ca 3272 meta.func_id = func_id;
17a52670 3273 /* check args */
33ff9823 3274 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
17a52670
AS
3275 if (err)
3276 return err;
33ff9823 3277 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
17a52670
AS
3278 if (err)
3279 return err;
33ff9823 3280 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
17a52670
AS
3281 if (err)
3282 return err;
33ff9823 3283 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
17a52670
AS
3284 if (err)
3285 return err;
33ff9823 3286 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
17a52670
AS
3287 if (err)
3288 return err;
3289
c93552c4
DB
3290 err = record_func_map(env, &meta, func_id, insn_idx);
3291 if (err)
3292 return err;
3293
435faee1
DB
3294 /* Mark slots with STACK_MISC in case of raw mode, stack offset
3295 * is inferred from register state.
3296 */
3297 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
3298 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
3299 BPF_WRITE, -1, false);
435faee1
DB
3300 if (err)
3301 return err;
3302 }
3303
fd978bf7
JS
3304 if (func_id == BPF_FUNC_tail_call) {
3305 err = check_reference_leak(env);
3306 if (err) {
3307 verbose(env, "tail_call would lead to reference leak\n");
3308 return err;
3309 }
3310 } else if (is_release_function(func_id)) {
1b986589 3311 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
3312 if (err) {
3313 verbose(env, "func %s#%d reference has not been acquired before\n",
3314 func_id_name(func_id), func_id);
fd978bf7 3315 return err;
46f8bc92 3316 }
fd978bf7
JS
3317 }
3318
638f5b90 3319 regs = cur_regs(env);
cd339431
RG
3320
3321 /* check that flags argument in get_local_storage(map, flags) is 0,
3322 * this is required because get_local_storage() can't return an error.
3323 */
3324 if (func_id == BPF_FUNC_get_local_storage &&
3325 !register_is_null(&regs[BPF_REG_2])) {
3326 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
3327 return -EINVAL;
3328 }
3329
17a52670 3330 /* reset caller saved regs */
dc503a8a 3331 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 3332 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
3333 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3334 }
17a52670 3335
dc503a8a 3336 /* update return register (already marked as written above) */
17a52670 3337 if (fn->ret_type == RET_INTEGER) {
f1174f77 3338 /* sets type to SCALAR_VALUE */
61bd5218 3339 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
3340 } else if (fn->ret_type == RET_VOID) {
3341 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
3342 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
3343 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 3344 /* There is no offset yet applied, variable or fixed */
61bd5218 3345 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
3346 /* remember map_ptr, so that check_map_access()
3347 * can check 'value_size' boundary of memory access
3348 * to map element returned from bpf_map_lookup_elem()
3349 */
33ff9823 3350 if (meta.map_ptr == NULL) {
61bd5218
JK
3351 verbose(env,
3352 "kernel subsystem misconfigured verifier\n");
17a52670
AS
3353 return -EINVAL;
3354 }
33ff9823 3355 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
3356 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
3357 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
3358 if (map_value_has_spin_lock(meta.map_ptr))
3359 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
3360 } else {
3361 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
3362 regs[BPF_REG_0].id = ++env->id_gen;
3363 }
c64b7983
JS
3364 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
3365 mark_reg_known_zero(env, regs, BPF_REG_0);
3366 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
0f3adc28 3367 regs[BPF_REG_0].id = ++env->id_gen;
85a51f8c
LB
3368 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
3369 mark_reg_known_zero(env, regs, BPF_REG_0);
3370 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
3371 regs[BPF_REG_0].id = ++env->id_gen;
655a51e5
MKL
3372 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
3373 mark_reg_known_zero(env, regs, BPF_REG_0);
3374 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
3375 regs[BPF_REG_0].id = ++env->id_gen;
17a52670 3376 } else {
61bd5218 3377 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 3378 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
3379 return -EINVAL;
3380 }
04fd61ab 3381
0f3adc28 3382 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
3383 /* For release_reference() */
3384 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
0f3adc28
LB
3385 } else if (is_acquire_function(func_id)) {
3386 int id = acquire_reference_state(env, insn_idx);
3387
3388 if (id < 0)
3389 return id;
3390 /* For mark_ptr_or_null_reg() */
3391 regs[BPF_REG_0].id = id;
3392 /* For release_reference() */
3393 regs[BPF_REG_0].ref_obj_id = id;
3394 }
1b986589 3395
849fa506
YS
3396 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
3397
61bd5218 3398 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
3399 if (err)
3400 return err;
04fd61ab 3401
c195651e
YS
3402 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
3403 const char *err_str;
3404
3405#ifdef CONFIG_PERF_EVENTS
3406 err = get_callchain_buffers(sysctl_perf_event_max_stack);
3407 err_str = "cannot get callchain buffer for func %s#%d\n";
3408#else
3409 err = -ENOTSUPP;
3410 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
3411#endif
3412 if (err) {
3413 verbose(env, err_str, func_id_name(func_id), func_id);
3414 return err;
3415 }
3416
3417 env->prog->has_callchain_buf = true;
3418 }
3419
969bf05e
AS
3420 if (changes_data)
3421 clear_all_pkt_pointers(env);
3422 return 0;
3423}
3424
b03c9f9f
EC
3425static bool signed_add_overflows(s64 a, s64 b)
3426{
3427 /* Do the add in u64, where overflow is well-defined */
3428 s64 res = (s64)((u64)a + (u64)b);
3429
3430 if (b < 0)
3431 return res > a;
3432 return res < a;
3433}
3434
3435static bool signed_sub_overflows(s64 a, s64 b)
3436{
3437 /* Do the sub in u64, where overflow is well-defined */
3438 s64 res = (s64)((u64)a - (u64)b);
3439
3440 if (b < 0)
3441 return res < a;
3442 return res > a;
969bf05e
AS
3443}
3444
bb7f0f98
AS
3445static bool check_reg_sane_offset(struct bpf_verifier_env *env,
3446 const struct bpf_reg_state *reg,
3447 enum bpf_reg_type type)
3448{
3449 bool known = tnum_is_const(reg->var_off);
3450 s64 val = reg->var_off.value;
3451 s64 smin = reg->smin_value;
3452
3453 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
3454 verbose(env, "math between %s pointer and %lld is not allowed\n",
3455 reg_type_str[type], val);
3456 return false;
3457 }
3458
3459 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
3460 verbose(env, "%s pointer offset %d is not allowed\n",
3461 reg_type_str[type], reg->off);
3462 return false;
3463 }
3464
3465 if (smin == S64_MIN) {
3466 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
3467 reg_type_str[type]);
3468 return false;
3469 }
3470
3471 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
3472 verbose(env, "value %lld makes %s pointer be out of bounds\n",
3473 smin, reg_type_str[type]);
3474 return false;
3475 }
3476
3477 return true;
3478}
3479
979d63d5
DB
3480static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
3481{
3482 return &env->insn_aux_data[env->insn_idx];
3483}
3484
3485static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
3486 u32 *ptr_limit, u8 opcode, bool off_is_neg)
3487{
3488 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
3489 (opcode == BPF_SUB && !off_is_neg);
3490 u32 off;
3491
3492 switch (ptr_reg->type) {
3493 case PTR_TO_STACK:
088ec26d
AI
3494 /* Indirect variable offset stack access is prohibited in
3495 * unprivileged mode so it's not handled here.
3496 */
979d63d5
DB
3497 off = ptr_reg->off + ptr_reg->var_off.value;
3498 if (mask_to_left)
3499 *ptr_limit = MAX_BPF_STACK + off;
3500 else
3501 *ptr_limit = -off;
3502 return 0;
3503 case PTR_TO_MAP_VALUE:
3504 if (mask_to_left) {
3505 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
3506 } else {
3507 off = ptr_reg->smin_value + ptr_reg->off;
3508 *ptr_limit = ptr_reg->map_ptr->value_size - off;
3509 }
3510 return 0;
3511 default:
3512 return -EINVAL;
3513 }
3514}
3515
d3bd7413
DB
3516static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
3517 const struct bpf_insn *insn)
3518{
3519 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
3520}
3521
3522static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
3523 u32 alu_state, u32 alu_limit)
3524{
3525 /* If we arrived here from different branches with different
3526 * state or limits to sanitize, then this won't work.
3527 */
3528 if (aux->alu_state &&
3529 (aux->alu_state != alu_state ||
3530 aux->alu_limit != alu_limit))
3531 return -EACCES;
3532
3533 /* Corresponding fixup done in fixup_bpf_calls(). */
3534 aux->alu_state = alu_state;
3535 aux->alu_limit = alu_limit;
3536 return 0;
3537}
3538
3539static int sanitize_val_alu(struct bpf_verifier_env *env,
3540 struct bpf_insn *insn)
3541{
3542 struct bpf_insn_aux_data *aux = cur_aux(env);
3543
3544 if (can_skip_alu_sanitation(env, insn))
3545 return 0;
3546
3547 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
3548}
3549
979d63d5
DB
3550static int sanitize_ptr_alu(struct bpf_verifier_env *env,
3551 struct bpf_insn *insn,
3552 const struct bpf_reg_state *ptr_reg,
3553 struct bpf_reg_state *dst_reg,
3554 bool off_is_neg)
3555{
3556 struct bpf_verifier_state *vstate = env->cur_state;
3557 struct bpf_insn_aux_data *aux = cur_aux(env);
3558 bool ptr_is_dst_reg = ptr_reg == dst_reg;
3559 u8 opcode = BPF_OP(insn->code);
3560 u32 alu_state, alu_limit;
3561 struct bpf_reg_state tmp;
3562 bool ret;
3563
d3bd7413 3564 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
3565 return 0;
3566
3567 /* We already marked aux for masking from non-speculative
3568 * paths, thus we got here in the first place. We only care
3569 * to explore bad access from here.
3570 */
3571 if (vstate->speculative)
3572 goto do_sim;
3573
3574 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
3575 alu_state |= ptr_is_dst_reg ?
3576 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
3577
3578 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
3579 return 0;
d3bd7413 3580 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
979d63d5 3581 return -EACCES;
979d63d5
DB
3582do_sim:
3583 /* Simulate and find potential out-of-bounds access under
3584 * speculative execution from truncation as a result of
3585 * masking when off was not within expected range. If off
3586 * sits in dst, then we temporarily need to move ptr there
3587 * to simulate dst (== 0) +/-= ptr. Needed, for example,
3588 * for cases where we use K-based arithmetic in one direction
3589 * and truncated reg-based in the other in order to explore
3590 * bad access.
3591 */
3592 if (!ptr_is_dst_reg) {
3593 tmp = *dst_reg;
3594 *dst_reg = *ptr_reg;
3595 }
3596 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 3597 if (!ptr_is_dst_reg && ret)
979d63d5
DB
3598 *dst_reg = tmp;
3599 return !ret ? -EFAULT : 0;
3600}
3601
f1174f77 3602/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
3603 * Caller should also handle BPF_MOV case separately.
3604 * If we return -EACCES, caller may want to try again treating pointer as a
3605 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
3606 */
3607static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
3608 struct bpf_insn *insn,
3609 const struct bpf_reg_state *ptr_reg,
3610 const struct bpf_reg_state *off_reg)
969bf05e 3611{
f4d7e40a
AS
3612 struct bpf_verifier_state *vstate = env->cur_state;
3613 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3614 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 3615 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
3616 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
3617 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
3618 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
3619 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 3620 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 3621 u8 opcode = BPF_OP(insn->code);
979d63d5 3622 int ret;
969bf05e 3623
f1174f77 3624 dst_reg = &regs[dst];
969bf05e 3625
6f16101e
DB
3626 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
3627 smin_val > smax_val || umin_val > umax_val) {
3628 /* Taint dst register if offset had invalid bounds derived from
3629 * e.g. dead branches.
3630 */
3631 __mark_reg_unknown(dst_reg);
3632 return 0;
f1174f77
EC
3633 }
3634
3635 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3636 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
82abbf8d
AS
3637 verbose(env,
3638 "R%d 32-bit pointer arithmetic prohibited\n",
3639 dst);
f1174f77 3640 return -EACCES;
969bf05e
AS
3641 }
3642
aad2eeaf
JS
3643 switch (ptr_reg->type) {
3644 case PTR_TO_MAP_VALUE_OR_NULL:
3645 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
3646 dst, reg_type_str[ptr_reg->type]);
f1174f77 3647 return -EACCES;
aad2eeaf
JS
3648 case CONST_PTR_TO_MAP:
3649 case PTR_TO_PACKET_END:
c64b7983
JS
3650 case PTR_TO_SOCKET:
3651 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
3652 case PTR_TO_SOCK_COMMON:
3653 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
3654 case PTR_TO_TCP_SOCK:
3655 case PTR_TO_TCP_SOCK_OR_NULL:
aad2eeaf
JS
3656 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
3657 dst, reg_type_str[ptr_reg->type]);
f1174f77 3658 return -EACCES;
9d7eceed
DB
3659 case PTR_TO_MAP_VALUE:
3660 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
3661 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
3662 off_reg == dst_reg ? dst : src);
3663 return -EACCES;
3664 }
3665 /* fall-through */
aad2eeaf
JS
3666 default:
3667 break;
f1174f77
EC
3668 }
3669
3670 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
3671 * The id may be overwritten later if we create a new variable offset.
969bf05e 3672 */
f1174f77
EC
3673 dst_reg->type = ptr_reg->type;
3674 dst_reg->id = ptr_reg->id;
969bf05e 3675
bb7f0f98
AS
3676 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
3677 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
3678 return -EINVAL;
3679
f1174f77
EC
3680 switch (opcode) {
3681 case BPF_ADD:
979d63d5
DB
3682 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
3683 if (ret < 0) {
3684 verbose(env, "R%d tried to add from different maps or paths\n", dst);
3685 return ret;
3686 }
f1174f77
EC
3687 /* We can take a fixed offset as long as it doesn't overflow
3688 * the s32 'off' field
969bf05e 3689 */
b03c9f9f
EC
3690 if (known && (ptr_reg->off + smin_val ==
3691 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 3692 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
3693 dst_reg->smin_value = smin_ptr;
3694 dst_reg->smax_value = smax_ptr;
3695 dst_reg->umin_value = umin_ptr;
3696 dst_reg->umax_value = umax_ptr;
f1174f77 3697 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 3698 dst_reg->off = ptr_reg->off + smin_val;
0962590e 3699 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
3700 break;
3701 }
f1174f77
EC
3702 /* A new variable offset is created. Note that off_reg->off
3703 * == 0, since it's a scalar.
3704 * dst_reg gets the pointer type and since some positive
3705 * integer value was added to the pointer, give it a new 'id'
3706 * if it's a PTR_TO_PACKET.
3707 * this creates a new 'base' pointer, off_reg (variable) gets
3708 * added into the variable offset, and we copy the fixed offset
3709 * from ptr_reg.
969bf05e 3710 */
b03c9f9f
EC
3711 if (signed_add_overflows(smin_ptr, smin_val) ||
3712 signed_add_overflows(smax_ptr, smax_val)) {
3713 dst_reg->smin_value = S64_MIN;
3714 dst_reg->smax_value = S64_MAX;
3715 } else {
3716 dst_reg->smin_value = smin_ptr + smin_val;
3717 dst_reg->smax_value = smax_ptr + smax_val;
3718 }
3719 if (umin_ptr + umin_val < umin_ptr ||
3720 umax_ptr + umax_val < umax_ptr) {
3721 dst_reg->umin_value = 0;
3722 dst_reg->umax_value = U64_MAX;
3723 } else {
3724 dst_reg->umin_value = umin_ptr + umin_val;
3725 dst_reg->umax_value = umax_ptr + umax_val;
3726 }
f1174f77
EC
3727 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
3728 dst_reg->off = ptr_reg->off;
0962590e 3729 dst_reg->raw = ptr_reg->raw;
de8f3a83 3730 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
3731 dst_reg->id = ++env->id_gen;
3732 /* something was added to pkt_ptr, set range to zero */
0962590e 3733 dst_reg->raw = 0;
f1174f77
EC
3734 }
3735 break;
3736 case BPF_SUB:
979d63d5
DB
3737 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
3738 if (ret < 0) {
3739 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
3740 return ret;
3741 }
f1174f77
EC
3742 if (dst_reg == off_reg) {
3743 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
3744 verbose(env, "R%d tried to subtract pointer from scalar\n",
3745 dst);
f1174f77
EC
3746 return -EACCES;
3747 }
3748 /* We don't allow subtraction from FP, because (according to
3749 * test_verifier.c test "invalid fp arithmetic", JITs might not
3750 * be able to deal with it.
969bf05e 3751 */
f1174f77 3752 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
3753 verbose(env, "R%d subtraction from stack pointer prohibited\n",
3754 dst);
f1174f77
EC
3755 return -EACCES;
3756 }
b03c9f9f
EC
3757 if (known && (ptr_reg->off - smin_val ==
3758 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 3759 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
3760 dst_reg->smin_value = smin_ptr;
3761 dst_reg->smax_value = smax_ptr;
3762 dst_reg->umin_value = umin_ptr;
3763 dst_reg->umax_value = umax_ptr;
f1174f77
EC
3764 dst_reg->var_off = ptr_reg->var_off;
3765 dst_reg->id = ptr_reg->id;
b03c9f9f 3766 dst_reg->off = ptr_reg->off - smin_val;
0962590e 3767 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
3768 break;
3769 }
f1174f77
EC
3770 /* A new variable offset is created. If the subtrahend is known
3771 * nonnegative, then any reg->range we had before is still good.
969bf05e 3772 */
b03c9f9f
EC
3773 if (signed_sub_overflows(smin_ptr, smax_val) ||
3774 signed_sub_overflows(smax_ptr, smin_val)) {
3775 /* Overflow possible, we know nothing */
3776 dst_reg->smin_value = S64_MIN;
3777 dst_reg->smax_value = S64_MAX;
3778 } else {
3779 dst_reg->smin_value = smin_ptr - smax_val;
3780 dst_reg->smax_value = smax_ptr - smin_val;
3781 }
3782 if (umin_ptr < umax_val) {
3783 /* Overflow possible, we know nothing */
3784 dst_reg->umin_value = 0;
3785 dst_reg->umax_value = U64_MAX;
3786 } else {
3787 /* Cannot overflow (as long as bounds are consistent) */
3788 dst_reg->umin_value = umin_ptr - umax_val;
3789 dst_reg->umax_value = umax_ptr - umin_val;
3790 }
f1174f77
EC
3791 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
3792 dst_reg->off = ptr_reg->off;
0962590e 3793 dst_reg->raw = ptr_reg->raw;
de8f3a83 3794 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
3795 dst_reg->id = ++env->id_gen;
3796 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 3797 if (smin_val < 0)
0962590e 3798 dst_reg->raw = 0;
43188702 3799 }
f1174f77
EC
3800 break;
3801 case BPF_AND:
3802 case BPF_OR:
3803 case BPF_XOR:
82abbf8d
AS
3804 /* bitwise ops on pointers are troublesome, prohibit. */
3805 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
3806 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
3807 return -EACCES;
3808 default:
3809 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
3810 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
3811 dst, bpf_alu_string[opcode >> 4]);
f1174f77 3812 return -EACCES;
43188702
JF
3813 }
3814
bb7f0f98
AS
3815 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
3816 return -EINVAL;
3817
b03c9f9f
EC
3818 __update_reg_bounds(dst_reg);
3819 __reg_deduce_bounds(dst_reg);
3820 __reg_bound_offset(dst_reg);
0d6303db
DB
3821
3822 /* For unprivileged we require that resulting offset must be in bounds
3823 * in order to be able to sanitize access later on.
3824 */
e4298d25
DB
3825 if (!env->allow_ptr_leaks) {
3826 if (dst_reg->type == PTR_TO_MAP_VALUE &&
3827 check_map_access(env, dst, dst_reg->off, 1, false)) {
3828 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
3829 "prohibited for !root\n", dst);
3830 return -EACCES;
3831 } else if (dst_reg->type == PTR_TO_STACK &&
3832 check_stack_access(env, dst_reg, dst_reg->off +
3833 dst_reg->var_off.value, 1)) {
3834 verbose(env, "R%d stack pointer arithmetic goes out of range, "
3835 "prohibited for !root\n", dst);
3836 return -EACCES;
3837 }
0d6303db
DB
3838 }
3839
43188702
JF
3840 return 0;
3841}
3842
468f6eaf
JH
3843/* WARNING: This function does calculations on 64-bit values, but the actual
3844 * execution may occur on 32-bit values. Therefore, things like bitshifts
3845 * need extra checks in the 32-bit case.
3846 */
f1174f77
EC
3847static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
3848 struct bpf_insn *insn,
3849 struct bpf_reg_state *dst_reg,
3850 struct bpf_reg_state src_reg)
969bf05e 3851{
638f5b90 3852 struct bpf_reg_state *regs = cur_regs(env);
48461135 3853 u8 opcode = BPF_OP(insn->code);
f1174f77 3854 bool src_known, dst_known;
b03c9f9f
EC
3855 s64 smin_val, smax_val;
3856 u64 umin_val, umax_val;
468f6eaf 3857 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
3858 u32 dst = insn->dst_reg;
3859 int ret;
48461135 3860
b799207e
JH
3861 if (insn_bitness == 32) {
3862 /* Relevant for 32-bit RSH: Information can propagate towards
3863 * LSB, so it isn't sufficient to only truncate the output to
3864 * 32 bits.
3865 */
3866 coerce_reg_to_size(dst_reg, 4);
3867 coerce_reg_to_size(&src_reg, 4);
3868 }
3869
b03c9f9f
EC
3870 smin_val = src_reg.smin_value;
3871 smax_val = src_reg.smax_value;
3872 umin_val = src_reg.umin_value;
3873 umax_val = src_reg.umax_value;
f1174f77
EC
3874 src_known = tnum_is_const(src_reg.var_off);
3875 dst_known = tnum_is_const(dst_reg->var_off);
f23cc643 3876
6f16101e
DB
3877 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
3878 smin_val > smax_val || umin_val > umax_val) {
3879 /* Taint dst register if offset had invalid bounds derived from
3880 * e.g. dead branches.
3881 */
3882 __mark_reg_unknown(dst_reg);
3883 return 0;
3884 }
3885
bb7f0f98
AS
3886 if (!src_known &&
3887 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
3888 __mark_reg_unknown(dst_reg);
3889 return 0;
3890 }
3891
48461135
JB
3892 switch (opcode) {
3893 case BPF_ADD:
d3bd7413
DB
3894 ret = sanitize_val_alu(env, insn);
3895 if (ret < 0) {
3896 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
3897 return ret;
3898 }
b03c9f9f
EC
3899 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
3900 signed_add_overflows(dst_reg->smax_value, smax_val)) {
3901 dst_reg->smin_value = S64_MIN;
3902 dst_reg->smax_value = S64_MAX;
3903 } else {
3904 dst_reg->smin_value += smin_val;
3905 dst_reg->smax_value += smax_val;
3906 }
3907 if (dst_reg->umin_value + umin_val < umin_val ||
3908 dst_reg->umax_value + umax_val < umax_val) {
3909 dst_reg->umin_value = 0;
3910 dst_reg->umax_value = U64_MAX;
3911 } else {
3912 dst_reg->umin_value += umin_val;
3913 dst_reg->umax_value += umax_val;
3914 }
f1174f77 3915 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
3916 break;
3917 case BPF_SUB:
d3bd7413
DB
3918 ret = sanitize_val_alu(env, insn);
3919 if (ret < 0) {
3920 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
3921 return ret;
3922 }
b03c9f9f
EC
3923 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
3924 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
3925 /* Overflow possible, we know nothing */
3926 dst_reg->smin_value = S64_MIN;
3927 dst_reg->smax_value = S64_MAX;
3928 } else {
3929 dst_reg->smin_value -= smax_val;
3930 dst_reg->smax_value -= smin_val;
3931 }
3932 if (dst_reg->umin_value < umax_val) {
3933 /* Overflow possible, we know nothing */
3934 dst_reg->umin_value = 0;
3935 dst_reg->umax_value = U64_MAX;
3936 } else {
3937 /* Cannot overflow (as long as bounds are consistent) */
3938 dst_reg->umin_value -= umax_val;
3939 dst_reg->umax_value -= umin_val;
3940 }
f1174f77 3941 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
3942 break;
3943 case BPF_MUL:
b03c9f9f
EC
3944 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
3945 if (smin_val < 0 || dst_reg->smin_value < 0) {
f1174f77 3946 /* Ain't nobody got time to multiply that sign */
b03c9f9f
EC
3947 __mark_reg_unbounded(dst_reg);
3948 __update_reg_bounds(dst_reg);
f1174f77
EC
3949 break;
3950 }
b03c9f9f
EC
3951 /* Both values are positive, so we can work with unsigned and
3952 * copy the result to signed (unless it exceeds S64_MAX).
f1174f77 3953 */
b03c9f9f
EC
3954 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
3955 /* Potential overflow, we know nothing */
3956 __mark_reg_unbounded(dst_reg);
3957 /* (except what we can learn from the var_off) */
3958 __update_reg_bounds(dst_reg);
3959 break;
3960 }
3961 dst_reg->umin_value *= umin_val;
3962 dst_reg->umax_value *= umax_val;
3963 if (dst_reg->umax_value > S64_MAX) {
3964 /* Overflow possible, we know nothing */
3965 dst_reg->smin_value = S64_MIN;
3966 dst_reg->smax_value = S64_MAX;
3967 } else {
3968 dst_reg->smin_value = dst_reg->umin_value;
3969 dst_reg->smax_value = dst_reg->umax_value;
3970 }
48461135
JB
3971 break;
3972 case BPF_AND:
f1174f77 3973 if (src_known && dst_known) {
b03c9f9f
EC
3974 __mark_reg_known(dst_reg, dst_reg->var_off.value &
3975 src_reg.var_off.value);
f1174f77
EC
3976 break;
3977 }
b03c9f9f
EC
3978 /* We get our minimum from the var_off, since that's inherently
3979 * bitwise. Our maximum is the minimum of the operands' maxima.
f23cc643 3980 */
f1174f77 3981 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
b03c9f9f
EC
3982 dst_reg->umin_value = dst_reg->var_off.value;
3983 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
3984 if (dst_reg->smin_value < 0 || smin_val < 0) {
3985 /* Lose signed bounds when ANDing negative numbers,
3986 * ain't nobody got time for that.
3987 */
3988 dst_reg->smin_value = S64_MIN;
3989 dst_reg->smax_value = S64_MAX;
3990 } else {
3991 /* ANDing two positives gives a positive, so safe to
3992 * cast result into s64.
3993 */
3994 dst_reg->smin_value = dst_reg->umin_value;
3995 dst_reg->smax_value = dst_reg->umax_value;
3996 }
3997 /* We may learn something more from the var_off */
3998 __update_reg_bounds(dst_reg);
f1174f77
EC
3999 break;
4000 case BPF_OR:
4001 if (src_known && dst_known) {
b03c9f9f
EC
4002 __mark_reg_known(dst_reg, dst_reg->var_off.value |
4003 src_reg.var_off.value);
f1174f77
EC
4004 break;
4005 }
b03c9f9f
EC
4006 /* We get our maximum from the var_off, and our minimum is the
4007 * maximum of the operands' minima
f1174f77
EC
4008 */
4009 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
b03c9f9f
EC
4010 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
4011 dst_reg->umax_value = dst_reg->var_off.value |
4012 dst_reg->var_off.mask;
4013 if (dst_reg->smin_value < 0 || smin_val < 0) {
4014 /* Lose signed bounds when ORing negative numbers,
4015 * ain't nobody got time for that.
4016 */
4017 dst_reg->smin_value = S64_MIN;
4018 dst_reg->smax_value = S64_MAX;
f1174f77 4019 } else {
b03c9f9f
EC
4020 /* ORing two positives gives a positive, so safe to
4021 * cast result into s64.
4022 */
4023 dst_reg->smin_value = dst_reg->umin_value;
4024 dst_reg->smax_value = dst_reg->umax_value;
f1174f77 4025 }
b03c9f9f
EC
4026 /* We may learn something more from the var_off */
4027 __update_reg_bounds(dst_reg);
48461135
JB
4028 break;
4029 case BPF_LSH:
468f6eaf
JH
4030 if (umax_val >= insn_bitness) {
4031 /* Shifts greater than 31 or 63 are undefined.
4032 * This includes shifts by a negative number.
b03c9f9f 4033 */
61bd5218 4034 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
4035 break;
4036 }
b03c9f9f
EC
4037 /* We lose all sign bit information (except what we can pick
4038 * up from var_off)
48461135 4039 */
b03c9f9f
EC
4040 dst_reg->smin_value = S64_MIN;
4041 dst_reg->smax_value = S64_MAX;
4042 /* If we might shift our top bit out, then we know nothing */
4043 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
4044 dst_reg->umin_value = 0;
4045 dst_reg->umax_value = U64_MAX;
d1174416 4046 } else {
b03c9f9f
EC
4047 dst_reg->umin_value <<= umin_val;
4048 dst_reg->umax_value <<= umax_val;
d1174416 4049 }
afbe1a5b 4050 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
b03c9f9f
EC
4051 /* We may learn something more from the var_off */
4052 __update_reg_bounds(dst_reg);
48461135
JB
4053 break;
4054 case BPF_RSH:
468f6eaf
JH
4055 if (umax_val >= insn_bitness) {
4056 /* Shifts greater than 31 or 63 are undefined.
4057 * This includes shifts by a negative number.
b03c9f9f 4058 */
61bd5218 4059 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
4060 break;
4061 }
4374f256
EC
4062 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
4063 * be negative, then either:
4064 * 1) src_reg might be zero, so the sign bit of the result is
4065 * unknown, so we lose our signed bounds
4066 * 2) it's known negative, thus the unsigned bounds capture the
4067 * signed bounds
4068 * 3) the signed bounds cross zero, so they tell us nothing
4069 * about the result
4070 * If the value in dst_reg is known nonnegative, then again the
4071 * unsigned bounts capture the signed bounds.
4072 * Thus, in all cases it suffices to blow away our signed bounds
4073 * and rely on inferring new ones from the unsigned bounds and
4074 * var_off of the result.
4075 */
4076 dst_reg->smin_value = S64_MIN;
4077 dst_reg->smax_value = S64_MAX;
afbe1a5b 4078 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
b03c9f9f
EC
4079 dst_reg->umin_value >>= umax_val;
4080 dst_reg->umax_value >>= umin_val;
4081 /* We may learn something more from the var_off */
4082 __update_reg_bounds(dst_reg);
48461135 4083 break;
9cbe1f5a
YS
4084 case BPF_ARSH:
4085 if (umax_val >= insn_bitness) {
4086 /* Shifts greater than 31 or 63 are undefined.
4087 * This includes shifts by a negative number.
4088 */
4089 mark_reg_unknown(env, regs, insn->dst_reg);
4090 break;
4091 }
4092
4093 /* Upon reaching here, src_known is true and
4094 * umax_val is equal to umin_val.
4095 */
4096 dst_reg->smin_value >>= umin_val;
4097 dst_reg->smax_value >>= umin_val;
4098 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
4099
4100 /* blow away the dst_reg umin_value/umax_value and rely on
4101 * dst_reg var_off to refine the result.
4102 */
4103 dst_reg->umin_value = 0;
4104 dst_reg->umax_value = U64_MAX;
4105 __update_reg_bounds(dst_reg);
4106 break;
48461135 4107 default:
61bd5218 4108 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
4109 break;
4110 }
4111
468f6eaf
JH
4112 if (BPF_CLASS(insn->code) != BPF_ALU64) {
4113 /* 32-bit ALU ops are (32,32)->32 */
4114 coerce_reg_to_size(dst_reg, 4);
468f6eaf
JH
4115 }
4116
b03c9f9f
EC
4117 __reg_deduce_bounds(dst_reg);
4118 __reg_bound_offset(dst_reg);
f1174f77
EC
4119 return 0;
4120}
4121
4122/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
4123 * and var_off.
4124 */
4125static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
4126 struct bpf_insn *insn)
4127{
f4d7e40a
AS
4128 struct bpf_verifier_state *vstate = env->cur_state;
4129 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4130 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
4131 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
4132 u8 opcode = BPF_OP(insn->code);
f1174f77
EC
4133
4134 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
4135 src_reg = NULL;
4136 if (dst_reg->type != SCALAR_VALUE)
4137 ptr_reg = dst_reg;
4138 if (BPF_SRC(insn->code) == BPF_X) {
4139 src_reg = &regs[insn->src_reg];
f1174f77
EC
4140 if (src_reg->type != SCALAR_VALUE) {
4141 if (dst_reg->type != SCALAR_VALUE) {
4142 /* Combining two pointers by any ALU op yields
82abbf8d
AS
4143 * an arbitrary scalar. Disallow all math except
4144 * pointer subtraction
f1174f77 4145 */
dd066823 4146 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
4147 mark_reg_unknown(env, regs, insn->dst_reg);
4148 return 0;
f1174f77 4149 }
82abbf8d
AS
4150 verbose(env, "R%d pointer %s pointer prohibited\n",
4151 insn->dst_reg,
4152 bpf_alu_string[opcode >> 4]);
4153 return -EACCES;
f1174f77
EC
4154 } else {
4155 /* scalar += pointer
4156 * This is legal, but we have to reverse our
4157 * src/dest handling in computing the range
4158 */
82abbf8d
AS
4159 return adjust_ptr_min_max_vals(env, insn,
4160 src_reg, dst_reg);
f1174f77
EC
4161 }
4162 } else if (ptr_reg) {
4163 /* pointer += scalar */
82abbf8d
AS
4164 return adjust_ptr_min_max_vals(env, insn,
4165 dst_reg, src_reg);
f1174f77
EC
4166 }
4167 } else {
4168 /* Pretend the src is a reg with a known value, since we only
4169 * need to be able to read from this state.
4170 */
4171 off_reg.type = SCALAR_VALUE;
b03c9f9f 4172 __mark_reg_known(&off_reg, insn->imm);
f1174f77 4173 src_reg = &off_reg;
82abbf8d
AS
4174 if (ptr_reg) /* pointer += K */
4175 return adjust_ptr_min_max_vals(env, insn,
4176 ptr_reg, src_reg);
f1174f77
EC
4177 }
4178
4179 /* Got here implies adding two SCALAR_VALUEs */
4180 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 4181 print_verifier_state(env, state);
61bd5218 4182 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
4183 return -EINVAL;
4184 }
4185 if (WARN_ON(!src_reg)) {
f4d7e40a 4186 print_verifier_state(env, state);
61bd5218 4187 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
4188 return -EINVAL;
4189 }
4190 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
4191}
4192
17a52670 4193/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 4194static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 4195{
638f5b90 4196 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
4197 u8 opcode = BPF_OP(insn->code);
4198 int err;
4199
4200 if (opcode == BPF_END || opcode == BPF_NEG) {
4201 if (opcode == BPF_NEG) {
4202 if (BPF_SRC(insn->code) != 0 ||
4203 insn->src_reg != BPF_REG_0 ||
4204 insn->off != 0 || insn->imm != 0) {
61bd5218 4205 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
4206 return -EINVAL;
4207 }
4208 } else {
4209 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
4210 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
4211 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 4212 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
4213 return -EINVAL;
4214 }
4215 }
4216
4217 /* check src operand */
dc503a8a 4218 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4219 if (err)
4220 return err;
4221
1be7f75d 4222 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 4223 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
4224 insn->dst_reg);
4225 return -EACCES;
4226 }
4227
17a52670 4228 /* check dest operand */
dc503a8a 4229 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
4230 if (err)
4231 return err;
4232
4233 } else if (opcode == BPF_MOV) {
4234
4235 if (BPF_SRC(insn->code) == BPF_X) {
4236 if (insn->imm != 0 || insn->off != 0) {
61bd5218 4237 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
4238 return -EINVAL;
4239 }
4240
4241 /* check src operand */
dc503a8a 4242 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4243 if (err)
4244 return err;
4245 } else {
4246 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 4247 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
4248 return -EINVAL;
4249 }
4250 }
4251
fbeb1603
AF
4252 /* check dest operand, mark as required later */
4253 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
4254 if (err)
4255 return err;
4256
4257 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
4258 struct bpf_reg_state *src_reg = regs + insn->src_reg;
4259 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
4260
17a52670
AS
4261 if (BPF_CLASS(insn->code) == BPF_ALU64) {
4262 /* case: R1 = R2
4263 * copy register state to dest reg
4264 */
e434b8cd
JW
4265 *dst_reg = *src_reg;
4266 dst_reg->live |= REG_LIVE_WRITTEN;
17a52670 4267 } else {
f1174f77 4268 /* R1 = (u32) R2 */
1be7f75d 4269 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
4270 verbose(env,
4271 "R%d partial copy of pointer\n",
1be7f75d
AS
4272 insn->src_reg);
4273 return -EACCES;
e434b8cd
JW
4274 } else if (src_reg->type == SCALAR_VALUE) {
4275 *dst_reg = *src_reg;
4276 dst_reg->live |= REG_LIVE_WRITTEN;
4277 } else {
4278 mark_reg_unknown(env, regs,
4279 insn->dst_reg);
1be7f75d 4280 }
e434b8cd 4281 coerce_reg_to_size(dst_reg, 4);
17a52670
AS
4282 }
4283 } else {
4284 /* case: R = imm
4285 * remember the value we stored into this reg
4286 */
fbeb1603
AF
4287 /* clear any state __mark_reg_known doesn't set */
4288 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 4289 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
4290 if (BPF_CLASS(insn->code) == BPF_ALU64) {
4291 __mark_reg_known(regs + insn->dst_reg,
4292 insn->imm);
4293 } else {
4294 __mark_reg_known(regs + insn->dst_reg,
4295 (u32)insn->imm);
4296 }
17a52670
AS
4297 }
4298
4299 } else if (opcode > BPF_END) {
61bd5218 4300 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
4301 return -EINVAL;
4302
4303 } else { /* all other ALU ops: and, sub, xor, add, ... */
4304
17a52670
AS
4305 if (BPF_SRC(insn->code) == BPF_X) {
4306 if (insn->imm != 0 || insn->off != 0) {
61bd5218 4307 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
4308 return -EINVAL;
4309 }
4310 /* check src1 operand */
dc503a8a 4311 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4312 if (err)
4313 return err;
4314 } else {
4315 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 4316 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
4317 return -EINVAL;
4318 }
4319 }
4320
4321 /* check src2 operand */
dc503a8a 4322 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4323 if (err)
4324 return err;
4325
4326 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
4327 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 4328 verbose(env, "div by zero\n");
17a52670
AS
4329 return -EINVAL;
4330 }
4331
229394e8
RV
4332 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
4333 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
4334 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
4335
4336 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 4337 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
4338 return -EINVAL;
4339 }
4340 }
4341
1a0dc1ac 4342 /* check dest operand */
dc503a8a 4343 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
4344 if (err)
4345 return err;
4346
f1174f77 4347 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
4348 }
4349
4350 return 0;
4351}
4352
c6a9efa1
PC
4353static void __find_good_pkt_pointers(struct bpf_func_state *state,
4354 struct bpf_reg_state *dst_reg,
4355 enum bpf_reg_type type, u16 new_range)
4356{
4357 struct bpf_reg_state *reg;
4358 int i;
4359
4360 for (i = 0; i < MAX_BPF_REG; i++) {
4361 reg = &state->regs[i];
4362 if (reg->type == type && reg->id == dst_reg->id)
4363 /* keep the maximum range already checked */
4364 reg->range = max(reg->range, new_range);
4365 }
4366
4367 bpf_for_each_spilled_reg(i, state, reg) {
4368 if (!reg)
4369 continue;
4370 if (reg->type == type && reg->id == dst_reg->id)
4371 reg->range = max(reg->range, new_range);
4372 }
4373}
4374
f4d7e40a 4375static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 4376 struct bpf_reg_state *dst_reg,
f8ddadc4 4377 enum bpf_reg_type type,
fb2a311a 4378 bool range_right_open)
969bf05e 4379{
fb2a311a 4380 u16 new_range;
c6a9efa1 4381 int i;
2d2be8ca 4382
fb2a311a
DB
4383 if (dst_reg->off < 0 ||
4384 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
4385 /* This doesn't give us any range */
4386 return;
4387
b03c9f9f
EC
4388 if (dst_reg->umax_value > MAX_PACKET_OFF ||
4389 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
4390 /* Risk of overflow. For instance, ptr + (1<<63) may be less
4391 * than pkt_end, but that's because it's also less than pkt.
4392 */
4393 return;
4394
fb2a311a
DB
4395 new_range = dst_reg->off;
4396 if (range_right_open)
4397 new_range--;
4398
4399 /* Examples for register markings:
2d2be8ca 4400 *
fb2a311a 4401 * pkt_data in dst register:
2d2be8ca
DB
4402 *
4403 * r2 = r3;
4404 * r2 += 8;
4405 * if (r2 > pkt_end) goto <handle exception>
4406 * <access okay>
4407 *
b4e432f1
DB
4408 * r2 = r3;
4409 * r2 += 8;
4410 * if (r2 < pkt_end) goto <access okay>
4411 * <handle exception>
4412 *
2d2be8ca
DB
4413 * Where:
4414 * r2 == dst_reg, pkt_end == src_reg
4415 * r2=pkt(id=n,off=8,r=0)
4416 * r3=pkt(id=n,off=0,r=0)
4417 *
fb2a311a 4418 * pkt_data in src register:
2d2be8ca
DB
4419 *
4420 * r2 = r3;
4421 * r2 += 8;
4422 * if (pkt_end >= r2) goto <access okay>
4423 * <handle exception>
4424 *
b4e432f1
DB
4425 * r2 = r3;
4426 * r2 += 8;
4427 * if (pkt_end <= r2) goto <handle exception>
4428 * <access okay>
4429 *
2d2be8ca
DB
4430 * Where:
4431 * pkt_end == dst_reg, r2 == src_reg
4432 * r2=pkt(id=n,off=8,r=0)
4433 * r3=pkt(id=n,off=0,r=0)
4434 *
4435 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
4436 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
4437 * and [r3, r3 + 8-1) respectively is safe to access depending on
4438 * the check.
969bf05e 4439 */
2d2be8ca 4440
f1174f77
EC
4441 /* If our ids match, then we must have the same max_value. And we
4442 * don't care about the other reg's fixed offset, since if it's too big
4443 * the range won't allow anything.
4444 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
4445 */
c6a9efa1
PC
4446 for (i = 0; i <= vstate->curframe; i++)
4447 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
4448 new_range);
969bf05e
AS
4449}
4450
4f7b3e82
AS
4451/* compute branch direction of the expression "if (reg opcode val) goto target;"
4452 * and return:
4453 * 1 - branch will be taken and "goto target" will be executed
4454 * 0 - branch will not be taken and fall-through to next insn
4455 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
4456 */
092ed096
JW
4457static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
4458 bool is_jmp32)
4f7b3e82 4459{
092ed096 4460 struct bpf_reg_state reg_lo;
a72dafaf
JW
4461 s64 sval;
4462
4f7b3e82
AS
4463 if (__is_pointer_value(false, reg))
4464 return -1;
4465
092ed096
JW
4466 if (is_jmp32) {
4467 reg_lo = *reg;
4468 reg = &reg_lo;
4469 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
4470 * could truncate high bits and update umin/umax according to
4471 * information of low bits.
4472 */
4473 coerce_reg_to_size(reg, 4);
4474 /* smin/smax need special handling. For example, after coerce,
4475 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
4476 * used as operand to JMP32. It is a negative number from s32's
4477 * point of view, while it is a positive number when seen as
4478 * s64. The smin/smax are kept as s64, therefore, when used with
4479 * JMP32, they need to be transformed into s32, then sign
4480 * extended back to s64.
4481 *
4482 * Also, smin/smax were copied from umin/umax. If umin/umax has
4483 * different sign bit, then min/max relationship doesn't
4484 * maintain after casting into s32, for this case, set smin/smax
4485 * to safest range.
4486 */
4487 if ((reg->umax_value ^ reg->umin_value) &
4488 (1ULL << 31)) {
4489 reg->smin_value = S32_MIN;
4490 reg->smax_value = S32_MAX;
4491 }
4492 reg->smin_value = (s64)(s32)reg->smin_value;
4493 reg->smax_value = (s64)(s32)reg->smax_value;
4494
4495 val = (u32)val;
4496 sval = (s64)(s32)val;
4497 } else {
4498 sval = (s64)val;
4499 }
a72dafaf 4500
4f7b3e82
AS
4501 switch (opcode) {
4502 case BPF_JEQ:
4503 if (tnum_is_const(reg->var_off))
4504 return !!tnum_equals_const(reg->var_off, val);
4505 break;
4506 case BPF_JNE:
4507 if (tnum_is_const(reg->var_off))
4508 return !tnum_equals_const(reg->var_off, val);
4509 break;
960ea056
JK
4510 case BPF_JSET:
4511 if ((~reg->var_off.mask & reg->var_off.value) & val)
4512 return 1;
4513 if (!((reg->var_off.mask | reg->var_off.value) & val))
4514 return 0;
4515 break;
4f7b3e82
AS
4516 case BPF_JGT:
4517 if (reg->umin_value > val)
4518 return 1;
4519 else if (reg->umax_value <= val)
4520 return 0;
4521 break;
4522 case BPF_JSGT:
a72dafaf 4523 if (reg->smin_value > sval)
4f7b3e82 4524 return 1;
a72dafaf 4525 else if (reg->smax_value < sval)
4f7b3e82
AS
4526 return 0;
4527 break;
4528 case BPF_JLT:
4529 if (reg->umax_value < val)
4530 return 1;
4531 else if (reg->umin_value >= val)
4532 return 0;
4533 break;
4534 case BPF_JSLT:
a72dafaf 4535 if (reg->smax_value < sval)
4f7b3e82 4536 return 1;
a72dafaf 4537 else if (reg->smin_value >= sval)
4f7b3e82
AS
4538 return 0;
4539 break;
4540 case BPF_JGE:
4541 if (reg->umin_value >= val)
4542 return 1;
4543 else if (reg->umax_value < val)
4544 return 0;
4545 break;
4546 case BPF_JSGE:
a72dafaf 4547 if (reg->smin_value >= sval)
4f7b3e82 4548 return 1;
a72dafaf 4549 else if (reg->smax_value < sval)
4f7b3e82
AS
4550 return 0;
4551 break;
4552 case BPF_JLE:
4553 if (reg->umax_value <= val)
4554 return 1;
4555 else if (reg->umin_value > val)
4556 return 0;
4557 break;
4558 case BPF_JSLE:
a72dafaf 4559 if (reg->smax_value <= sval)
4f7b3e82 4560 return 1;
a72dafaf 4561 else if (reg->smin_value > sval)
4f7b3e82
AS
4562 return 0;
4563 break;
4564 }
4565
4566 return -1;
4567}
4568
092ed096
JW
4569/* Generate min value of the high 32-bit from TNUM info. */
4570static u64 gen_hi_min(struct tnum var)
4571{
4572 return var.value & ~0xffffffffULL;
4573}
4574
4575/* Generate max value of the high 32-bit from TNUM info. */
4576static u64 gen_hi_max(struct tnum var)
4577{
4578 return (var.value | var.mask) & ~0xffffffffULL;
4579}
4580
4581/* Return true if VAL is compared with a s64 sign extended from s32, and they
4582 * are with the same signedness.
4583 */
4584static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
4585{
4586 return ((s32)sval >= 0 &&
4587 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
4588 ((s32)sval < 0 &&
4589 reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
4590}
4591
48461135
JB
4592/* Adjusts the register min/max values in the case that the dst_reg is the
4593 * variable register that we are working on, and src_reg is a constant or we're
4594 * simply doing a BPF_K check.
f1174f77 4595 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
4596 */
4597static void reg_set_min_max(struct bpf_reg_state *true_reg,
4598 struct bpf_reg_state *false_reg, u64 val,
092ed096 4599 u8 opcode, bool is_jmp32)
48461135 4600{
a72dafaf
JW
4601 s64 sval;
4602
f1174f77
EC
4603 /* If the dst_reg is a pointer, we can't learn anything about its
4604 * variable offset from the compare (unless src_reg were a pointer into
4605 * the same object, but we don't bother with that.
4606 * Since false_reg and true_reg have the same type by construction, we
4607 * only need to check one of them for pointerness.
4608 */
4609 if (__is_pointer_value(false, false_reg))
4610 return;
4cabc5b1 4611
092ed096
JW
4612 val = is_jmp32 ? (u32)val : val;
4613 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
a72dafaf 4614
48461135
JB
4615 switch (opcode) {
4616 case BPF_JEQ:
48461135 4617 case BPF_JNE:
a72dafaf
JW
4618 {
4619 struct bpf_reg_state *reg =
4620 opcode == BPF_JEQ ? true_reg : false_reg;
4621
4622 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
4623 * if it is true we know the value for sure. Likewise for
4624 * BPF_JNE.
48461135 4625 */
092ed096
JW
4626 if (is_jmp32) {
4627 u64 old_v = reg->var_off.value;
4628 u64 hi_mask = ~0xffffffffULL;
4629
4630 reg->var_off.value = (old_v & hi_mask) | val;
4631 reg->var_off.mask &= hi_mask;
4632 } else {
4633 __mark_reg_known(reg, val);
4634 }
48461135 4635 break;
a72dafaf 4636 }
960ea056
JK
4637 case BPF_JSET:
4638 false_reg->var_off = tnum_and(false_reg->var_off,
4639 tnum_const(~val));
4640 if (is_power_of_2(val))
4641 true_reg->var_off = tnum_or(true_reg->var_off,
4642 tnum_const(val));
4643 break;
48461135 4644 case BPF_JGE:
a72dafaf
JW
4645 case BPF_JGT:
4646 {
4647 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
4648 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
4649
092ed096
JW
4650 if (is_jmp32) {
4651 false_umax += gen_hi_max(false_reg->var_off);
4652 true_umin += gen_hi_min(true_reg->var_off);
4653 }
a72dafaf
JW
4654 false_reg->umax_value = min(false_reg->umax_value, false_umax);
4655 true_reg->umin_value = max(true_reg->umin_value, true_umin);
b03c9f9f 4656 break;
a72dafaf 4657 }
48461135 4658 case BPF_JSGE:
a72dafaf
JW
4659 case BPF_JSGT:
4660 {
4661 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
4662 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
4663
092ed096
JW
4664 /* If the full s64 was not sign-extended from s32 then don't
4665 * deduct further info.
4666 */
4667 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4668 break;
a72dafaf
JW
4669 false_reg->smax_value = min(false_reg->smax_value, false_smax);
4670 true_reg->smin_value = max(true_reg->smin_value, true_smin);
48461135 4671 break;
a72dafaf 4672 }
b4e432f1 4673 case BPF_JLE:
a72dafaf
JW
4674 case BPF_JLT:
4675 {
4676 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
4677 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
4678
092ed096
JW
4679 if (is_jmp32) {
4680 false_umin += gen_hi_min(false_reg->var_off);
4681 true_umax += gen_hi_max(true_reg->var_off);
4682 }
a72dafaf
JW
4683 false_reg->umin_value = max(false_reg->umin_value, false_umin);
4684 true_reg->umax_value = min(true_reg->umax_value, true_umax);
b4e432f1 4685 break;
a72dafaf 4686 }
b4e432f1 4687 case BPF_JSLE:
a72dafaf
JW
4688 case BPF_JSLT:
4689 {
4690 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
4691 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
4692
092ed096
JW
4693 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4694 break;
a72dafaf
JW
4695 false_reg->smin_value = max(false_reg->smin_value, false_smin);
4696 true_reg->smax_value = min(true_reg->smax_value, true_smax);
b4e432f1 4697 break;
a72dafaf 4698 }
48461135
JB
4699 default:
4700 break;
4701 }
4702
b03c9f9f
EC
4703 __reg_deduce_bounds(false_reg);
4704 __reg_deduce_bounds(true_reg);
4705 /* We might have learned some bits from the bounds. */
4706 __reg_bound_offset(false_reg);
4707 __reg_bound_offset(true_reg);
4708 /* Intersecting with the old var_off might have improved our bounds
4709 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4710 * then new var_off is (0; 0x7f...fc) which improves our umax.
4711 */
4712 __update_reg_bounds(false_reg);
4713 __update_reg_bounds(true_reg);
48461135
JB
4714}
4715
f1174f77
EC
4716/* Same as above, but for the case that dst_reg holds a constant and src_reg is
4717 * the variable reg.
48461135
JB
4718 */
4719static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
4720 struct bpf_reg_state *false_reg, u64 val,
092ed096 4721 u8 opcode, bool is_jmp32)
48461135 4722{
a72dafaf
JW
4723 s64 sval;
4724
f1174f77
EC
4725 if (__is_pointer_value(false, false_reg))
4726 return;
4cabc5b1 4727
092ed096
JW
4728 val = is_jmp32 ? (u32)val : val;
4729 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
a72dafaf 4730
48461135
JB
4731 switch (opcode) {
4732 case BPF_JEQ:
48461135 4733 case BPF_JNE:
a72dafaf
JW
4734 {
4735 struct bpf_reg_state *reg =
4736 opcode == BPF_JEQ ? true_reg : false_reg;
4737
092ed096
JW
4738 if (is_jmp32) {
4739 u64 old_v = reg->var_off.value;
4740 u64 hi_mask = ~0xffffffffULL;
4741
4742 reg->var_off.value = (old_v & hi_mask) | val;
4743 reg->var_off.mask &= hi_mask;
4744 } else {
4745 __mark_reg_known(reg, val);
4746 }
48461135 4747 break;
a72dafaf 4748 }
960ea056
JK
4749 case BPF_JSET:
4750 false_reg->var_off = tnum_and(false_reg->var_off,
4751 tnum_const(~val));
4752 if (is_power_of_2(val))
4753 true_reg->var_off = tnum_or(true_reg->var_off,
4754 tnum_const(val));
4755 break;
48461135 4756 case BPF_JGE:
a72dafaf
JW
4757 case BPF_JGT:
4758 {
4759 u64 false_umin = opcode == BPF_JGT ? val : val + 1;
4760 u64 true_umax = opcode == BPF_JGT ? val - 1 : val;
4761
092ed096
JW
4762 if (is_jmp32) {
4763 false_umin += gen_hi_min(false_reg->var_off);
4764 true_umax += gen_hi_max(true_reg->var_off);
4765 }
a72dafaf
JW
4766 false_reg->umin_value = max(false_reg->umin_value, false_umin);
4767 true_reg->umax_value = min(true_reg->umax_value, true_umax);
b03c9f9f 4768 break;
a72dafaf 4769 }
48461135 4770 case BPF_JSGE:
a72dafaf
JW
4771 case BPF_JSGT:
4772 {
4773 s64 false_smin = opcode == BPF_JSGT ? sval : sval + 1;
4774 s64 true_smax = opcode == BPF_JSGT ? sval - 1 : sval;
4775
092ed096
JW
4776 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4777 break;
a72dafaf
JW
4778 false_reg->smin_value = max(false_reg->smin_value, false_smin);
4779 true_reg->smax_value = min(true_reg->smax_value, true_smax);
48461135 4780 break;
a72dafaf 4781 }
b4e432f1 4782 case BPF_JLE:
a72dafaf
JW
4783 case BPF_JLT:
4784 {
4785 u64 false_umax = opcode == BPF_JLT ? val : val - 1;
4786 u64 true_umin = opcode == BPF_JLT ? val + 1 : val;
4787
092ed096
JW
4788 if (is_jmp32) {
4789 false_umax += gen_hi_max(false_reg->var_off);
4790 true_umin += gen_hi_min(true_reg->var_off);
4791 }
a72dafaf
JW
4792 false_reg->umax_value = min(false_reg->umax_value, false_umax);
4793 true_reg->umin_value = max(true_reg->umin_value, true_umin);
b4e432f1 4794 break;
a72dafaf 4795 }
b4e432f1 4796 case BPF_JSLE:
a72dafaf
JW
4797 case BPF_JSLT:
4798 {
4799 s64 false_smax = opcode == BPF_JSLT ? sval : sval - 1;
4800 s64 true_smin = opcode == BPF_JSLT ? sval + 1 : sval;
4801
092ed096
JW
4802 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4803 break;
a72dafaf
JW
4804 false_reg->smax_value = min(false_reg->smax_value, false_smax);
4805 true_reg->smin_value = max(true_reg->smin_value, true_smin);
b4e432f1 4806 break;
a72dafaf 4807 }
48461135
JB
4808 default:
4809 break;
4810 }
4811
b03c9f9f
EC
4812 __reg_deduce_bounds(false_reg);
4813 __reg_deduce_bounds(true_reg);
4814 /* We might have learned some bits from the bounds. */
4815 __reg_bound_offset(false_reg);
4816 __reg_bound_offset(true_reg);
4817 /* Intersecting with the old var_off might have improved our bounds
4818 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4819 * then new var_off is (0; 0x7f...fc) which improves our umax.
4820 */
4821 __update_reg_bounds(false_reg);
4822 __update_reg_bounds(true_reg);
f1174f77
EC
4823}
4824
4825/* Regs are known to be equal, so intersect their min/max/var_off */
4826static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
4827 struct bpf_reg_state *dst_reg)
4828{
b03c9f9f
EC
4829 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
4830 dst_reg->umin_value);
4831 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
4832 dst_reg->umax_value);
4833 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
4834 dst_reg->smin_value);
4835 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
4836 dst_reg->smax_value);
f1174f77
EC
4837 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
4838 dst_reg->var_off);
b03c9f9f
EC
4839 /* We might have learned new bounds from the var_off. */
4840 __update_reg_bounds(src_reg);
4841 __update_reg_bounds(dst_reg);
4842 /* We might have learned something about the sign bit. */
4843 __reg_deduce_bounds(src_reg);
4844 __reg_deduce_bounds(dst_reg);
4845 /* We might have learned some bits from the bounds. */
4846 __reg_bound_offset(src_reg);
4847 __reg_bound_offset(dst_reg);
4848 /* Intersecting with the old var_off might have improved our bounds
4849 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4850 * then new var_off is (0; 0x7f...fc) which improves our umax.
4851 */
4852 __update_reg_bounds(src_reg);
4853 __update_reg_bounds(dst_reg);
f1174f77
EC
4854}
4855
4856static void reg_combine_min_max(struct bpf_reg_state *true_src,
4857 struct bpf_reg_state *true_dst,
4858 struct bpf_reg_state *false_src,
4859 struct bpf_reg_state *false_dst,
4860 u8 opcode)
4861{
4862 switch (opcode) {
4863 case BPF_JEQ:
4864 __reg_combine_min_max(true_src, true_dst);
4865 break;
4866 case BPF_JNE:
4867 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 4868 break;
4cabc5b1 4869 }
48461135
JB
4870}
4871
fd978bf7
JS
4872static void mark_ptr_or_null_reg(struct bpf_func_state *state,
4873 struct bpf_reg_state *reg, u32 id,
840b9615 4874 bool is_null)
57a09bf0 4875{
840b9615 4876 if (reg_type_may_be_null(reg->type) && reg->id == id) {
f1174f77
EC
4877 /* Old offset (both fixed and variable parts) should
4878 * have been known-zero, because we don't allow pointer
4879 * arithmetic on pointers that might be NULL.
4880 */
b03c9f9f
EC
4881 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
4882 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 4883 reg->off)) {
b03c9f9f
EC
4884 __mark_reg_known_zero(reg);
4885 reg->off = 0;
f1174f77
EC
4886 }
4887 if (is_null) {
4888 reg->type = SCALAR_VALUE;
840b9615
JS
4889 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
4890 if (reg->map_ptr->inner_map_meta) {
4891 reg->type = CONST_PTR_TO_MAP;
4892 reg->map_ptr = reg->map_ptr->inner_map_meta;
4893 } else {
4894 reg->type = PTR_TO_MAP_VALUE;
4895 }
c64b7983
JS
4896 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
4897 reg->type = PTR_TO_SOCKET;
46f8bc92
MKL
4898 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
4899 reg->type = PTR_TO_SOCK_COMMON;
655a51e5
MKL
4900 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
4901 reg->type = PTR_TO_TCP_SOCK;
56f668df 4902 }
1b986589
MKL
4903 if (is_null) {
4904 /* We don't need id and ref_obj_id from this point
4905 * onwards anymore, thus we should better reset it,
4906 * so that state pruning has chances to take effect.
4907 */
4908 reg->id = 0;
4909 reg->ref_obj_id = 0;
4910 } else if (!reg_may_point_to_spin_lock(reg)) {
4911 /* For not-NULL ptr, reg->ref_obj_id will be reset
4912 * in release_reg_references().
4913 *
4914 * reg->id is still used by spin_lock ptr. Other
4915 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
4916 */
4917 reg->id = 0;
56f668df 4918 }
57a09bf0
TG
4919 }
4920}
4921
c6a9efa1
PC
4922static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
4923 bool is_null)
4924{
4925 struct bpf_reg_state *reg;
4926 int i;
4927
4928 for (i = 0; i < MAX_BPF_REG; i++)
4929 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
4930
4931 bpf_for_each_spilled_reg(i, state, reg) {
4932 if (!reg)
4933 continue;
4934 mark_ptr_or_null_reg(state, reg, id, is_null);
4935 }
4936}
4937
57a09bf0
TG
4938/* The logic is similar to find_good_pkt_pointers(), both could eventually
4939 * be folded together at some point.
4940 */
840b9615
JS
4941static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
4942 bool is_null)
57a09bf0 4943{
f4d7e40a 4944 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 4945 struct bpf_reg_state *regs = state->regs;
1b986589 4946 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 4947 u32 id = regs[regno].id;
c6a9efa1 4948 int i;
57a09bf0 4949
1b986589
MKL
4950 if (ref_obj_id && ref_obj_id == id && is_null)
4951 /* regs[regno] is in the " == NULL" branch.
4952 * No one could have freed the reference state before
4953 * doing the NULL check.
4954 */
4955 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 4956
c6a9efa1
PC
4957 for (i = 0; i <= vstate->curframe; i++)
4958 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
4959}
4960
5beca081
DB
4961static bool try_match_pkt_pointers(const struct bpf_insn *insn,
4962 struct bpf_reg_state *dst_reg,
4963 struct bpf_reg_state *src_reg,
4964 struct bpf_verifier_state *this_branch,
4965 struct bpf_verifier_state *other_branch)
4966{
4967 if (BPF_SRC(insn->code) != BPF_X)
4968 return false;
4969
092ed096
JW
4970 /* Pointers are always 64-bit. */
4971 if (BPF_CLASS(insn->code) == BPF_JMP32)
4972 return false;
4973
5beca081
DB
4974 switch (BPF_OP(insn->code)) {
4975 case BPF_JGT:
4976 if ((dst_reg->type == PTR_TO_PACKET &&
4977 src_reg->type == PTR_TO_PACKET_END) ||
4978 (dst_reg->type == PTR_TO_PACKET_META &&
4979 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4980 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
4981 find_good_pkt_pointers(this_branch, dst_reg,
4982 dst_reg->type, false);
4983 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4984 src_reg->type == PTR_TO_PACKET) ||
4985 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4986 src_reg->type == PTR_TO_PACKET_META)) {
4987 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
4988 find_good_pkt_pointers(other_branch, src_reg,
4989 src_reg->type, true);
4990 } else {
4991 return false;
4992 }
4993 break;
4994 case BPF_JLT:
4995 if ((dst_reg->type == PTR_TO_PACKET &&
4996 src_reg->type == PTR_TO_PACKET_END) ||
4997 (dst_reg->type == PTR_TO_PACKET_META &&
4998 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4999 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
5000 find_good_pkt_pointers(other_branch, dst_reg,
5001 dst_reg->type, true);
5002 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5003 src_reg->type == PTR_TO_PACKET) ||
5004 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5005 src_reg->type == PTR_TO_PACKET_META)) {
5006 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
5007 find_good_pkt_pointers(this_branch, src_reg,
5008 src_reg->type, false);
5009 } else {
5010 return false;
5011 }
5012 break;
5013 case BPF_JGE:
5014 if ((dst_reg->type == PTR_TO_PACKET &&
5015 src_reg->type == PTR_TO_PACKET_END) ||
5016 (dst_reg->type == PTR_TO_PACKET_META &&
5017 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5018 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
5019 find_good_pkt_pointers(this_branch, dst_reg,
5020 dst_reg->type, true);
5021 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5022 src_reg->type == PTR_TO_PACKET) ||
5023 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5024 src_reg->type == PTR_TO_PACKET_META)) {
5025 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
5026 find_good_pkt_pointers(other_branch, src_reg,
5027 src_reg->type, false);
5028 } else {
5029 return false;
5030 }
5031 break;
5032 case BPF_JLE:
5033 if ((dst_reg->type == PTR_TO_PACKET &&
5034 src_reg->type == PTR_TO_PACKET_END) ||
5035 (dst_reg->type == PTR_TO_PACKET_META &&
5036 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5037 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
5038 find_good_pkt_pointers(other_branch, dst_reg,
5039 dst_reg->type, false);
5040 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5041 src_reg->type == PTR_TO_PACKET) ||
5042 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5043 src_reg->type == PTR_TO_PACKET_META)) {
5044 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
5045 find_good_pkt_pointers(this_branch, src_reg,
5046 src_reg->type, true);
5047 } else {
5048 return false;
5049 }
5050 break;
5051 default:
5052 return false;
5053 }
5054
5055 return true;
5056}
5057
58e2af8b 5058static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
5059 struct bpf_insn *insn, int *insn_idx)
5060{
f4d7e40a
AS
5061 struct bpf_verifier_state *this_branch = env->cur_state;
5062 struct bpf_verifier_state *other_branch;
5063 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
5064 struct bpf_reg_state *dst_reg, *other_branch_regs;
17a52670 5065 u8 opcode = BPF_OP(insn->code);
092ed096 5066 bool is_jmp32;
17a52670
AS
5067 int err;
5068
092ed096
JW
5069 /* Only conditional jumps are expected to reach here. */
5070 if (opcode == BPF_JA || opcode > BPF_JSLE) {
5071 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
5072 return -EINVAL;
5073 }
5074
5075 if (BPF_SRC(insn->code) == BPF_X) {
5076 if (insn->imm != 0) {
092ed096 5077 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
5078 return -EINVAL;
5079 }
5080
5081 /* check src1 operand */
dc503a8a 5082 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
5083 if (err)
5084 return err;
1be7f75d
AS
5085
5086 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 5087 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
5088 insn->src_reg);
5089 return -EACCES;
5090 }
17a52670
AS
5091 } else {
5092 if (insn->src_reg != BPF_REG_0) {
092ed096 5093 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
5094 return -EINVAL;
5095 }
5096 }
5097
5098 /* check src2 operand */
dc503a8a 5099 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
5100 if (err)
5101 return err;
5102
1a0dc1ac 5103 dst_reg = &regs[insn->dst_reg];
092ed096 5104 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 5105
4f7b3e82 5106 if (BPF_SRC(insn->code) == BPF_K) {
092ed096
JW
5107 int pred = is_branch_taken(dst_reg, insn->imm, opcode,
5108 is_jmp32);
4f7b3e82
AS
5109
5110 if (pred == 1) {
5111 /* only follow the goto, ignore fall-through */
17a52670
AS
5112 *insn_idx += insn->off;
5113 return 0;
4f7b3e82
AS
5114 } else if (pred == 0) {
5115 /* only follow fall-through branch, since
17a52670
AS
5116 * that's where the program will go
5117 */
5118 return 0;
5119 }
5120 }
5121
979d63d5
DB
5122 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
5123 false);
17a52670
AS
5124 if (!other_branch)
5125 return -EFAULT;
f4d7e40a 5126 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 5127
48461135
JB
5128 /* detect if we are comparing against a constant value so we can adjust
5129 * our min/max values for our dst register.
f1174f77
EC
5130 * this is only legit if both are scalars (or pointers to the same
5131 * object, I suppose, but we don't support that right now), because
5132 * otherwise the different base pointers mean the offsets aren't
5133 * comparable.
48461135
JB
5134 */
5135 if (BPF_SRC(insn->code) == BPF_X) {
092ed096
JW
5136 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
5137 struct bpf_reg_state lo_reg0 = *dst_reg;
5138 struct bpf_reg_state lo_reg1 = *src_reg;
5139 struct bpf_reg_state *src_lo, *dst_lo;
5140
5141 dst_lo = &lo_reg0;
5142 src_lo = &lo_reg1;
5143 coerce_reg_to_size(dst_lo, 4);
5144 coerce_reg_to_size(src_lo, 4);
5145
f1174f77 5146 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
5147 src_reg->type == SCALAR_VALUE) {
5148 if (tnum_is_const(src_reg->var_off) ||
5149 (is_jmp32 && tnum_is_const(src_lo->var_off)))
f4d7e40a 5150 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096
JW
5151 dst_reg,
5152 is_jmp32
5153 ? src_lo->var_off.value
5154 : src_reg->var_off.value,
5155 opcode, is_jmp32);
5156 else if (tnum_is_const(dst_reg->var_off) ||
5157 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
f4d7e40a 5158 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096
JW
5159 src_reg,
5160 is_jmp32
5161 ? dst_lo->var_off.value
5162 : dst_reg->var_off.value,
5163 opcode, is_jmp32);
5164 else if (!is_jmp32 &&
5165 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 5166 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
5167 reg_combine_min_max(&other_branch_regs[insn->src_reg],
5168 &other_branch_regs[insn->dst_reg],
092ed096 5169 src_reg, dst_reg, opcode);
f1174f77
EC
5170 }
5171 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 5172 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 5173 dst_reg, insn->imm, opcode, is_jmp32);
48461135
JB
5174 }
5175
092ed096
JW
5176 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
5177 * NOTE: these optimizations below are related with pointer comparison
5178 * which will never be JMP32.
5179 */
5180 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 5181 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
5182 reg_type_may_be_null(dst_reg->type)) {
5183 /* Mark all identical registers in each branch as either
57a09bf0
TG
5184 * safe or unknown depending R == 0 or R != 0 conditional.
5185 */
840b9615
JS
5186 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
5187 opcode == BPF_JNE);
5188 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
5189 opcode == BPF_JEQ);
5beca081
DB
5190 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
5191 this_branch, other_branch) &&
5192 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
5193 verbose(env, "R%d pointer comparison prohibited\n",
5194 insn->dst_reg);
1be7f75d 5195 return -EACCES;
17a52670 5196 }
06ee7115 5197 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 5198 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
5199 return 0;
5200}
5201
17a52670 5202/* verify BPF_LD_IMM64 instruction */
58e2af8b 5203static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 5204{
d8eca5bb 5205 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 5206 struct bpf_reg_state *regs = cur_regs(env);
d8eca5bb 5207 struct bpf_map *map;
17a52670
AS
5208 int err;
5209
5210 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 5211 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
5212 return -EINVAL;
5213 }
5214 if (insn->off != 0) {
61bd5218 5215 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
5216 return -EINVAL;
5217 }
5218
dc503a8a 5219 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
5220 if (err)
5221 return err;
5222
6b173873 5223 if (insn->src_reg == 0) {
6b173873
JK
5224 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
5225
f1174f77 5226 regs[insn->dst_reg].type = SCALAR_VALUE;
b03c9f9f 5227 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 5228 return 0;
6b173873 5229 }
17a52670 5230
d8eca5bb
DB
5231 map = env->used_maps[aux->map_index];
5232 mark_reg_known_zero(env, regs, insn->dst_reg);
5233 regs[insn->dst_reg].map_ptr = map;
5234
5235 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
5236 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
5237 regs[insn->dst_reg].off = aux->map_off;
5238 if (map_value_has_spin_lock(map))
5239 regs[insn->dst_reg].id = ++env->id_gen;
5240 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
5241 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
5242 } else {
5243 verbose(env, "bpf verifier is misconfigured\n");
5244 return -EINVAL;
5245 }
17a52670 5246
17a52670
AS
5247 return 0;
5248}
5249
96be4325
DB
5250static bool may_access_skb(enum bpf_prog_type type)
5251{
5252 switch (type) {
5253 case BPF_PROG_TYPE_SOCKET_FILTER:
5254 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 5255 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
5256 return true;
5257 default:
5258 return false;
5259 }
5260}
5261
ddd872bc
AS
5262/* verify safety of LD_ABS|LD_IND instructions:
5263 * - they can only appear in the programs where ctx == skb
5264 * - since they are wrappers of function calls, they scratch R1-R5 registers,
5265 * preserve R6-R9, and store return value into R0
5266 *
5267 * Implicit input:
5268 * ctx == skb == R6 == CTX
5269 *
5270 * Explicit input:
5271 * SRC == any register
5272 * IMM == 32-bit immediate
5273 *
5274 * Output:
5275 * R0 - 8/16/32-bit skb data converted to cpu endianness
5276 */
58e2af8b 5277static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 5278{
638f5b90 5279 struct bpf_reg_state *regs = cur_regs(env);
ddd872bc 5280 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
5281 int i, err;
5282
24701ece 5283 if (!may_access_skb(env->prog->type)) {
61bd5218 5284 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
5285 return -EINVAL;
5286 }
5287
e0cea7ce
DB
5288 if (!env->ops->gen_ld_abs) {
5289 verbose(env, "bpf verifier is misconfigured\n");
5290 return -EINVAL;
5291 }
5292
f910cefa 5293 if (env->subprog_cnt > 1) {
f4d7e40a
AS
5294 /* when program has LD_ABS insn JITs and interpreter assume
5295 * that r1 == ctx == skb which is not the case for callees
5296 * that can have arbitrary arguments. It's problematic
5297 * for main prog as well since JITs would need to analyze
5298 * all functions in order to make proper register save/restore
5299 * decisions in the main prog. Hence disallow LD_ABS with calls
5300 */
5301 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
5302 return -EINVAL;
5303 }
5304
ddd872bc 5305 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 5306 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 5307 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 5308 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
5309 return -EINVAL;
5310 }
5311
5312 /* check whether implicit source operand (register R6) is readable */
dc503a8a 5313 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
ddd872bc
AS
5314 if (err)
5315 return err;
5316
fd978bf7
JS
5317 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
5318 * gen_ld_abs() may terminate the program at runtime, leading to
5319 * reference leak.
5320 */
5321 err = check_reference_leak(env);
5322 if (err) {
5323 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
5324 return err;
5325 }
5326
d83525ca
AS
5327 if (env->cur_state->active_spin_lock) {
5328 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
5329 return -EINVAL;
5330 }
5331
ddd872bc 5332 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
61bd5218
JK
5333 verbose(env,
5334 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
5335 return -EINVAL;
5336 }
5337
5338 if (mode == BPF_IND) {
5339 /* check explicit source operand */
dc503a8a 5340 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
5341 if (err)
5342 return err;
5343 }
5344
5345 /* reset caller saved regs to unreadable */
dc503a8a 5346 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 5347 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
5348 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5349 }
ddd872bc
AS
5350
5351 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
5352 * the value fetched from the packet.
5353 * Already marked as written above.
ddd872bc 5354 */
61bd5218 5355 mark_reg_unknown(env, regs, BPF_REG_0);
ddd872bc
AS
5356 return 0;
5357}
5358
390ee7e2
AS
5359static int check_return_code(struct bpf_verifier_env *env)
5360{
5361 struct bpf_reg_state *reg;
5362 struct tnum range = tnum_range(0, 1);
5363
5364 switch (env->prog->type) {
5365 case BPF_PROG_TYPE_CGROUP_SKB:
5366 case BPF_PROG_TYPE_CGROUP_SOCK:
4fbac77d 5367 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
390ee7e2 5368 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 5369 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 5370 case BPF_PROG_TYPE_CGROUP_SYSCTL:
390ee7e2
AS
5371 break;
5372 default:
5373 return 0;
5374 }
5375
638f5b90 5376 reg = cur_regs(env) + BPF_REG_0;
390ee7e2 5377 if (reg->type != SCALAR_VALUE) {
61bd5218 5378 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
5379 reg_type_str[reg->type]);
5380 return -EINVAL;
5381 }
5382
5383 if (!tnum_in(range, reg->var_off)) {
61bd5218 5384 verbose(env, "At program exit the register R0 ");
390ee7e2
AS
5385 if (!tnum_is_unknown(reg->var_off)) {
5386 char tn_buf[48];
5387
5388 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 5389 verbose(env, "has value %s", tn_buf);
390ee7e2 5390 } else {
61bd5218 5391 verbose(env, "has unknown scalar value");
390ee7e2 5392 }
61bd5218 5393 verbose(env, " should have been 0 or 1\n");
390ee7e2
AS
5394 return -EINVAL;
5395 }
5396 return 0;
5397}
5398
475fb78f
AS
5399/* non-recursive DFS pseudo code
5400 * 1 procedure DFS-iterative(G,v):
5401 * 2 label v as discovered
5402 * 3 let S be a stack
5403 * 4 S.push(v)
5404 * 5 while S is not empty
5405 * 6 t <- S.pop()
5406 * 7 if t is what we're looking for:
5407 * 8 return t
5408 * 9 for all edges e in G.adjacentEdges(t) do
5409 * 10 if edge e is already labelled
5410 * 11 continue with the next edge
5411 * 12 w <- G.adjacentVertex(t,e)
5412 * 13 if vertex w is not discovered and not explored
5413 * 14 label e as tree-edge
5414 * 15 label w as discovered
5415 * 16 S.push(w)
5416 * 17 continue at 5
5417 * 18 else if vertex w is discovered
5418 * 19 label e as back-edge
5419 * 20 else
5420 * 21 // vertex w is explored
5421 * 22 label e as forward- or cross-edge
5422 * 23 label t as explored
5423 * 24 S.pop()
5424 *
5425 * convention:
5426 * 0x10 - discovered
5427 * 0x11 - discovered and fall-through edge labelled
5428 * 0x12 - discovered and fall-through and branch edges labelled
5429 * 0x20 - explored
5430 */
5431
5432enum {
5433 DISCOVERED = 0x10,
5434 EXPLORED = 0x20,
5435 FALLTHROUGH = 1,
5436 BRANCH = 2,
5437};
5438
58e2af8b 5439#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
f1bca824 5440
475fb78f
AS
5441/* t, w, e - match pseudo-code above:
5442 * t - index of current instruction
5443 * w - next instruction
5444 * e - edge
5445 */
58e2af8b 5446static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
475fb78f 5447{
7df737e9
AS
5448 int *insn_stack = env->cfg.insn_stack;
5449 int *insn_state = env->cfg.insn_state;
5450
475fb78f
AS
5451 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
5452 return 0;
5453
5454 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
5455 return 0;
5456
5457 if (w < 0 || w >= env->prog->len) {
d9762e84 5458 verbose_linfo(env, t, "%d: ", t);
61bd5218 5459 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
5460 return -EINVAL;
5461 }
5462
f1bca824
AS
5463 if (e == BRANCH)
5464 /* mark branch target for state pruning */
5465 env->explored_states[w] = STATE_LIST_MARK;
5466
475fb78f
AS
5467 if (insn_state[w] == 0) {
5468 /* tree-edge */
5469 insn_state[t] = DISCOVERED | e;
5470 insn_state[w] = DISCOVERED;
7df737e9 5471 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 5472 return -E2BIG;
7df737e9 5473 insn_stack[env->cfg.cur_stack++] = w;
475fb78f
AS
5474 return 1;
5475 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
d9762e84
MKL
5476 verbose_linfo(env, t, "%d: ", t);
5477 verbose_linfo(env, w, "%d: ", w);
61bd5218 5478 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
5479 return -EINVAL;
5480 } else if (insn_state[w] == EXPLORED) {
5481 /* forward- or cross-edge */
5482 insn_state[t] = DISCOVERED | e;
5483 } else {
61bd5218 5484 verbose(env, "insn state internal bug\n");
475fb78f
AS
5485 return -EFAULT;
5486 }
5487 return 0;
5488}
5489
5490/* non-recursive depth-first-search to detect loops in BPF program
5491 * loop == back-edge in directed graph
5492 */
58e2af8b 5493static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
5494{
5495 struct bpf_insn *insns = env->prog->insnsi;
5496 int insn_cnt = env->prog->len;
7df737e9 5497 int *insn_stack, *insn_state;
475fb78f
AS
5498 int ret = 0;
5499 int i, t;
5500
7df737e9 5501 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
5502 if (!insn_state)
5503 return -ENOMEM;
5504
7df737e9 5505 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 5506 if (!insn_stack) {
71dde681 5507 kvfree(insn_state);
475fb78f
AS
5508 return -ENOMEM;
5509 }
5510
5511 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
5512 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 5513 env->cfg.cur_stack = 1;
475fb78f
AS
5514
5515peek_stack:
7df737e9 5516 if (env->cfg.cur_stack == 0)
475fb78f 5517 goto check_state;
7df737e9 5518 t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 5519
092ed096
JW
5520 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
5521 BPF_CLASS(insns[t].code) == BPF_JMP32) {
475fb78f
AS
5522 u8 opcode = BPF_OP(insns[t].code);
5523
5524 if (opcode == BPF_EXIT) {
5525 goto mark_explored;
5526 } else if (opcode == BPF_CALL) {
5527 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5528 if (ret == 1)
5529 goto peek_stack;
5530 else if (ret < 0)
5531 goto err_free;
07016151
DB
5532 if (t + 1 < insn_cnt)
5533 env->explored_states[t + 1] = STATE_LIST_MARK;
cc8b0b92
AS
5534 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5535 env->explored_states[t] = STATE_LIST_MARK;
5536 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
5537 if (ret == 1)
5538 goto peek_stack;
5539 else if (ret < 0)
5540 goto err_free;
5541 }
475fb78f
AS
5542 } else if (opcode == BPF_JA) {
5543 if (BPF_SRC(insns[t].code) != BPF_K) {
5544 ret = -EINVAL;
5545 goto err_free;
5546 }
5547 /* unconditional jump with single edge */
5548 ret = push_insn(t, t + insns[t].off + 1,
5549 FALLTHROUGH, env);
5550 if (ret == 1)
5551 goto peek_stack;
5552 else if (ret < 0)
5553 goto err_free;
f1bca824
AS
5554 /* tell verifier to check for equivalent states
5555 * after every call and jump
5556 */
c3de6317
AS
5557 if (t + 1 < insn_cnt)
5558 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
5559 } else {
5560 /* conditional jump with two edges */
3c2ce60b 5561 env->explored_states[t] = STATE_LIST_MARK;
475fb78f
AS
5562 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5563 if (ret == 1)
5564 goto peek_stack;
5565 else if (ret < 0)
5566 goto err_free;
5567
5568 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
5569 if (ret == 1)
5570 goto peek_stack;
5571 else if (ret < 0)
5572 goto err_free;
5573 }
5574 } else {
5575 /* all other non-branch instructions with single
5576 * fall-through edge
5577 */
5578 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5579 if (ret == 1)
5580 goto peek_stack;
5581 else if (ret < 0)
5582 goto err_free;
5583 }
5584
5585mark_explored:
5586 insn_state[t] = EXPLORED;
7df737e9 5587 if (env->cfg.cur_stack-- <= 0) {
61bd5218 5588 verbose(env, "pop stack internal bug\n");
475fb78f
AS
5589 ret = -EFAULT;
5590 goto err_free;
5591 }
5592 goto peek_stack;
5593
5594check_state:
5595 for (i = 0; i < insn_cnt; i++) {
5596 if (insn_state[i] != EXPLORED) {
61bd5218 5597 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
5598 ret = -EINVAL;
5599 goto err_free;
5600 }
5601 }
5602 ret = 0; /* cfg looks good */
5603
5604err_free:
71dde681
AS
5605 kvfree(insn_state);
5606 kvfree(insn_stack);
7df737e9 5607 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
5608 return ret;
5609}
5610
838e9690
YS
5611/* The minimum supported BTF func info size */
5612#define MIN_BPF_FUNCINFO_SIZE 8
5613#define MAX_FUNCINFO_REC_SIZE 252
5614
c454a46b
MKL
5615static int check_btf_func(struct bpf_verifier_env *env,
5616 const union bpf_attr *attr,
5617 union bpf_attr __user *uattr)
838e9690 5618{
d0b2818e 5619 u32 i, nfuncs, urec_size, min_size;
838e9690 5620 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 5621 struct bpf_func_info *krecord;
838e9690 5622 const struct btf_type *type;
c454a46b
MKL
5623 struct bpf_prog *prog;
5624 const struct btf *btf;
838e9690 5625 void __user *urecord;
d0b2818e 5626 u32 prev_offset = 0;
838e9690
YS
5627 int ret = 0;
5628
5629 nfuncs = attr->func_info_cnt;
5630 if (!nfuncs)
5631 return 0;
5632
5633 if (nfuncs != env->subprog_cnt) {
5634 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
5635 return -EINVAL;
5636 }
5637
5638 urec_size = attr->func_info_rec_size;
5639 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
5640 urec_size > MAX_FUNCINFO_REC_SIZE ||
5641 urec_size % sizeof(u32)) {
5642 verbose(env, "invalid func info rec size %u\n", urec_size);
5643 return -EINVAL;
5644 }
5645
c454a46b
MKL
5646 prog = env->prog;
5647 btf = prog->aux->btf;
838e9690
YS
5648
5649 urecord = u64_to_user_ptr(attr->func_info);
5650 min_size = min_t(u32, krec_size, urec_size);
5651
ba64e7d8 5652 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
5653 if (!krecord)
5654 return -ENOMEM;
ba64e7d8 5655
838e9690
YS
5656 for (i = 0; i < nfuncs; i++) {
5657 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
5658 if (ret) {
5659 if (ret == -E2BIG) {
5660 verbose(env, "nonzero tailing record in func info");
5661 /* set the size kernel expects so loader can zero
5662 * out the rest of the record.
5663 */
5664 if (put_user(min_size, &uattr->func_info_rec_size))
5665 ret = -EFAULT;
5666 }
c454a46b 5667 goto err_free;
838e9690
YS
5668 }
5669
ba64e7d8 5670 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 5671 ret = -EFAULT;
c454a46b 5672 goto err_free;
838e9690
YS
5673 }
5674
d30d42e0 5675 /* check insn_off */
838e9690 5676 if (i == 0) {
d30d42e0 5677 if (krecord[i].insn_off) {
838e9690 5678 verbose(env,
d30d42e0
MKL
5679 "nonzero insn_off %u for the first func info record",
5680 krecord[i].insn_off);
838e9690 5681 ret = -EINVAL;
c454a46b 5682 goto err_free;
838e9690 5683 }
d30d42e0 5684 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
5685 verbose(env,
5686 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 5687 krecord[i].insn_off, prev_offset);
838e9690 5688 ret = -EINVAL;
c454a46b 5689 goto err_free;
838e9690
YS
5690 }
5691
d30d42e0 5692 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690
YS
5693 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
5694 ret = -EINVAL;
c454a46b 5695 goto err_free;
838e9690
YS
5696 }
5697
5698 /* check type_id */
ba64e7d8 5699 type = btf_type_by_id(btf, krecord[i].type_id);
838e9690
YS
5700 if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) {
5701 verbose(env, "invalid type id %d in func info",
ba64e7d8 5702 krecord[i].type_id);
838e9690 5703 ret = -EINVAL;
c454a46b 5704 goto err_free;
838e9690
YS
5705 }
5706
d30d42e0 5707 prev_offset = krecord[i].insn_off;
838e9690
YS
5708 urecord += urec_size;
5709 }
5710
ba64e7d8
YS
5711 prog->aux->func_info = krecord;
5712 prog->aux->func_info_cnt = nfuncs;
838e9690
YS
5713 return 0;
5714
c454a46b 5715err_free:
ba64e7d8 5716 kvfree(krecord);
838e9690
YS
5717 return ret;
5718}
5719
ba64e7d8
YS
5720static void adjust_btf_func(struct bpf_verifier_env *env)
5721{
5722 int i;
5723
5724 if (!env->prog->aux->func_info)
5725 return;
5726
5727 for (i = 0; i < env->subprog_cnt; i++)
d30d42e0 5728 env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
5729}
5730
c454a46b
MKL
5731#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
5732 sizeof(((struct bpf_line_info *)(0))->line_col))
5733#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
5734
5735static int check_btf_line(struct bpf_verifier_env *env,
5736 const union bpf_attr *attr,
5737 union bpf_attr __user *uattr)
5738{
5739 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
5740 struct bpf_subprog_info *sub;
5741 struct bpf_line_info *linfo;
5742 struct bpf_prog *prog;
5743 const struct btf *btf;
5744 void __user *ulinfo;
5745 int err;
5746
5747 nr_linfo = attr->line_info_cnt;
5748 if (!nr_linfo)
5749 return 0;
5750
5751 rec_size = attr->line_info_rec_size;
5752 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
5753 rec_size > MAX_LINEINFO_REC_SIZE ||
5754 rec_size & (sizeof(u32) - 1))
5755 return -EINVAL;
5756
5757 /* Need to zero it in case the userspace may
5758 * pass in a smaller bpf_line_info object.
5759 */
5760 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
5761 GFP_KERNEL | __GFP_NOWARN);
5762 if (!linfo)
5763 return -ENOMEM;
5764
5765 prog = env->prog;
5766 btf = prog->aux->btf;
5767
5768 s = 0;
5769 sub = env->subprog_info;
5770 ulinfo = u64_to_user_ptr(attr->line_info);
5771 expected_size = sizeof(struct bpf_line_info);
5772 ncopy = min_t(u32, expected_size, rec_size);
5773 for (i = 0; i < nr_linfo; i++) {
5774 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
5775 if (err) {
5776 if (err == -E2BIG) {
5777 verbose(env, "nonzero tailing record in line_info");
5778 if (put_user(expected_size,
5779 &uattr->line_info_rec_size))
5780 err = -EFAULT;
5781 }
5782 goto err_free;
5783 }
5784
5785 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
5786 err = -EFAULT;
5787 goto err_free;
5788 }
5789
5790 /*
5791 * Check insn_off to ensure
5792 * 1) strictly increasing AND
5793 * 2) bounded by prog->len
5794 *
5795 * The linfo[0].insn_off == 0 check logically falls into
5796 * the later "missing bpf_line_info for func..." case
5797 * because the first linfo[0].insn_off must be the
5798 * first sub also and the first sub must have
5799 * subprog_info[0].start == 0.
5800 */
5801 if ((i && linfo[i].insn_off <= prev_offset) ||
5802 linfo[i].insn_off >= prog->len) {
5803 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
5804 i, linfo[i].insn_off, prev_offset,
5805 prog->len);
5806 err = -EINVAL;
5807 goto err_free;
5808 }
5809
fdbaa0be
MKL
5810 if (!prog->insnsi[linfo[i].insn_off].code) {
5811 verbose(env,
5812 "Invalid insn code at line_info[%u].insn_off\n",
5813 i);
5814 err = -EINVAL;
5815 goto err_free;
5816 }
5817
23127b33
MKL
5818 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
5819 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
5820 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
5821 err = -EINVAL;
5822 goto err_free;
5823 }
5824
5825 if (s != env->subprog_cnt) {
5826 if (linfo[i].insn_off == sub[s].start) {
5827 sub[s].linfo_idx = i;
5828 s++;
5829 } else if (sub[s].start < linfo[i].insn_off) {
5830 verbose(env, "missing bpf_line_info for func#%u\n", s);
5831 err = -EINVAL;
5832 goto err_free;
5833 }
5834 }
5835
5836 prev_offset = linfo[i].insn_off;
5837 ulinfo += rec_size;
5838 }
5839
5840 if (s != env->subprog_cnt) {
5841 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
5842 env->subprog_cnt - s, s);
5843 err = -EINVAL;
5844 goto err_free;
5845 }
5846
5847 prog->aux->linfo = linfo;
5848 prog->aux->nr_linfo = nr_linfo;
5849
5850 return 0;
5851
5852err_free:
5853 kvfree(linfo);
5854 return err;
5855}
5856
5857static int check_btf_info(struct bpf_verifier_env *env,
5858 const union bpf_attr *attr,
5859 union bpf_attr __user *uattr)
5860{
5861 struct btf *btf;
5862 int err;
5863
5864 if (!attr->func_info_cnt && !attr->line_info_cnt)
5865 return 0;
5866
5867 btf = btf_get_by_fd(attr->prog_btf_fd);
5868 if (IS_ERR(btf))
5869 return PTR_ERR(btf);
5870 env->prog->aux->btf = btf;
5871
5872 err = check_btf_func(env, attr, uattr);
5873 if (err)
5874 return err;
5875
5876 err = check_btf_line(env, attr, uattr);
5877 if (err)
5878 return err;
5879
5880 return 0;
ba64e7d8
YS
5881}
5882
f1174f77
EC
5883/* check %cur's range satisfies %old's */
5884static bool range_within(struct bpf_reg_state *old,
5885 struct bpf_reg_state *cur)
5886{
b03c9f9f
EC
5887 return old->umin_value <= cur->umin_value &&
5888 old->umax_value >= cur->umax_value &&
5889 old->smin_value <= cur->smin_value &&
5890 old->smax_value >= cur->smax_value;
f1174f77
EC
5891}
5892
5893/* Maximum number of register states that can exist at once */
5894#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
5895struct idpair {
5896 u32 old;
5897 u32 cur;
5898};
5899
5900/* If in the old state two registers had the same id, then they need to have
5901 * the same id in the new state as well. But that id could be different from
5902 * the old state, so we need to track the mapping from old to new ids.
5903 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
5904 * regs with old id 5 must also have new id 9 for the new state to be safe. But
5905 * regs with a different old id could still have new id 9, we don't care about
5906 * that.
5907 * So we look through our idmap to see if this old id has been seen before. If
5908 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 5909 */
f1174f77 5910static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 5911{
f1174f77 5912 unsigned int i;
969bf05e 5913
f1174f77
EC
5914 for (i = 0; i < ID_MAP_SIZE; i++) {
5915 if (!idmap[i].old) {
5916 /* Reached an empty slot; haven't seen this id before */
5917 idmap[i].old = old_id;
5918 idmap[i].cur = cur_id;
5919 return true;
5920 }
5921 if (idmap[i].old == old_id)
5922 return idmap[i].cur == cur_id;
5923 }
5924 /* We ran out of idmap slots, which should be impossible */
5925 WARN_ON_ONCE(1);
5926 return false;
5927}
5928
9242b5f5
AS
5929static void clean_func_state(struct bpf_verifier_env *env,
5930 struct bpf_func_state *st)
5931{
5932 enum bpf_reg_liveness live;
5933 int i, j;
5934
5935 for (i = 0; i < BPF_REG_FP; i++) {
5936 live = st->regs[i].live;
5937 /* liveness must not touch this register anymore */
5938 st->regs[i].live |= REG_LIVE_DONE;
5939 if (!(live & REG_LIVE_READ))
5940 /* since the register is unused, clear its state
5941 * to make further comparison simpler
5942 */
5943 __mark_reg_not_init(&st->regs[i]);
5944 }
5945
5946 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
5947 live = st->stack[i].spilled_ptr.live;
5948 /* liveness must not touch this stack slot anymore */
5949 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
5950 if (!(live & REG_LIVE_READ)) {
5951 __mark_reg_not_init(&st->stack[i].spilled_ptr);
5952 for (j = 0; j < BPF_REG_SIZE; j++)
5953 st->stack[i].slot_type[j] = STACK_INVALID;
5954 }
5955 }
5956}
5957
5958static void clean_verifier_state(struct bpf_verifier_env *env,
5959 struct bpf_verifier_state *st)
5960{
5961 int i;
5962
5963 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
5964 /* all regs in this state in all frames were already marked */
5965 return;
5966
5967 for (i = 0; i <= st->curframe; i++)
5968 clean_func_state(env, st->frame[i]);
5969}
5970
5971/* the parentage chains form a tree.
5972 * the verifier states are added to state lists at given insn and
5973 * pushed into state stack for future exploration.
5974 * when the verifier reaches bpf_exit insn some of the verifer states
5975 * stored in the state lists have their final liveness state already,
5976 * but a lot of states will get revised from liveness point of view when
5977 * the verifier explores other branches.
5978 * Example:
5979 * 1: r0 = 1
5980 * 2: if r1 == 100 goto pc+1
5981 * 3: r0 = 2
5982 * 4: exit
5983 * when the verifier reaches exit insn the register r0 in the state list of
5984 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
5985 * of insn 2 and goes exploring further. At the insn 4 it will walk the
5986 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
5987 *
5988 * Since the verifier pushes the branch states as it sees them while exploring
5989 * the program the condition of walking the branch instruction for the second
5990 * time means that all states below this branch were already explored and
5991 * their final liveness markes are already propagated.
5992 * Hence when the verifier completes the search of state list in is_state_visited()
5993 * we can call this clean_live_states() function to mark all liveness states
5994 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
5995 * will not be used.
5996 * This function also clears the registers and stack for states that !READ
5997 * to simplify state merging.
5998 *
5999 * Important note here that walking the same branch instruction in the callee
6000 * doesn't meant that the states are DONE. The verifier has to compare
6001 * the callsites
6002 */
6003static void clean_live_states(struct bpf_verifier_env *env, int insn,
6004 struct bpf_verifier_state *cur)
6005{
6006 struct bpf_verifier_state_list *sl;
6007 int i;
6008
6009 sl = env->explored_states[insn];
6010 if (!sl)
6011 return;
6012
6013 while (sl != STATE_LIST_MARK) {
6014 if (sl->state.curframe != cur->curframe)
6015 goto next;
6016 for (i = 0; i <= cur->curframe; i++)
6017 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
6018 goto next;
6019 clean_verifier_state(env, &sl->state);
6020next:
6021 sl = sl->next;
6022 }
6023}
6024
f1174f77 6025/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
6026static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
6027 struct idpair *idmap)
f1174f77 6028{
f4d7e40a
AS
6029 bool equal;
6030
dc503a8a
EC
6031 if (!(rold->live & REG_LIVE_READ))
6032 /* explored state didn't use this */
6033 return true;
6034
679c782d 6035 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
6036
6037 if (rold->type == PTR_TO_STACK)
6038 /* two stack pointers are equal only if they're pointing to
6039 * the same stack frame, since fp-8 in foo != fp-8 in bar
6040 */
6041 return equal && rold->frameno == rcur->frameno;
6042
6043 if (equal)
969bf05e
AS
6044 return true;
6045
f1174f77
EC
6046 if (rold->type == NOT_INIT)
6047 /* explored state can't have used this */
969bf05e 6048 return true;
f1174f77
EC
6049 if (rcur->type == NOT_INIT)
6050 return false;
6051 switch (rold->type) {
6052 case SCALAR_VALUE:
6053 if (rcur->type == SCALAR_VALUE) {
6054 /* new val must satisfy old val knowledge */
6055 return range_within(rold, rcur) &&
6056 tnum_in(rold->var_off, rcur->var_off);
6057 } else {
179d1c56
JH
6058 /* We're trying to use a pointer in place of a scalar.
6059 * Even if the scalar was unbounded, this could lead to
6060 * pointer leaks because scalars are allowed to leak
6061 * while pointers are not. We could make this safe in
6062 * special cases if root is calling us, but it's
6063 * probably not worth the hassle.
f1174f77 6064 */
179d1c56 6065 return false;
f1174f77
EC
6066 }
6067 case PTR_TO_MAP_VALUE:
1b688a19
EC
6068 /* If the new min/max/var_off satisfy the old ones and
6069 * everything else matches, we are OK.
d83525ca
AS
6070 * 'id' is not compared, since it's only used for maps with
6071 * bpf_spin_lock inside map element and in such cases if
6072 * the rest of the prog is valid for one map element then
6073 * it's valid for all map elements regardless of the key
6074 * used in bpf_map_lookup()
1b688a19
EC
6075 */
6076 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
6077 range_within(rold, rcur) &&
6078 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
6079 case PTR_TO_MAP_VALUE_OR_NULL:
6080 /* a PTR_TO_MAP_VALUE could be safe to use as a
6081 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
6082 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
6083 * checked, doing so could have affected others with the same
6084 * id, and we can't check for that because we lost the id when
6085 * we converted to a PTR_TO_MAP_VALUE.
6086 */
6087 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
6088 return false;
6089 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
6090 return false;
6091 /* Check our ids match any regs they're supposed to */
6092 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 6093 case PTR_TO_PACKET_META:
f1174f77 6094 case PTR_TO_PACKET:
de8f3a83 6095 if (rcur->type != rold->type)
f1174f77
EC
6096 return false;
6097 /* We must have at least as much range as the old ptr
6098 * did, so that any accesses which were safe before are
6099 * still safe. This is true even if old range < old off,
6100 * since someone could have accessed through (ptr - k), or
6101 * even done ptr -= k in a register, to get a safe access.
6102 */
6103 if (rold->range > rcur->range)
6104 return false;
6105 /* If the offsets don't match, we can't trust our alignment;
6106 * nor can we be sure that we won't fall out of range.
6107 */
6108 if (rold->off != rcur->off)
6109 return false;
6110 /* id relations must be preserved */
6111 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
6112 return false;
6113 /* new val must satisfy old val knowledge */
6114 return range_within(rold, rcur) &&
6115 tnum_in(rold->var_off, rcur->var_off);
6116 case PTR_TO_CTX:
6117 case CONST_PTR_TO_MAP:
f1174f77 6118 case PTR_TO_PACKET_END:
d58e468b 6119 case PTR_TO_FLOW_KEYS:
c64b7983
JS
6120 case PTR_TO_SOCKET:
6121 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6122 case PTR_TO_SOCK_COMMON:
6123 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6124 case PTR_TO_TCP_SOCK:
6125 case PTR_TO_TCP_SOCK_OR_NULL:
f1174f77
EC
6126 /* Only valid matches are exact, which memcmp() above
6127 * would have accepted
6128 */
6129 default:
6130 /* Don't know what's going on, just say it's not safe */
6131 return false;
6132 }
969bf05e 6133
f1174f77
EC
6134 /* Shouldn't get here; if we do, say it's not safe */
6135 WARN_ON_ONCE(1);
969bf05e
AS
6136 return false;
6137}
6138
f4d7e40a
AS
6139static bool stacksafe(struct bpf_func_state *old,
6140 struct bpf_func_state *cur,
638f5b90
AS
6141 struct idpair *idmap)
6142{
6143 int i, spi;
6144
638f5b90
AS
6145 /* walk slots of the explored stack and ignore any additional
6146 * slots in the current stack, since explored(safe) state
6147 * didn't use them
6148 */
6149 for (i = 0; i < old->allocated_stack; i++) {
6150 spi = i / BPF_REG_SIZE;
6151
b233920c
AS
6152 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
6153 i += BPF_REG_SIZE - 1;
cc2b14d5 6154 /* explored state didn't use this */
fd05e57b 6155 continue;
b233920c 6156 }
cc2b14d5 6157
638f5b90
AS
6158 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
6159 continue;
19e2dbb7
AS
6160
6161 /* explored stack has more populated slots than current stack
6162 * and these slots were used
6163 */
6164 if (i >= cur->allocated_stack)
6165 return false;
6166
cc2b14d5
AS
6167 /* if old state was safe with misc data in the stack
6168 * it will be safe with zero-initialized stack.
6169 * The opposite is not true
6170 */
6171 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
6172 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
6173 continue;
638f5b90
AS
6174 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
6175 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
6176 /* Ex: old explored (safe) state has STACK_SPILL in
6177 * this stack slot, but current has has STACK_MISC ->
6178 * this verifier states are not equivalent,
6179 * return false to continue verification of this path
6180 */
6181 return false;
6182 if (i % BPF_REG_SIZE)
6183 continue;
6184 if (old->stack[spi].slot_type[0] != STACK_SPILL)
6185 continue;
6186 if (!regsafe(&old->stack[spi].spilled_ptr,
6187 &cur->stack[spi].spilled_ptr,
6188 idmap))
6189 /* when explored and current stack slot are both storing
6190 * spilled registers, check that stored pointers types
6191 * are the same as well.
6192 * Ex: explored safe path could have stored
6193 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
6194 * but current path has stored:
6195 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
6196 * such verifier states are not equivalent.
6197 * return false to continue verification of this path
6198 */
6199 return false;
6200 }
6201 return true;
6202}
6203
fd978bf7
JS
6204static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
6205{
6206 if (old->acquired_refs != cur->acquired_refs)
6207 return false;
6208 return !memcmp(old->refs, cur->refs,
6209 sizeof(*old->refs) * old->acquired_refs);
6210}
6211
f1bca824
AS
6212/* compare two verifier states
6213 *
6214 * all states stored in state_list are known to be valid, since
6215 * verifier reached 'bpf_exit' instruction through them
6216 *
6217 * this function is called when verifier exploring different branches of
6218 * execution popped from the state stack. If it sees an old state that has
6219 * more strict register state and more strict stack state then this execution
6220 * branch doesn't need to be explored further, since verifier already
6221 * concluded that more strict state leads to valid finish.
6222 *
6223 * Therefore two states are equivalent if register state is more conservative
6224 * and explored stack state is more conservative than the current one.
6225 * Example:
6226 * explored current
6227 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
6228 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
6229 *
6230 * In other words if current stack state (one being explored) has more
6231 * valid slots than old one that already passed validation, it means
6232 * the verifier can stop exploring and conclude that current state is valid too
6233 *
6234 * Similarly with registers. If explored state has register type as invalid
6235 * whereas register type in current state is meaningful, it means that
6236 * the current state will reach 'bpf_exit' instruction safely
6237 */
f4d7e40a
AS
6238static bool func_states_equal(struct bpf_func_state *old,
6239 struct bpf_func_state *cur)
f1bca824 6240{
f1174f77
EC
6241 struct idpair *idmap;
6242 bool ret = false;
f1bca824
AS
6243 int i;
6244
f1174f77
EC
6245 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
6246 /* If we failed to allocate the idmap, just say it's not safe */
6247 if (!idmap)
1a0dc1ac 6248 return false;
f1174f77
EC
6249
6250 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 6251 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 6252 goto out_free;
f1bca824
AS
6253 }
6254
638f5b90
AS
6255 if (!stacksafe(old, cur, idmap))
6256 goto out_free;
fd978bf7
JS
6257
6258 if (!refsafe(old, cur))
6259 goto out_free;
f1174f77
EC
6260 ret = true;
6261out_free:
6262 kfree(idmap);
6263 return ret;
f1bca824
AS
6264}
6265
f4d7e40a
AS
6266static bool states_equal(struct bpf_verifier_env *env,
6267 struct bpf_verifier_state *old,
6268 struct bpf_verifier_state *cur)
6269{
6270 int i;
6271
6272 if (old->curframe != cur->curframe)
6273 return false;
6274
979d63d5
DB
6275 /* Verification state from speculative execution simulation
6276 * must never prune a non-speculative execution one.
6277 */
6278 if (old->speculative && !cur->speculative)
6279 return false;
6280
d83525ca
AS
6281 if (old->active_spin_lock != cur->active_spin_lock)
6282 return false;
6283
f4d7e40a
AS
6284 /* for states to be equal callsites have to be the same
6285 * and all frame states need to be equivalent
6286 */
6287 for (i = 0; i <= old->curframe; i++) {
6288 if (old->frame[i]->callsite != cur->frame[i]->callsite)
6289 return false;
6290 if (!func_states_equal(old->frame[i], cur->frame[i]))
6291 return false;
6292 }
6293 return true;
6294}
6295
55e7f3b5
JW
6296static int propagate_liveness_reg(struct bpf_verifier_env *env,
6297 struct bpf_reg_state *reg,
6298 struct bpf_reg_state *parent_reg)
6299{
6300 int err;
6301
6302 if (parent_reg->live & REG_LIVE_READ || !(reg->live & REG_LIVE_READ))
6303 return 0;
6304
6305 err = mark_reg_read(env, reg, parent_reg);
6306 if (err)
6307 return err;
6308
6309 return 0;
6310}
6311
8e9cd9ce 6312/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
6313 * straight-line code between a state and its parent. When we arrive at an
6314 * equivalent state (jump target or such) we didn't arrive by the straight-line
6315 * code, so read marks in the state must propagate to the parent regardless
6316 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 6317 * in mark_reg_read() is for.
8e9cd9ce 6318 */
f4d7e40a
AS
6319static int propagate_liveness(struct bpf_verifier_env *env,
6320 const struct bpf_verifier_state *vstate,
6321 struct bpf_verifier_state *vparent)
dc503a8a 6322{
3f8cafa4 6323 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 6324 struct bpf_func_state *state, *parent;
3f8cafa4 6325 int i, frame, err = 0;
dc503a8a 6326
f4d7e40a
AS
6327 if (vparent->curframe != vstate->curframe) {
6328 WARN(1, "propagate_live: parent frame %d current frame %d\n",
6329 vparent->curframe, vstate->curframe);
6330 return -EFAULT;
6331 }
dc503a8a
EC
6332 /* Propagate read liveness of registers... */
6333 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 6334 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
6335 parent = vparent->frame[frame];
6336 state = vstate->frame[frame];
6337 parent_reg = parent->regs;
6338 state_reg = state->regs;
83d16312
JK
6339 /* We don't need to worry about FP liveness, it's read-only */
6340 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
6341 err = propagate_liveness_reg(env, &state_reg[i],
6342 &parent_reg[i]);
3f8cafa4
JW
6343 if (err)
6344 return err;
dc503a8a 6345 }
f4d7e40a 6346
1b04aee7 6347 /* Propagate stack slots. */
f4d7e40a
AS
6348 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
6349 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
6350 parent_reg = &parent->stack[i].spilled_ptr;
6351 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
6352 err = propagate_liveness_reg(env, state_reg,
6353 parent_reg);
3f8cafa4
JW
6354 if (err)
6355 return err;
dc503a8a
EC
6356 }
6357 }
f4d7e40a 6358 return err;
dc503a8a
EC
6359}
6360
58e2af8b 6361static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 6362{
58e2af8b 6363 struct bpf_verifier_state_list *new_sl;
9f4686c4 6364 struct bpf_verifier_state_list *sl, **pprev;
679c782d 6365 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 6366 int i, j, err, states_cnt = 0;
f1bca824 6367
9f4686c4
AS
6368 pprev = &env->explored_states[insn_idx];
6369 sl = *pprev;
6370
f1bca824
AS
6371 if (!sl)
6372 /* this 'insn_idx' instruction wasn't marked, so we will not
6373 * be doing state search here
6374 */
6375 return 0;
6376
9242b5f5
AS
6377 clean_live_states(env, insn_idx, cur);
6378
f1bca824 6379 while (sl != STATE_LIST_MARK) {
638f5b90 6380 if (states_equal(env, &sl->state, cur)) {
9f4686c4 6381 sl->hit_cnt++;
f1bca824 6382 /* reached equivalent register/stack state,
dc503a8a
EC
6383 * prune the search.
6384 * Registers read by the continuation are read by us.
8e9cd9ce
EC
6385 * If we have any write marks in env->cur_state, they
6386 * will prevent corresponding reads in the continuation
6387 * from reaching our parent (an explored_state). Our
6388 * own state will get the read marks recorded, but
6389 * they'll be immediately forgotten as we're pruning
6390 * this state and will pop a new one.
f1bca824 6391 */
f4d7e40a
AS
6392 err = propagate_liveness(env, &sl->state, cur);
6393 if (err)
6394 return err;
f1bca824 6395 return 1;
dc503a8a 6396 }
ceefbc96 6397 states_cnt++;
9f4686c4
AS
6398 sl->miss_cnt++;
6399 /* heuristic to determine whether this state is beneficial
6400 * to keep checking from state equivalence point of view.
6401 * Higher numbers increase max_states_per_insn and verification time,
6402 * but do not meaningfully decrease insn_processed.
6403 */
6404 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
6405 /* the state is unlikely to be useful. Remove it to
6406 * speed up verification
6407 */
6408 *pprev = sl->next;
6409 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
6410 free_verifier_state(&sl->state, false);
6411 kfree(sl);
6412 env->peak_states--;
6413 } else {
6414 /* cannot free this state, since parentage chain may
6415 * walk it later. Add it for free_list instead to
6416 * be freed at the end of verification
6417 */
6418 sl->next = env->free_list;
6419 env->free_list = sl;
6420 }
6421 sl = *pprev;
6422 continue;
6423 }
6424 pprev = &sl->next;
6425 sl = *pprev;
f1bca824
AS
6426 }
6427
06ee7115
AS
6428 if (env->max_states_per_insn < states_cnt)
6429 env->max_states_per_insn = states_cnt;
6430
ceefbc96
AS
6431 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
6432 return 0;
6433
f1bca824
AS
6434 /* there were no equivalent states, remember current one.
6435 * technically the current state is not proven to be safe yet,
f4d7e40a
AS
6436 * but it will either reach outer most bpf_exit (which means it's safe)
6437 * or it will be rejected. Since there are no loops, we won't be
6438 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
6439 * again on the way to bpf_exit
f1bca824 6440 */
638f5b90 6441 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
6442 if (!new_sl)
6443 return -ENOMEM;
06ee7115
AS
6444 env->total_states++;
6445 env->peak_states++;
f1bca824
AS
6446
6447 /* add new state to the head of linked list */
679c782d
EC
6448 new = &new_sl->state;
6449 err = copy_verifier_state(new, cur);
1969db47 6450 if (err) {
679c782d 6451 free_verifier_state(new, false);
1969db47
AS
6452 kfree(new_sl);
6453 return err;
6454 }
f1bca824
AS
6455 new_sl->next = env->explored_states[insn_idx];
6456 env->explored_states[insn_idx] = new_sl;
7640ead9
JK
6457 /* connect new state to parentage chain. Current frame needs all
6458 * registers connected. Only r6 - r9 of the callers are alive (pushed
6459 * to the stack implicitly by JITs) so in callers' frames connect just
6460 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
6461 * the state of the call instruction (with WRITTEN set), and r0 comes
6462 * from callee with its full parentage chain, anyway.
6463 */
6464 for (j = 0; j <= cur->curframe; j++)
6465 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
6466 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
8e9cd9ce
EC
6467 /* clear write marks in current state: the writes we did are not writes
6468 * our child did, so they don't screen off its reads from us.
6469 * (There are no read marks in current state, because reads always mark
6470 * their parent and current state never has children yet. Only
6471 * explored_states can get read marks.)
6472 */
dc503a8a 6473 for (i = 0; i < BPF_REG_FP; i++)
f4d7e40a
AS
6474 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
6475
6476 /* all stack frames are accessible from callee, clear them all */
6477 for (j = 0; j <= cur->curframe; j++) {
6478 struct bpf_func_state *frame = cur->frame[j];
679c782d 6479 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 6480
679c782d 6481 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 6482 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
6483 frame->stack[i].spilled_ptr.parent =
6484 &newframe->stack[i].spilled_ptr;
6485 }
f4d7e40a 6486 }
f1bca824
AS
6487 return 0;
6488}
6489
c64b7983
JS
6490/* Return true if it's OK to have the same insn return a different type. */
6491static bool reg_type_mismatch_ok(enum bpf_reg_type type)
6492{
6493 switch (type) {
6494 case PTR_TO_CTX:
6495 case PTR_TO_SOCKET:
6496 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6497 case PTR_TO_SOCK_COMMON:
6498 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6499 case PTR_TO_TCP_SOCK:
6500 case PTR_TO_TCP_SOCK_OR_NULL:
c64b7983
JS
6501 return false;
6502 default:
6503 return true;
6504 }
6505}
6506
6507/* If an instruction was previously used with particular pointer types, then we
6508 * need to be careful to avoid cases such as the below, where it may be ok
6509 * for one branch accessing the pointer, but not ok for the other branch:
6510 *
6511 * R1 = sock_ptr
6512 * goto X;
6513 * ...
6514 * R1 = some_other_valid_ptr;
6515 * goto X;
6516 * ...
6517 * R2 = *(u32 *)(R1 + 0);
6518 */
6519static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
6520{
6521 return src != prev && (!reg_type_mismatch_ok(src) ||
6522 !reg_type_mismatch_ok(prev));
6523}
6524
58e2af8b 6525static int do_check(struct bpf_verifier_env *env)
17a52670 6526{
638f5b90 6527 struct bpf_verifier_state *state;
17a52670 6528 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 6529 struct bpf_reg_state *regs;
06ee7115 6530 int insn_cnt = env->prog->len;
17a52670
AS
6531 bool do_print_state = false;
6532
d9762e84
MKL
6533 env->prev_linfo = NULL;
6534
638f5b90
AS
6535 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
6536 if (!state)
6537 return -ENOMEM;
f4d7e40a 6538 state->curframe = 0;
979d63d5 6539 state->speculative = false;
f4d7e40a
AS
6540 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
6541 if (!state->frame[0]) {
6542 kfree(state);
6543 return -ENOMEM;
6544 }
6545 env->cur_state = state;
6546 init_func_state(env, state->frame[0],
6547 BPF_MAIN_FUNC /* callsite */,
6548 0 /* frameno */,
6549 0 /* subprogno, zero == main subprog */);
c08435ec 6550
17a52670
AS
6551 for (;;) {
6552 struct bpf_insn *insn;
6553 u8 class;
6554 int err;
6555
c08435ec 6556 if (env->insn_idx >= insn_cnt) {
61bd5218 6557 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 6558 env->insn_idx, insn_cnt);
17a52670
AS
6559 return -EFAULT;
6560 }
6561
c08435ec 6562 insn = &insns[env->insn_idx];
17a52670
AS
6563 class = BPF_CLASS(insn->code);
6564
06ee7115 6565 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
6566 verbose(env,
6567 "BPF program is too large. Processed %d insn\n",
06ee7115 6568 env->insn_processed);
17a52670
AS
6569 return -E2BIG;
6570 }
6571
c08435ec 6572 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
6573 if (err < 0)
6574 return err;
6575 if (err == 1) {
6576 /* found equivalent state, can prune the search */
06ee7115 6577 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 6578 if (do_print_state)
979d63d5
DB
6579 verbose(env, "\nfrom %d to %d%s: safe\n",
6580 env->prev_insn_idx, env->insn_idx,
6581 env->cur_state->speculative ?
6582 " (speculative execution)" : "");
f1bca824 6583 else
c08435ec 6584 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
6585 }
6586 goto process_bpf_exit;
6587 }
6588
c3494801
AS
6589 if (signal_pending(current))
6590 return -EAGAIN;
6591
3c2ce60b
DB
6592 if (need_resched())
6593 cond_resched();
6594
06ee7115
AS
6595 if (env->log.level & BPF_LOG_LEVEL2 ||
6596 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
6597 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 6598 verbose(env, "%d:", env->insn_idx);
c5fc9692 6599 else
979d63d5
DB
6600 verbose(env, "\nfrom %d to %d%s:",
6601 env->prev_insn_idx, env->insn_idx,
6602 env->cur_state->speculative ?
6603 " (speculative execution)" : "");
f4d7e40a 6604 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
6605 do_print_state = false;
6606 }
6607
06ee7115 6608 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
6609 const struct bpf_insn_cbs cbs = {
6610 .cb_print = verbose,
abe08840 6611 .private_data = env,
7105e828
DB
6612 };
6613
c08435ec
DB
6614 verbose_linfo(env, env->insn_idx, "; ");
6615 verbose(env, "%d: ", env->insn_idx);
abe08840 6616 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
6617 }
6618
cae1927c 6619 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
6620 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
6621 env->prev_insn_idx);
cae1927c
JK
6622 if (err)
6623 return err;
6624 }
13a27dfc 6625
638f5b90 6626 regs = cur_regs(env);
c08435ec 6627 env->insn_aux_data[env->insn_idx].seen = true;
fd978bf7 6628
17a52670 6629 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 6630 err = check_alu_op(env, insn);
17a52670
AS
6631 if (err)
6632 return err;
6633
6634 } else if (class == BPF_LDX) {
3df126f3 6635 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
6636
6637 /* check for reserved fields is already done */
6638
17a52670 6639 /* check src operand */
dc503a8a 6640 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6641 if (err)
6642 return err;
6643
dc503a8a 6644 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
6645 if (err)
6646 return err;
6647
725f9dcd
AS
6648 src_reg_type = regs[insn->src_reg].type;
6649
17a52670
AS
6650 /* check that memory (src_reg + off) is readable,
6651 * the state of dst_reg will be updated by this func
6652 */
c08435ec
DB
6653 err = check_mem_access(env, env->insn_idx, insn->src_reg,
6654 insn->off, BPF_SIZE(insn->code),
6655 BPF_READ, insn->dst_reg, false);
17a52670
AS
6656 if (err)
6657 return err;
6658
c08435ec 6659 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
6660
6661 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
6662 /* saw a valid insn
6663 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 6664 * save type to validate intersecting paths
9bac3d6d 6665 */
3df126f3 6666 *prev_src_type = src_reg_type;
9bac3d6d 6667
c64b7983 6668 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
6669 /* ABuser program is trying to use the same insn
6670 * dst_reg = *(u32*) (src_reg + off)
6671 * with different pointer types:
6672 * src_reg == ctx in one branch and
6673 * src_reg == stack|map in some other branch.
6674 * Reject it.
6675 */
61bd5218 6676 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
6677 return -EINVAL;
6678 }
6679
17a52670 6680 } else if (class == BPF_STX) {
3df126f3 6681 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 6682
17a52670 6683 if (BPF_MODE(insn->code) == BPF_XADD) {
c08435ec 6684 err = check_xadd(env, env->insn_idx, insn);
17a52670
AS
6685 if (err)
6686 return err;
c08435ec 6687 env->insn_idx++;
17a52670
AS
6688 continue;
6689 }
6690
17a52670 6691 /* check src1 operand */
dc503a8a 6692 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6693 if (err)
6694 return err;
6695 /* check src2 operand */
dc503a8a 6696 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6697 if (err)
6698 return err;
6699
d691f9e8
AS
6700 dst_reg_type = regs[insn->dst_reg].type;
6701
17a52670 6702 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
6703 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
6704 insn->off, BPF_SIZE(insn->code),
6705 BPF_WRITE, insn->src_reg, false);
17a52670
AS
6706 if (err)
6707 return err;
6708
c08435ec 6709 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
6710
6711 if (*prev_dst_type == NOT_INIT) {
6712 *prev_dst_type = dst_reg_type;
c64b7983 6713 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 6714 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
6715 return -EINVAL;
6716 }
6717
17a52670
AS
6718 } else if (class == BPF_ST) {
6719 if (BPF_MODE(insn->code) != BPF_MEM ||
6720 insn->src_reg != BPF_REG_0) {
61bd5218 6721 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
6722 return -EINVAL;
6723 }
6724 /* check src operand */
dc503a8a 6725 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6726 if (err)
6727 return err;
6728
f37a8cb8 6729 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 6730 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
6731 insn->dst_reg,
6732 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
6733 return -EACCES;
6734 }
6735
17a52670 6736 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
6737 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
6738 insn->off, BPF_SIZE(insn->code),
6739 BPF_WRITE, -1, false);
17a52670
AS
6740 if (err)
6741 return err;
6742
092ed096 6743 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
6744 u8 opcode = BPF_OP(insn->code);
6745
6746 if (opcode == BPF_CALL) {
6747 if (BPF_SRC(insn->code) != BPF_K ||
6748 insn->off != 0 ||
f4d7e40a
AS
6749 (insn->src_reg != BPF_REG_0 &&
6750 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
6751 insn->dst_reg != BPF_REG_0 ||
6752 class == BPF_JMP32) {
61bd5218 6753 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
6754 return -EINVAL;
6755 }
6756
d83525ca
AS
6757 if (env->cur_state->active_spin_lock &&
6758 (insn->src_reg == BPF_PSEUDO_CALL ||
6759 insn->imm != BPF_FUNC_spin_unlock)) {
6760 verbose(env, "function calls are not allowed while holding a lock\n");
6761 return -EINVAL;
6762 }
f4d7e40a 6763 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 6764 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 6765 else
c08435ec 6766 err = check_helper_call(env, insn->imm, env->insn_idx);
17a52670
AS
6767 if (err)
6768 return err;
6769
6770 } else if (opcode == BPF_JA) {
6771 if (BPF_SRC(insn->code) != BPF_K ||
6772 insn->imm != 0 ||
6773 insn->src_reg != BPF_REG_0 ||
092ed096
JW
6774 insn->dst_reg != BPF_REG_0 ||
6775 class == BPF_JMP32) {
61bd5218 6776 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
6777 return -EINVAL;
6778 }
6779
c08435ec 6780 env->insn_idx += insn->off + 1;
17a52670
AS
6781 continue;
6782
6783 } else if (opcode == BPF_EXIT) {
6784 if (BPF_SRC(insn->code) != BPF_K ||
6785 insn->imm != 0 ||
6786 insn->src_reg != BPF_REG_0 ||
092ed096
JW
6787 insn->dst_reg != BPF_REG_0 ||
6788 class == BPF_JMP32) {
61bd5218 6789 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
6790 return -EINVAL;
6791 }
6792
d83525ca
AS
6793 if (env->cur_state->active_spin_lock) {
6794 verbose(env, "bpf_spin_unlock is missing\n");
6795 return -EINVAL;
6796 }
6797
f4d7e40a
AS
6798 if (state->curframe) {
6799 /* exit from nested function */
c08435ec
DB
6800 env->prev_insn_idx = env->insn_idx;
6801 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
6802 if (err)
6803 return err;
6804 do_print_state = true;
6805 continue;
6806 }
6807
fd978bf7
JS
6808 err = check_reference_leak(env);
6809 if (err)
6810 return err;
6811
17a52670
AS
6812 /* eBPF calling convetion is such that R0 is used
6813 * to return the value from eBPF program.
6814 * Make sure that it's readable at this time
6815 * of bpf_exit, which means that program wrote
6816 * something into it earlier
6817 */
dc503a8a 6818 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
17a52670
AS
6819 if (err)
6820 return err;
6821
1be7f75d 6822 if (is_pointer_value(env, BPF_REG_0)) {
61bd5218 6823 verbose(env, "R0 leaks addr as return value\n");
1be7f75d
AS
6824 return -EACCES;
6825 }
6826
390ee7e2
AS
6827 err = check_return_code(env);
6828 if (err)
6829 return err;
f1bca824 6830process_bpf_exit:
c08435ec
DB
6831 err = pop_stack(env, &env->prev_insn_idx,
6832 &env->insn_idx);
638f5b90
AS
6833 if (err < 0) {
6834 if (err != -ENOENT)
6835 return err;
17a52670
AS
6836 break;
6837 } else {
6838 do_print_state = true;
6839 continue;
6840 }
6841 } else {
c08435ec 6842 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
6843 if (err)
6844 return err;
6845 }
6846 } else if (class == BPF_LD) {
6847 u8 mode = BPF_MODE(insn->code);
6848
6849 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
6850 err = check_ld_abs(env, insn);
6851 if (err)
6852 return err;
6853
17a52670
AS
6854 } else if (mode == BPF_IMM) {
6855 err = check_ld_imm(env, insn);
6856 if (err)
6857 return err;
6858
c08435ec
DB
6859 env->insn_idx++;
6860 env->insn_aux_data[env->insn_idx].seen = true;
17a52670 6861 } else {
61bd5218 6862 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
6863 return -EINVAL;
6864 }
6865 } else {
61bd5218 6866 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
6867 return -EINVAL;
6868 }
6869
c08435ec 6870 env->insn_idx++;
17a52670
AS
6871 }
6872
9c8105bd 6873 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17a52670
AS
6874 return 0;
6875}
6876
56f668df
MKL
6877static int check_map_prealloc(struct bpf_map *map)
6878{
6879 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
6880 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6881 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
6882 !(map->map_flags & BPF_F_NO_PREALLOC);
6883}
6884
d83525ca
AS
6885static bool is_tracing_prog_type(enum bpf_prog_type type)
6886{
6887 switch (type) {
6888 case BPF_PROG_TYPE_KPROBE:
6889 case BPF_PROG_TYPE_TRACEPOINT:
6890 case BPF_PROG_TYPE_PERF_EVENT:
6891 case BPF_PROG_TYPE_RAW_TRACEPOINT:
6892 return true;
6893 default:
6894 return false;
6895 }
6896}
6897
61bd5218
JK
6898static int check_map_prog_compatibility(struct bpf_verifier_env *env,
6899 struct bpf_map *map,
fdc15d38
AS
6900 struct bpf_prog *prog)
6901
6902{
56f668df
MKL
6903 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
6904 * preallocated hash maps, since doing memory allocation
6905 * in overflow_handler can crash depending on where nmi got
6906 * triggered.
6907 */
6908 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
6909 if (!check_map_prealloc(map)) {
61bd5218 6910 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
6911 return -EINVAL;
6912 }
6913 if (map->inner_map_meta &&
6914 !check_map_prealloc(map->inner_map_meta)) {
61bd5218 6915 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
56f668df
MKL
6916 return -EINVAL;
6917 }
fdc15d38 6918 }
a3884572 6919
d83525ca
AS
6920 if ((is_tracing_prog_type(prog->type) ||
6921 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
6922 map_value_has_spin_lock(map)) {
6923 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
6924 return -EINVAL;
6925 }
6926
a3884572 6927 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 6928 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
6929 verbose(env, "offload device mismatch between prog and map\n");
6930 return -EINVAL;
6931 }
6932
fdc15d38
AS
6933 return 0;
6934}
6935
b741f163
RG
6936static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
6937{
6938 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
6939 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
6940}
6941
0246e64d
AS
6942/* look for pseudo eBPF instructions that access map FDs and
6943 * replace them with actual map pointers
6944 */
58e2af8b 6945static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
6946{
6947 struct bpf_insn *insn = env->prog->insnsi;
6948 int insn_cnt = env->prog->len;
fdc15d38 6949 int i, j, err;
0246e64d 6950
f1f7714e 6951 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
6952 if (err)
6953 return err;
6954
0246e64d 6955 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 6956 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 6957 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 6958 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
6959 return -EINVAL;
6960 }
6961
d691f9e8
AS
6962 if (BPF_CLASS(insn->code) == BPF_STX &&
6963 ((BPF_MODE(insn->code) != BPF_MEM &&
6964 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 6965 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
6966 return -EINVAL;
6967 }
6968
0246e64d 6969 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 6970 struct bpf_insn_aux_data *aux;
0246e64d
AS
6971 struct bpf_map *map;
6972 struct fd f;
d8eca5bb 6973 u64 addr;
0246e64d
AS
6974
6975 if (i == insn_cnt - 1 || insn[1].code != 0 ||
6976 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
6977 insn[1].off != 0) {
61bd5218 6978 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
6979 return -EINVAL;
6980 }
6981
d8eca5bb 6982 if (insn[0].src_reg == 0)
0246e64d
AS
6983 /* valid generic load 64-bit imm */
6984 goto next_insn;
6985
d8eca5bb
DB
6986 /* In final convert_pseudo_ld_imm64() step, this is
6987 * converted into regular 64-bit imm load insn.
6988 */
6989 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
6990 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
6991 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
6992 insn[1].imm != 0)) {
6993 verbose(env,
6994 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
6995 return -EINVAL;
6996 }
6997
20182390 6998 f = fdget(insn[0].imm);
c2101297 6999 map = __bpf_map_get(f);
0246e64d 7000 if (IS_ERR(map)) {
61bd5218 7001 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 7002 insn[0].imm);
0246e64d
AS
7003 return PTR_ERR(map);
7004 }
7005
61bd5218 7006 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
7007 if (err) {
7008 fdput(f);
7009 return err;
7010 }
7011
d8eca5bb
DB
7012 aux = &env->insn_aux_data[i];
7013 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7014 addr = (unsigned long)map;
7015 } else {
7016 u32 off = insn[1].imm;
7017
7018 if (off >= BPF_MAX_VAR_OFF) {
7019 verbose(env, "direct value offset of %u is not allowed\n", off);
7020 fdput(f);
7021 return -EINVAL;
7022 }
7023
7024 if (!map->ops->map_direct_value_addr) {
7025 verbose(env, "no direct value access support for this map type\n");
7026 fdput(f);
7027 return -EINVAL;
7028 }
7029
7030 err = map->ops->map_direct_value_addr(map, &addr, off);
7031 if (err) {
7032 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
7033 map->value_size, off);
7034 fdput(f);
7035 return err;
7036 }
7037
7038 aux->map_off = off;
7039 addr += off;
7040 }
7041
7042 insn[0].imm = (u32)addr;
7043 insn[1].imm = addr >> 32;
0246e64d
AS
7044
7045 /* check whether we recorded this map already */
d8eca5bb 7046 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 7047 if (env->used_maps[j] == map) {
d8eca5bb 7048 aux->map_index = j;
0246e64d
AS
7049 fdput(f);
7050 goto next_insn;
7051 }
d8eca5bb 7052 }
0246e64d
AS
7053
7054 if (env->used_map_cnt >= MAX_USED_MAPS) {
7055 fdput(f);
7056 return -E2BIG;
7057 }
7058
0246e64d
AS
7059 /* hold the map. If the program is rejected by verifier,
7060 * the map will be released by release_maps() or it
7061 * will be used by the valid program until it's unloaded
ab7f5bf0 7062 * and all maps are released in free_used_maps()
0246e64d 7063 */
92117d84
AS
7064 map = bpf_map_inc(map, false);
7065 if (IS_ERR(map)) {
7066 fdput(f);
7067 return PTR_ERR(map);
7068 }
d8eca5bb
DB
7069
7070 aux->map_index = env->used_map_cnt;
92117d84
AS
7071 env->used_maps[env->used_map_cnt++] = map;
7072
b741f163 7073 if (bpf_map_is_cgroup_storage(map) &&
de9cbbaa 7074 bpf_cgroup_storage_assign(env->prog, map)) {
b741f163 7075 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
7076 fdput(f);
7077 return -EBUSY;
7078 }
7079
0246e64d
AS
7080 fdput(f);
7081next_insn:
7082 insn++;
7083 i++;
5e581dad
DB
7084 continue;
7085 }
7086
7087 /* Basic sanity check before we invest more work here. */
7088 if (!bpf_opcode_in_insntable(insn->code)) {
7089 verbose(env, "unknown opcode %02x\n", insn->code);
7090 return -EINVAL;
0246e64d
AS
7091 }
7092 }
7093
7094 /* now all pseudo BPF_LD_IMM64 instructions load valid
7095 * 'struct bpf_map *' into a register instead of user map_fd.
7096 * These pointers will be used later by verifier to validate map access.
7097 */
7098 return 0;
7099}
7100
7101/* drop refcnt of maps used by the rejected program */
58e2af8b 7102static void release_maps(struct bpf_verifier_env *env)
0246e64d 7103{
8bad74f9 7104 enum bpf_cgroup_storage_type stype;
0246e64d
AS
7105 int i;
7106
8bad74f9
RG
7107 for_each_cgroup_storage_type(stype) {
7108 if (!env->prog->aux->cgroup_storage[stype])
7109 continue;
de9cbbaa 7110 bpf_cgroup_storage_release(env->prog,
8bad74f9
RG
7111 env->prog->aux->cgroup_storage[stype]);
7112 }
de9cbbaa 7113
0246e64d
AS
7114 for (i = 0; i < env->used_map_cnt; i++)
7115 bpf_map_put(env->used_maps[i]);
7116}
7117
7118/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 7119static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
7120{
7121 struct bpf_insn *insn = env->prog->insnsi;
7122 int insn_cnt = env->prog->len;
7123 int i;
7124
7125 for (i = 0; i < insn_cnt; i++, insn++)
7126 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
7127 insn->src_reg = 0;
7128}
7129
8041902d
AS
7130/* single env->prog->insni[off] instruction was replaced with the range
7131 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
7132 * [0, off) and [off, end) to new locations, so the patched range stays zero
7133 */
7134static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
7135 u32 off, u32 cnt)
7136{
7137 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
c131187d 7138 int i;
8041902d
AS
7139
7140 if (cnt == 1)
7141 return 0;
fad953ce
KC
7142 new_data = vzalloc(array_size(prog_len,
7143 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
7144 if (!new_data)
7145 return -ENOMEM;
7146 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
7147 memcpy(new_data + off + cnt - 1, old_data + off,
7148 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
c131187d
AS
7149 for (i = off; i < off + cnt - 1; i++)
7150 new_data[i].seen = true;
8041902d
AS
7151 env->insn_aux_data = new_data;
7152 vfree(old_data);
7153 return 0;
7154}
7155
cc8b0b92
AS
7156static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
7157{
7158 int i;
7159
7160 if (len == 1)
7161 return;
4cb3d99c
JW
7162 /* NOTE: fake 'exit' subprog should be updated as well. */
7163 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 7164 if (env->subprog_info[i].start <= off)
cc8b0b92 7165 continue;
9c8105bd 7166 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
7167 }
7168}
7169
8041902d
AS
7170static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
7171 const struct bpf_insn *patch, u32 len)
7172{
7173 struct bpf_prog *new_prog;
7174
7175 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
7176 if (IS_ERR(new_prog)) {
7177 if (PTR_ERR(new_prog) == -ERANGE)
7178 verbose(env,
7179 "insn %d cannot be patched due to 16-bit range\n",
7180 env->insn_aux_data[off].orig_idx);
8041902d 7181 return NULL;
4f73379e 7182 }
8041902d
AS
7183 if (adjust_insn_aux_data(env, new_prog->len, off, len))
7184 return NULL;
cc8b0b92 7185 adjust_subprog_starts(env, off, len);
8041902d
AS
7186 return new_prog;
7187}
7188
52875a04
JK
7189static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
7190 u32 off, u32 cnt)
7191{
7192 int i, j;
7193
7194 /* find first prog starting at or after off (first to remove) */
7195 for (i = 0; i < env->subprog_cnt; i++)
7196 if (env->subprog_info[i].start >= off)
7197 break;
7198 /* find first prog starting at or after off + cnt (first to stay) */
7199 for (j = i; j < env->subprog_cnt; j++)
7200 if (env->subprog_info[j].start >= off + cnt)
7201 break;
7202 /* if j doesn't start exactly at off + cnt, we are just removing
7203 * the front of previous prog
7204 */
7205 if (env->subprog_info[j].start != off + cnt)
7206 j--;
7207
7208 if (j > i) {
7209 struct bpf_prog_aux *aux = env->prog->aux;
7210 int move;
7211
7212 /* move fake 'exit' subprog as well */
7213 move = env->subprog_cnt + 1 - j;
7214
7215 memmove(env->subprog_info + i,
7216 env->subprog_info + j,
7217 sizeof(*env->subprog_info) * move);
7218 env->subprog_cnt -= j - i;
7219
7220 /* remove func_info */
7221 if (aux->func_info) {
7222 move = aux->func_info_cnt - j;
7223
7224 memmove(aux->func_info + i,
7225 aux->func_info + j,
7226 sizeof(*aux->func_info) * move);
7227 aux->func_info_cnt -= j - i;
7228 /* func_info->insn_off is set after all code rewrites,
7229 * in adjust_btf_func() - no need to adjust
7230 */
7231 }
7232 } else {
7233 /* convert i from "first prog to remove" to "first to adjust" */
7234 if (env->subprog_info[i].start == off)
7235 i++;
7236 }
7237
7238 /* update fake 'exit' subprog as well */
7239 for (; i <= env->subprog_cnt; i++)
7240 env->subprog_info[i].start -= cnt;
7241
7242 return 0;
7243}
7244
7245static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
7246 u32 cnt)
7247{
7248 struct bpf_prog *prog = env->prog;
7249 u32 i, l_off, l_cnt, nr_linfo;
7250 struct bpf_line_info *linfo;
7251
7252 nr_linfo = prog->aux->nr_linfo;
7253 if (!nr_linfo)
7254 return 0;
7255
7256 linfo = prog->aux->linfo;
7257
7258 /* find first line info to remove, count lines to be removed */
7259 for (i = 0; i < nr_linfo; i++)
7260 if (linfo[i].insn_off >= off)
7261 break;
7262
7263 l_off = i;
7264 l_cnt = 0;
7265 for (; i < nr_linfo; i++)
7266 if (linfo[i].insn_off < off + cnt)
7267 l_cnt++;
7268 else
7269 break;
7270
7271 /* First live insn doesn't match first live linfo, it needs to "inherit"
7272 * last removed linfo. prog is already modified, so prog->len == off
7273 * means no live instructions after (tail of the program was removed).
7274 */
7275 if (prog->len != off && l_cnt &&
7276 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
7277 l_cnt--;
7278 linfo[--i].insn_off = off + cnt;
7279 }
7280
7281 /* remove the line info which refer to the removed instructions */
7282 if (l_cnt) {
7283 memmove(linfo + l_off, linfo + i,
7284 sizeof(*linfo) * (nr_linfo - i));
7285
7286 prog->aux->nr_linfo -= l_cnt;
7287 nr_linfo = prog->aux->nr_linfo;
7288 }
7289
7290 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
7291 for (i = l_off; i < nr_linfo; i++)
7292 linfo[i].insn_off -= cnt;
7293
7294 /* fix up all subprogs (incl. 'exit') which start >= off */
7295 for (i = 0; i <= env->subprog_cnt; i++)
7296 if (env->subprog_info[i].linfo_idx > l_off) {
7297 /* program may have started in the removed region but
7298 * may not be fully removed
7299 */
7300 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
7301 env->subprog_info[i].linfo_idx -= l_cnt;
7302 else
7303 env->subprog_info[i].linfo_idx = l_off;
7304 }
7305
7306 return 0;
7307}
7308
7309static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
7310{
7311 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7312 unsigned int orig_prog_len = env->prog->len;
7313 int err;
7314
08ca90af
JK
7315 if (bpf_prog_is_dev_bound(env->prog->aux))
7316 bpf_prog_offload_remove_insns(env, off, cnt);
7317
52875a04
JK
7318 err = bpf_remove_insns(env->prog, off, cnt);
7319 if (err)
7320 return err;
7321
7322 err = adjust_subprog_starts_after_remove(env, off, cnt);
7323 if (err)
7324 return err;
7325
7326 err = bpf_adj_linfo_after_remove(env, off, cnt);
7327 if (err)
7328 return err;
7329
7330 memmove(aux_data + off, aux_data + off + cnt,
7331 sizeof(*aux_data) * (orig_prog_len - off - cnt));
7332
7333 return 0;
7334}
7335
2a5418a1
DB
7336/* The verifier does more data flow analysis than llvm and will not
7337 * explore branches that are dead at run time. Malicious programs can
7338 * have dead code too. Therefore replace all dead at-run-time code
7339 * with 'ja -1'.
7340 *
7341 * Just nops are not optimal, e.g. if they would sit at the end of the
7342 * program and through another bug we would manage to jump there, then
7343 * we'd execute beyond program memory otherwise. Returning exception
7344 * code also wouldn't work since we can have subprogs where the dead
7345 * code could be located.
c131187d
AS
7346 */
7347static void sanitize_dead_code(struct bpf_verifier_env *env)
7348{
7349 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 7350 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
7351 struct bpf_insn *insn = env->prog->insnsi;
7352 const int insn_cnt = env->prog->len;
7353 int i;
7354
7355 for (i = 0; i < insn_cnt; i++) {
7356 if (aux_data[i].seen)
7357 continue;
2a5418a1 7358 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
7359 }
7360}
7361
e2ae4ca2
JK
7362static bool insn_is_cond_jump(u8 code)
7363{
7364 u8 op;
7365
092ed096
JW
7366 if (BPF_CLASS(code) == BPF_JMP32)
7367 return true;
7368
e2ae4ca2
JK
7369 if (BPF_CLASS(code) != BPF_JMP)
7370 return false;
7371
7372 op = BPF_OP(code);
7373 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
7374}
7375
7376static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
7377{
7378 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7379 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
7380 struct bpf_insn *insn = env->prog->insnsi;
7381 const int insn_cnt = env->prog->len;
7382 int i;
7383
7384 for (i = 0; i < insn_cnt; i++, insn++) {
7385 if (!insn_is_cond_jump(insn->code))
7386 continue;
7387
7388 if (!aux_data[i + 1].seen)
7389 ja.off = insn->off;
7390 else if (!aux_data[i + 1 + insn->off].seen)
7391 ja.off = 0;
7392 else
7393 continue;
7394
08ca90af
JK
7395 if (bpf_prog_is_dev_bound(env->prog->aux))
7396 bpf_prog_offload_replace_insn(env, i, &ja);
7397
e2ae4ca2
JK
7398 memcpy(insn, &ja, sizeof(ja));
7399 }
7400}
7401
52875a04
JK
7402static int opt_remove_dead_code(struct bpf_verifier_env *env)
7403{
7404 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7405 int insn_cnt = env->prog->len;
7406 int i, err;
7407
7408 for (i = 0; i < insn_cnt; i++) {
7409 int j;
7410
7411 j = 0;
7412 while (i + j < insn_cnt && !aux_data[i + j].seen)
7413 j++;
7414 if (!j)
7415 continue;
7416
7417 err = verifier_remove_insns(env, i, j);
7418 if (err)
7419 return err;
7420 insn_cnt = env->prog->len;
7421 }
7422
7423 return 0;
7424}
7425
a1b14abc
JK
7426static int opt_remove_nops(struct bpf_verifier_env *env)
7427{
7428 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
7429 struct bpf_insn *insn = env->prog->insnsi;
7430 int insn_cnt = env->prog->len;
7431 int i, err;
7432
7433 for (i = 0; i < insn_cnt; i++) {
7434 if (memcmp(&insn[i], &ja, sizeof(ja)))
7435 continue;
7436
7437 err = verifier_remove_insns(env, i, 1);
7438 if (err)
7439 return err;
7440 insn_cnt--;
7441 i--;
7442 }
7443
7444 return 0;
7445}
7446
c64b7983
JS
7447/* convert load instructions that access fields of a context type into a
7448 * sequence of instructions that access fields of the underlying structure:
7449 * struct __sk_buff -> struct sk_buff
7450 * struct bpf_sock_ops -> struct sock
9bac3d6d 7451 */
58e2af8b 7452static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 7453{
00176a34 7454 const struct bpf_verifier_ops *ops = env->ops;
f96da094 7455 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 7456 const int insn_cnt = env->prog->len;
36bbef52 7457 struct bpf_insn insn_buf[16], *insn;
46f53a65 7458 u32 target_size, size_default, off;
9bac3d6d 7459 struct bpf_prog *new_prog;
d691f9e8 7460 enum bpf_access_type type;
f96da094 7461 bool is_narrower_load;
9bac3d6d 7462
b09928b9
DB
7463 if (ops->gen_prologue || env->seen_direct_write) {
7464 if (!ops->gen_prologue) {
7465 verbose(env, "bpf verifier is misconfigured\n");
7466 return -EINVAL;
7467 }
36bbef52
DB
7468 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
7469 env->prog);
7470 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 7471 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
7472 return -EINVAL;
7473 } else if (cnt) {
8041902d 7474 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
7475 if (!new_prog)
7476 return -ENOMEM;
8041902d 7477
36bbef52 7478 env->prog = new_prog;
3df126f3 7479 delta += cnt - 1;
36bbef52
DB
7480 }
7481 }
7482
c64b7983 7483 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
7484 return 0;
7485
3df126f3 7486 insn = env->prog->insnsi + delta;
36bbef52 7487
9bac3d6d 7488 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
7489 bpf_convert_ctx_access_t convert_ctx_access;
7490
62c7989b
DB
7491 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
7492 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
7493 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 7494 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 7495 type = BPF_READ;
62c7989b
DB
7496 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
7497 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
7498 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 7499 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
7500 type = BPF_WRITE;
7501 else
9bac3d6d
AS
7502 continue;
7503
af86ca4e
AS
7504 if (type == BPF_WRITE &&
7505 env->insn_aux_data[i + delta].sanitize_stack_off) {
7506 struct bpf_insn patch[] = {
7507 /* Sanitize suspicious stack slot with zero.
7508 * There are no memory dependencies for this store,
7509 * since it's only using frame pointer and immediate
7510 * constant of zero
7511 */
7512 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
7513 env->insn_aux_data[i + delta].sanitize_stack_off,
7514 0),
7515 /* the original STX instruction will immediately
7516 * overwrite the same stack slot with appropriate value
7517 */
7518 *insn,
7519 };
7520
7521 cnt = ARRAY_SIZE(patch);
7522 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
7523 if (!new_prog)
7524 return -ENOMEM;
7525
7526 delta += cnt - 1;
7527 env->prog = new_prog;
7528 insn = new_prog->insnsi + i + delta;
7529 continue;
7530 }
7531
c64b7983
JS
7532 switch (env->insn_aux_data[i + delta].ptr_type) {
7533 case PTR_TO_CTX:
7534 if (!ops->convert_ctx_access)
7535 continue;
7536 convert_ctx_access = ops->convert_ctx_access;
7537 break;
7538 case PTR_TO_SOCKET:
46f8bc92 7539 case PTR_TO_SOCK_COMMON:
c64b7983
JS
7540 convert_ctx_access = bpf_sock_convert_ctx_access;
7541 break;
655a51e5
MKL
7542 case PTR_TO_TCP_SOCK:
7543 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
7544 break;
c64b7983 7545 default:
9bac3d6d 7546 continue;
c64b7983 7547 }
9bac3d6d 7548
31fd8581 7549 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 7550 size = BPF_LDST_BYTES(insn);
31fd8581
YS
7551
7552 /* If the read access is a narrower load of the field,
7553 * convert to a 4/8-byte load, to minimum program type specific
7554 * convert_ctx_access changes. If conversion is successful,
7555 * we will apply proper mask to the result.
7556 */
f96da094 7557 is_narrower_load = size < ctx_field_size;
46f53a65
AI
7558 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
7559 off = insn->off;
31fd8581 7560 if (is_narrower_load) {
f96da094
DB
7561 u8 size_code;
7562
7563 if (type == BPF_WRITE) {
61bd5218 7564 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
7565 return -EINVAL;
7566 }
31fd8581 7567
f96da094 7568 size_code = BPF_H;
31fd8581
YS
7569 if (ctx_field_size == 4)
7570 size_code = BPF_W;
7571 else if (ctx_field_size == 8)
7572 size_code = BPF_DW;
f96da094 7573
bc23105c 7574 insn->off = off & ~(size_default - 1);
31fd8581
YS
7575 insn->code = BPF_LDX | BPF_MEM | size_code;
7576 }
f96da094
DB
7577
7578 target_size = 0;
c64b7983
JS
7579 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
7580 &target_size);
f96da094
DB
7581 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
7582 (ctx_field_size && !target_size)) {
61bd5218 7583 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
7584 return -EINVAL;
7585 }
f96da094
DB
7586
7587 if (is_narrower_load && size < target_size) {
46f53a65
AI
7588 u8 shift = (off & (size_default - 1)) * 8;
7589
7590 if (ctx_field_size <= 4) {
7591 if (shift)
7592 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
7593 insn->dst_reg,
7594 shift);
31fd8581 7595 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 7596 (1 << size * 8) - 1);
46f53a65
AI
7597 } else {
7598 if (shift)
7599 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
7600 insn->dst_reg,
7601 shift);
31fd8581 7602 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 7603 (1ULL << size * 8) - 1);
46f53a65 7604 }
31fd8581 7605 }
9bac3d6d 7606
8041902d 7607 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
7608 if (!new_prog)
7609 return -ENOMEM;
7610
3df126f3 7611 delta += cnt - 1;
9bac3d6d
AS
7612
7613 /* keep walking new program and skip insns we just inserted */
7614 env->prog = new_prog;
3df126f3 7615 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
7616 }
7617
7618 return 0;
7619}
7620
1c2a088a
AS
7621static int jit_subprogs(struct bpf_verifier_env *env)
7622{
7623 struct bpf_prog *prog = env->prog, **func, *tmp;
7624 int i, j, subprog_start, subprog_end = 0, len, subprog;
7105e828 7625 struct bpf_insn *insn;
1c2a088a 7626 void *old_bpf_func;
c454a46b 7627 int err;
1c2a088a 7628
f910cefa 7629 if (env->subprog_cnt <= 1)
1c2a088a
AS
7630 return 0;
7631
7105e828 7632 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1c2a088a
AS
7633 if (insn->code != (BPF_JMP | BPF_CALL) ||
7634 insn->src_reg != BPF_PSEUDO_CALL)
7635 continue;
c7a89784
DB
7636 /* Upon error here we cannot fall back to interpreter but
7637 * need a hard reject of the program. Thus -EFAULT is
7638 * propagated in any case.
7639 */
1c2a088a
AS
7640 subprog = find_subprog(env, i + insn->imm + 1);
7641 if (subprog < 0) {
7642 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7643 i + insn->imm + 1);
7644 return -EFAULT;
7645 }
7646 /* temporarily remember subprog id inside insn instead of
7647 * aux_data, since next loop will split up all insns into funcs
7648 */
f910cefa 7649 insn->off = subprog;
1c2a088a
AS
7650 /* remember original imm in case JIT fails and fallback
7651 * to interpreter will be needed
7652 */
7653 env->insn_aux_data[i].call_imm = insn->imm;
7654 /* point imm to __bpf_call_base+1 from JITs point of view */
7655 insn->imm = 1;
7656 }
7657
c454a46b
MKL
7658 err = bpf_prog_alloc_jited_linfo(prog);
7659 if (err)
7660 goto out_undo_insn;
7661
7662 err = -ENOMEM;
6396bb22 7663 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 7664 if (!func)
c7a89784 7665 goto out_undo_insn;
1c2a088a 7666
f910cefa 7667 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 7668 subprog_start = subprog_end;
4cb3d99c 7669 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
7670
7671 len = subprog_end - subprog_start;
492ecee8
AS
7672 /* BPF_PROG_RUN doesn't call subprogs directly,
7673 * hence main prog stats include the runtime of subprogs.
7674 * subprogs don't have IDs and not reachable via prog_get_next_id
7675 * func[i]->aux->stats will never be accessed and stays NULL
7676 */
7677 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
7678 if (!func[i])
7679 goto out_free;
7680 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
7681 len * sizeof(struct bpf_insn));
4f74d809 7682 func[i]->type = prog->type;
1c2a088a 7683 func[i]->len = len;
4f74d809
DB
7684 if (bpf_prog_calc_tag(func[i]))
7685 goto out_free;
1c2a088a 7686 func[i]->is_func = 1;
ba64e7d8
YS
7687 func[i]->aux->func_idx = i;
7688 /* the btf and func_info will be freed only at prog->aux */
7689 func[i]->aux->btf = prog->aux->btf;
7690 func[i]->aux->func_info = prog->aux->func_info;
7691
1c2a088a
AS
7692 /* Use bpf_prog_F_tag to indicate functions in stack traces.
7693 * Long term would need debug info to populate names
7694 */
7695 func[i]->aux->name[0] = 'F';
9c8105bd 7696 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 7697 func[i]->jit_requested = 1;
c454a46b
MKL
7698 func[i]->aux->linfo = prog->aux->linfo;
7699 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
7700 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
7701 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
1c2a088a
AS
7702 func[i] = bpf_int_jit_compile(func[i]);
7703 if (!func[i]->jited) {
7704 err = -ENOTSUPP;
7705 goto out_free;
7706 }
7707 cond_resched();
7708 }
7709 /* at this point all bpf functions were successfully JITed
7710 * now populate all bpf_calls with correct addresses and
7711 * run last pass of JIT
7712 */
f910cefa 7713 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
7714 insn = func[i]->insnsi;
7715 for (j = 0; j < func[i]->len; j++, insn++) {
7716 if (insn->code != (BPF_JMP | BPF_CALL) ||
7717 insn->src_reg != BPF_PSEUDO_CALL)
7718 continue;
7719 subprog = insn->off;
0d306c31
PB
7720 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
7721 __bpf_call_base;
1c2a088a 7722 }
2162fed4
SD
7723
7724 /* we use the aux data to keep a list of the start addresses
7725 * of the JITed images for each function in the program
7726 *
7727 * for some architectures, such as powerpc64, the imm field
7728 * might not be large enough to hold the offset of the start
7729 * address of the callee's JITed image from __bpf_call_base
7730 *
7731 * in such cases, we can lookup the start address of a callee
7732 * by using its subprog id, available from the off field of
7733 * the call instruction, as an index for this list
7734 */
7735 func[i]->aux->func = func;
7736 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 7737 }
f910cefa 7738 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
7739 old_bpf_func = func[i]->bpf_func;
7740 tmp = bpf_int_jit_compile(func[i]);
7741 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
7742 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 7743 err = -ENOTSUPP;
1c2a088a
AS
7744 goto out_free;
7745 }
7746 cond_resched();
7747 }
7748
7749 /* finally lock prog and jit images for all functions and
7750 * populate kallsysm
7751 */
f910cefa 7752 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
7753 bpf_prog_lock_ro(func[i]);
7754 bpf_prog_kallsyms_add(func[i]);
7755 }
7105e828
DB
7756
7757 /* Last step: make now unused interpreter insns from main
7758 * prog consistent for later dump requests, so they can
7759 * later look the same as if they were interpreted only.
7760 */
7761 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7105e828
DB
7762 if (insn->code != (BPF_JMP | BPF_CALL) ||
7763 insn->src_reg != BPF_PSEUDO_CALL)
7764 continue;
7765 insn->off = env->insn_aux_data[i].call_imm;
7766 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 7767 insn->imm = subprog;
7105e828
DB
7768 }
7769
1c2a088a
AS
7770 prog->jited = 1;
7771 prog->bpf_func = func[0]->bpf_func;
7772 prog->aux->func = func;
f910cefa 7773 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 7774 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
7775 return 0;
7776out_free:
f910cefa 7777 for (i = 0; i < env->subprog_cnt; i++)
1c2a088a
AS
7778 if (func[i])
7779 bpf_jit_free(func[i]);
7780 kfree(func);
c7a89784 7781out_undo_insn:
1c2a088a
AS
7782 /* cleanup main prog to be interpreted */
7783 prog->jit_requested = 0;
7784 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7785 if (insn->code != (BPF_JMP | BPF_CALL) ||
7786 insn->src_reg != BPF_PSEUDO_CALL)
7787 continue;
7788 insn->off = 0;
7789 insn->imm = env->insn_aux_data[i].call_imm;
7790 }
c454a46b 7791 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
7792 return err;
7793}
7794
1ea47e01
AS
7795static int fixup_call_args(struct bpf_verifier_env *env)
7796{
19d28fbd 7797#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
7798 struct bpf_prog *prog = env->prog;
7799 struct bpf_insn *insn = prog->insnsi;
7800 int i, depth;
19d28fbd 7801#endif
e4052d06 7802 int err = 0;
1ea47e01 7803
e4052d06
QM
7804 if (env->prog->jit_requested &&
7805 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
7806 err = jit_subprogs(env);
7807 if (err == 0)
1c2a088a 7808 return 0;
c7a89784
DB
7809 if (err == -EFAULT)
7810 return err;
19d28fbd
DM
7811 }
7812#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
7813 for (i = 0; i < prog->len; i++, insn++) {
7814 if (insn->code != (BPF_JMP | BPF_CALL) ||
7815 insn->src_reg != BPF_PSEUDO_CALL)
7816 continue;
7817 depth = get_callee_stack_depth(env, insn, i);
7818 if (depth < 0)
7819 return depth;
7820 bpf_patch_call_args(insn, depth);
7821 }
19d28fbd
DM
7822 err = 0;
7823#endif
7824 return err;
1ea47e01
AS
7825}
7826
79741b3b 7827/* fixup insn->imm field of bpf_call instructions
81ed18ab 7828 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
7829 *
7830 * this function is called after eBPF program passed verification
7831 */
79741b3b 7832static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 7833{
79741b3b
AS
7834 struct bpf_prog *prog = env->prog;
7835 struct bpf_insn *insn = prog->insnsi;
e245c5c6 7836 const struct bpf_func_proto *fn;
79741b3b 7837 const int insn_cnt = prog->len;
09772d92 7838 const struct bpf_map_ops *ops;
c93552c4 7839 struct bpf_insn_aux_data *aux;
81ed18ab
AS
7840 struct bpf_insn insn_buf[16];
7841 struct bpf_prog *new_prog;
7842 struct bpf_map *map_ptr;
7843 int i, cnt, delta = 0;
e245c5c6 7844
79741b3b 7845 for (i = 0; i < insn_cnt; i++, insn++) {
f6b1b3bf
DB
7846 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
7847 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
7848 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 7849 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf
DB
7850 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
7851 struct bpf_insn mask_and_div[] = {
7852 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
7853 /* Rx div 0 -> 0 */
7854 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
7855 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
7856 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7857 *insn,
7858 };
7859 struct bpf_insn mask_and_mod[] = {
7860 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
7861 /* Rx mod 0 -> Rx */
7862 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
7863 *insn,
7864 };
7865 struct bpf_insn *patchlet;
7866
7867 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
7868 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
7869 patchlet = mask_and_div + (is64 ? 1 : 0);
7870 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
7871 } else {
7872 patchlet = mask_and_mod + (is64 ? 1 : 0);
7873 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
7874 }
7875
7876 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
7877 if (!new_prog)
7878 return -ENOMEM;
7879
7880 delta += cnt - 1;
7881 env->prog = prog = new_prog;
7882 insn = new_prog->insnsi + i + delta;
7883 continue;
7884 }
7885
e0cea7ce
DB
7886 if (BPF_CLASS(insn->code) == BPF_LD &&
7887 (BPF_MODE(insn->code) == BPF_ABS ||
7888 BPF_MODE(insn->code) == BPF_IND)) {
7889 cnt = env->ops->gen_ld_abs(insn, insn_buf);
7890 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
7891 verbose(env, "bpf verifier is misconfigured\n");
7892 return -EINVAL;
7893 }
7894
7895 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7896 if (!new_prog)
7897 return -ENOMEM;
7898
7899 delta += cnt - 1;
7900 env->prog = prog = new_prog;
7901 insn = new_prog->insnsi + i + delta;
7902 continue;
7903 }
7904
979d63d5
DB
7905 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
7906 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
7907 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
7908 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
7909 struct bpf_insn insn_buf[16];
7910 struct bpf_insn *patch = &insn_buf[0];
7911 bool issrc, isneg;
7912 u32 off_reg;
7913
7914 aux = &env->insn_aux_data[i + delta];
3612af78
DB
7915 if (!aux->alu_state ||
7916 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
7917 continue;
7918
7919 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
7920 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
7921 BPF_ALU_SANITIZE_SRC;
7922
7923 off_reg = issrc ? insn->src_reg : insn->dst_reg;
7924 if (isneg)
7925 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
7926 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
7927 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
7928 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
7929 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
7930 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
7931 if (issrc) {
7932 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
7933 off_reg);
7934 insn->src_reg = BPF_REG_AX;
7935 } else {
7936 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
7937 BPF_REG_AX);
7938 }
7939 if (isneg)
7940 insn->code = insn->code == code_add ?
7941 code_sub : code_add;
7942 *patch++ = *insn;
7943 if (issrc && isneg)
7944 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
7945 cnt = patch - insn_buf;
7946
7947 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7948 if (!new_prog)
7949 return -ENOMEM;
7950
7951 delta += cnt - 1;
7952 env->prog = prog = new_prog;
7953 insn = new_prog->insnsi + i + delta;
7954 continue;
7955 }
7956
79741b3b
AS
7957 if (insn->code != (BPF_JMP | BPF_CALL))
7958 continue;
cc8b0b92
AS
7959 if (insn->src_reg == BPF_PSEUDO_CALL)
7960 continue;
e245c5c6 7961
79741b3b
AS
7962 if (insn->imm == BPF_FUNC_get_route_realm)
7963 prog->dst_needed = 1;
7964 if (insn->imm == BPF_FUNC_get_prandom_u32)
7965 bpf_user_rnd_init_once();
9802d865
JB
7966 if (insn->imm == BPF_FUNC_override_return)
7967 prog->kprobe_override = 1;
79741b3b 7968 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
7969 /* If we tail call into other programs, we
7970 * cannot make any assumptions since they can
7971 * be replaced dynamically during runtime in
7972 * the program array.
7973 */
7974 prog->cb_access = 1;
80a58d02 7975 env->prog->aux->stack_depth = MAX_BPF_STACK;
e647815a 7976 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 7977
79741b3b
AS
7978 /* mark bpf_tail_call as different opcode to avoid
7979 * conditional branch in the interpeter for every normal
7980 * call and to prevent accidental JITing by JIT compiler
7981 * that doesn't support bpf_tail_call yet
e245c5c6 7982 */
79741b3b 7983 insn->imm = 0;
71189fa9 7984 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 7985
c93552c4
DB
7986 aux = &env->insn_aux_data[i + delta];
7987 if (!bpf_map_ptr_unpriv(aux))
7988 continue;
7989
b2157399
AS
7990 /* instead of changing every JIT dealing with tail_call
7991 * emit two extra insns:
7992 * if (index >= max_entries) goto out;
7993 * index &= array->index_mask;
7994 * to avoid out-of-bounds cpu speculation
7995 */
c93552c4 7996 if (bpf_map_ptr_poisoned(aux)) {
40950343 7997 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
7998 return -EINVAL;
7999 }
c93552c4
DB
8000
8001 map_ptr = BPF_MAP_PTR(aux->map_state);
b2157399
AS
8002 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
8003 map_ptr->max_entries, 2);
8004 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
8005 container_of(map_ptr,
8006 struct bpf_array,
8007 map)->index_mask);
8008 insn_buf[2] = *insn;
8009 cnt = 3;
8010 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
8011 if (!new_prog)
8012 return -ENOMEM;
8013
8014 delta += cnt - 1;
8015 env->prog = prog = new_prog;
8016 insn = new_prog->insnsi + i + delta;
79741b3b
AS
8017 continue;
8018 }
e245c5c6 8019
89c63074 8020 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
8021 * and other inlining handlers are currently limited to 64 bit
8022 * only.
89c63074 8023 */
60b58afc 8024 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
8025 (insn->imm == BPF_FUNC_map_lookup_elem ||
8026 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
8027 insn->imm == BPF_FUNC_map_delete_elem ||
8028 insn->imm == BPF_FUNC_map_push_elem ||
8029 insn->imm == BPF_FUNC_map_pop_elem ||
8030 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
8031 aux = &env->insn_aux_data[i + delta];
8032 if (bpf_map_ptr_poisoned(aux))
8033 goto patch_call_imm;
8034
8035 map_ptr = BPF_MAP_PTR(aux->map_state);
09772d92
DB
8036 ops = map_ptr->ops;
8037 if (insn->imm == BPF_FUNC_map_lookup_elem &&
8038 ops->map_gen_lookup) {
8039 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
8040 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
8041 verbose(env, "bpf verifier is misconfigured\n");
8042 return -EINVAL;
8043 }
81ed18ab 8044
09772d92
DB
8045 new_prog = bpf_patch_insn_data(env, i + delta,
8046 insn_buf, cnt);
8047 if (!new_prog)
8048 return -ENOMEM;
81ed18ab 8049
09772d92
DB
8050 delta += cnt - 1;
8051 env->prog = prog = new_prog;
8052 insn = new_prog->insnsi + i + delta;
8053 continue;
8054 }
81ed18ab 8055
09772d92
DB
8056 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
8057 (void *(*)(struct bpf_map *map, void *key))NULL));
8058 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
8059 (int (*)(struct bpf_map *map, void *key))NULL));
8060 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
8061 (int (*)(struct bpf_map *map, void *key, void *value,
8062 u64 flags))NULL));
84430d42
DB
8063 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
8064 (int (*)(struct bpf_map *map, void *value,
8065 u64 flags))NULL));
8066 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
8067 (int (*)(struct bpf_map *map, void *value))NULL));
8068 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
8069 (int (*)(struct bpf_map *map, void *value))NULL));
8070
09772d92
DB
8071 switch (insn->imm) {
8072 case BPF_FUNC_map_lookup_elem:
8073 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
8074 __bpf_call_base;
8075 continue;
8076 case BPF_FUNC_map_update_elem:
8077 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
8078 __bpf_call_base;
8079 continue;
8080 case BPF_FUNC_map_delete_elem:
8081 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
8082 __bpf_call_base;
8083 continue;
84430d42
DB
8084 case BPF_FUNC_map_push_elem:
8085 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
8086 __bpf_call_base;
8087 continue;
8088 case BPF_FUNC_map_pop_elem:
8089 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
8090 __bpf_call_base;
8091 continue;
8092 case BPF_FUNC_map_peek_elem:
8093 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
8094 __bpf_call_base;
8095 continue;
09772d92 8096 }
81ed18ab 8097
09772d92 8098 goto patch_call_imm;
81ed18ab
AS
8099 }
8100
8101patch_call_imm:
5e43f899 8102 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
8103 /* all functions that have prototype and verifier allowed
8104 * programs to call them, must be real in-kernel functions
8105 */
8106 if (!fn->func) {
61bd5218
JK
8107 verbose(env,
8108 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
8109 func_id_name(insn->imm), insn->imm);
8110 return -EFAULT;
e245c5c6 8111 }
79741b3b 8112 insn->imm = fn->func - __bpf_call_base;
e245c5c6 8113 }
e245c5c6 8114
79741b3b
AS
8115 return 0;
8116}
e245c5c6 8117
58e2af8b 8118static void free_states(struct bpf_verifier_env *env)
f1bca824 8119{
58e2af8b 8120 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
8121 int i;
8122
9f4686c4
AS
8123 sl = env->free_list;
8124 while (sl) {
8125 sln = sl->next;
8126 free_verifier_state(&sl->state, false);
8127 kfree(sl);
8128 sl = sln;
8129 }
8130
f1bca824
AS
8131 if (!env->explored_states)
8132 return;
8133
8134 for (i = 0; i < env->prog->len; i++) {
8135 sl = env->explored_states[i];
8136
8137 if (sl)
8138 while (sl != STATE_LIST_MARK) {
8139 sln = sl->next;
1969db47 8140 free_verifier_state(&sl->state, false);
f1bca824
AS
8141 kfree(sl);
8142 sl = sln;
8143 }
8144 }
8145
71dde681 8146 kvfree(env->explored_states);
f1bca824
AS
8147}
8148
06ee7115
AS
8149static void print_verification_stats(struct bpf_verifier_env *env)
8150{
8151 int i;
8152
8153 if (env->log.level & BPF_LOG_STATS) {
8154 verbose(env, "verification time %lld usec\n",
8155 div_u64(env->verification_time, 1000));
8156 verbose(env, "stack depth ");
8157 for (i = 0; i < env->subprog_cnt; i++) {
8158 u32 depth = env->subprog_info[i].stack_depth;
8159
8160 verbose(env, "%d", depth);
8161 if (i + 1 < env->subprog_cnt)
8162 verbose(env, "+");
8163 }
8164 verbose(env, "\n");
8165 }
8166 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
8167 "total_states %d peak_states %d mark_read %d\n",
8168 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
8169 env->max_states_per_insn, env->total_states,
8170 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
8171}
8172
838e9690
YS
8173int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
8174 union bpf_attr __user *uattr)
51580e79 8175{
06ee7115 8176 u64 start_time = ktime_get_ns();
58e2af8b 8177 struct bpf_verifier_env *env;
b9193c1b 8178 struct bpf_verifier_log *log;
9e4c24e7 8179 int i, len, ret = -EINVAL;
e2ae4ca2 8180 bool is_priv;
51580e79 8181
eba0c929
AB
8182 /* no program is valid */
8183 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
8184 return -EINVAL;
8185
58e2af8b 8186 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
8187 * allocate/free it every time bpf_check() is called
8188 */
58e2af8b 8189 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
8190 if (!env)
8191 return -ENOMEM;
61bd5218 8192 log = &env->log;
cbd35700 8193
9e4c24e7 8194 len = (*prog)->len;
fad953ce 8195 env->insn_aux_data =
9e4c24e7 8196 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
8197 ret = -ENOMEM;
8198 if (!env->insn_aux_data)
8199 goto err_free_env;
9e4c24e7
JK
8200 for (i = 0; i < len; i++)
8201 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 8202 env->prog = *prog;
00176a34 8203 env->ops = bpf_verifier_ops[env->prog->type];
45a73c17 8204 is_priv = capable(CAP_SYS_ADMIN);
0246e64d 8205
cbd35700 8206 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
8207 if (!is_priv)
8208 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
8209
8210 if (attr->log_level || attr->log_buf || attr->log_size) {
8211 /* user requested verbose verifier output
8212 * and supplied buffer to store the verification trace
8213 */
e7bf8249
JK
8214 log->level = attr->log_level;
8215 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
8216 log->len_total = attr->log_size;
cbd35700
AS
8217
8218 ret = -EINVAL;
e7bf8249 8219 /* log attributes have to be sane */
7a9f5c65 8220 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 8221 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 8222 goto err_unlock;
cbd35700 8223 }
1ad2f583
DB
8224
8225 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
8226 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 8227 env->strict_alignment = true;
e9ee9efc
DM
8228 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
8229 env->strict_alignment = false;
cbd35700 8230
e2ae4ca2
JK
8231 env->allow_ptr_leaks = is_priv;
8232
f4e3ec0d
JK
8233 ret = replace_map_fd_with_map_ptr(env);
8234 if (ret < 0)
8235 goto skip_full_check;
8236
cae1927c 8237 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 8238 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 8239 if (ret)
f4e3ec0d 8240 goto skip_full_check;
ab3f0063
JK
8241 }
8242
71dde681 8243 env->explored_states = kvcalloc(env->prog->len,
58e2af8b 8244 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
8245 GFP_USER);
8246 ret = -ENOMEM;
8247 if (!env->explored_states)
8248 goto skip_full_check;
8249
d9762e84 8250 ret = check_subprogs(env);
475fb78f
AS
8251 if (ret < 0)
8252 goto skip_full_check;
8253
c454a46b 8254 ret = check_btf_info(env, attr, uattr);
838e9690
YS
8255 if (ret < 0)
8256 goto skip_full_check;
8257
d9762e84
MKL
8258 ret = check_cfg(env);
8259 if (ret < 0)
8260 goto skip_full_check;
8261
17a52670 8262 ret = do_check(env);
8c01c4f8
CG
8263 if (env->cur_state) {
8264 free_verifier_state(env->cur_state, true);
8265 env->cur_state = NULL;
8266 }
cbd35700 8267
c941ce9c
QM
8268 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
8269 ret = bpf_prog_offload_finalize(env);
8270
0246e64d 8271skip_full_check:
638f5b90 8272 while (!pop_stack(env, NULL, NULL));
f1bca824 8273 free_states(env);
0246e64d 8274
c131187d 8275 if (ret == 0)
9b38c405 8276 ret = check_max_stack_depth(env);
c131187d 8277
9b38c405 8278 /* instruction rewrites happen after this point */
e2ae4ca2
JK
8279 if (is_priv) {
8280 if (ret == 0)
8281 opt_hard_wire_dead_code_branches(env);
52875a04
JK
8282 if (ret == 0)
8283 ret = opt_remove_dead_code(env);
a1b14abc
JK
8284 if (ret == 0)
8285 ret = opt_remove_nops(env);
52875a04
JK
8286 } else {
8287 if (ret == 0)
8288 sanitize_dead_code(env);
e2ae4ca2
JK
8289 }
8290
9bac3d6d
AS
8291 if (ret == 0)
8292 /* program is valid, convert *(u32*)(ctx + off) accesses */
8293 ret = convert_ctx_accesses(env);
8294
e245c5c6 8295 if (ret == 0)
79741b3b 8296 ret = fixup_bpf_calls(env);
e245c5c6 8297
1ea47e01
AS
8298 if (ret == 0)
8299 ret = fixup_call_args(env);
8300
06ee7115
AS
8301 env->verification_time = ktime_get_ns() - start_time;
8302 print_verification_stats(env);
8303
a2a7d570 8304 if (log->level && bpf_verifier_log_full(log))
cbd35700 8305 ret = -ENOSPC;
a2a7d570 8306 if (log->level && !log->ubuf) {
cbd35700 8307 ret = -EFAULT;
a2a7d570 8308 goto err_release_maps;
cbd35700
AS
8309 }
8310
0246e64d
AS
8311 if (ret == 0 && env->used_map_cnt) {
8312 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
8313 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
8314 sizeof(env->used_maps[0]),
8315 GFP_KERNEL);
0246e64d 8316
9bac3d6d 8317 if (!env->prog->aux->used_maps) {
0246e64d 8318 ret = -ENOMEM;
a2a7d570 8319 goto err_release_maps;
0246e64d
AS
8320 }
8321
9bac3d6d 8322 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 8323 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 8324 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
8325
8326 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
8327 * bpf_ld_imm64 instructions
8328 */
8329 convert_pseudo_ld_imm64(env);
8330 }
cbd35700 8331
ba64e7d8
YS
8332 if (ret == 0)
8333 adjust_btf_func(env);
8334
a2a7d570 8335err_release_maps:
9bac3d6d 8336 if (!env->prog->aux->used_maps)
0246e64d 8337 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 8338 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
8339 */
8340 release_maps(env);
9bac3d6d 8341 *prog = env->prog;
3df126f3 8342err_unlock:
45a73c17
AS
8343 if (!is_priv)
8344 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
8345 vfree(env->insn_aux_data);
8346err_free_env:
8347 kfree(env);
51580e79
AS
8348 return ret;
8349}