]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - kernel/bpf/verifier.c
Merge branch 'bpf-send-sig'
[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
dc2a4ebc
AS
5439static u32 state_htab_size(struct bpf_verifier_env *env)
5440{
5441 return env->prog->len;
5442}
5443
5d839021
AS
5444static struct bpf_verifier_state_list **explored_state(
5445 struct bpf_verifier_env *env,
5446 int idx)
5447{
dc2a4ebc
AS
5448 struct bpf_verifier_state *cur = env->cur_state;
5449 struct bpf_func_state *state = cur->frame[cur->curframe];
5450
5451 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
5452}
5453
5454static void init_explored_state(struct bpf_verifier_env *env, int idx)
5455{
a8f500af 5456 env->insn_aux_data[idx].prune_point = true;
5d839021 5457}
f1bca824 5458
475fb78f
AS
5459/* t, w, e - match pseudo-code above:
5460 * t - index of current instruction
5461 * w - next instruction
5462 * e - edge
5463 */
58e2af8b 5464static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
475fb78f 5465{
7df737e9
AS
5466 int *insn_stack = env->cfg.insn_stack;
5467 int *insn_state = env->cfg.insn_state;
5468
475fb78f
AS
5469 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
5470 return 0;
5471
5472 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
5473 return 0;
5474
5475 if (w < 0 || w >= env->prog->len) {
d9762e84 5476 verbose_linfo(env, t, "%d: ", t);
61bd5218 5477 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
5478 return -EINVAL;
5479 }
5480
f1bca824
AS
5481 if (e == BRANCH)
5482 /* mark branch target for state pruning */
5d839021 5483 init_explored_state(env, w);
f1bca824 5484
475fb78f
AS
5485 if (insn_state[w] == 0) {
5486 /* tree-edge */
5487 insn_state[t] = DISCOVERED | e;
5488 insn_state[w] = DISCOVERED;
7df737e9 5489 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 5490 return -E2BIG;
7df737e9 5491 insn_stack[env->cfg.cur_stack++] = w;
475fb78f
AS
5492 return 1;
5493 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
d9762e84
MKL
5494 verbose_linfo(env, t, "%d: ", t);
5495 verbose_linfo(env, w, "%d: ", w);
61bd5218 5496 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
5497 return -EINVAL;
5498 } else if (insn_state[w] == EXPLORED) {
5499 /* forward- or cross-edge */
5500 insn_state[t] = DISCOVERED | e;
5501 } else {
61bd5218 5502 verbose(env, "insn state internal bug\n");
475fb78f
AS
5503 return -EFAULT;
5504 }
5505 return 0;
5506}
5507
5508/* non-recursive depth-first-search to detect loops in BPF program
5509 * loop == back-edge in directed graph
5510 */
58e2af8b 5511static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
5512{
5513 struct bpf_insn *insns = env->prog->insnsi;
5514 int insn_cnt = env->prog->len;
7df737e9 5515 int *insn_stack, *insn_state;
475fb78f
AS
5516 int ret = 0;
5517 int i, t;
5518
7df737e9 5519 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
5520 if (!insn_state)
5521 return -ENOMEM;
5522
7df737e9 5523 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 5524 if (!insn_stack) {
71dde681 5525 kvfree(insn_state);
475fb78f
AS
5526 return -ENOMEM;
5527 }
5528
5529 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
5530 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 5531 env->cfg.cur_stack = 1;
475fb78f
AS
5532
5533peek_stack:
7df737e9 5534 if (env->cfg.cur_stack == 0)
475fb78f 5535 goto check_state;
7df737e9 5536 t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 5537
092ed096
JW
5538 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
5539 BPF_CLASS(insns[t].code) == BPF_JMP32) {
475fb78f
AS
5540 u8 opcode = BPF_OP(insns[t].code);
5541
5542 if (opcode == BPF_EXIT) {
5543 goto mark_explored;
5544 } else if (opcode == BPF_CALL) {
5545 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5546 if (ret == 1)
5547 goto peek_stack;
5548 else if (ret < 0)
5549 goto err_free;
07016151 5550 if (t + 1 < insn_cnt)
5d839021 5551 init_explored_state(env, t + 1);
cc8b0b92 5552 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5d839021 5553 init_explored_state(env, t);
cc8b0b92
AS
5554 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
5555 if (ret == 1)
5556 goto peek_stack;
5557 else if (ret < 0)
5558 goto err_free;
5559 }
475fb78f
AS
5560 } else if (opcode == BPF_JA) {
5561 if (BPF_SRC(insns[t].code) != BPF_K) {
5562 ret = -EINVAL;
5563 goto err_free;
5564 }
5565 /* unconditional jump with single edge */
5566 ret = push_insn(t, t + insns[t].off + 1,
5567 FALLTHROUGH, env);
5568 if (ret == 1)
5569 goto peek_stack;
5570 else if (ret < 0)
5571 goto err_free;
f1bca824
AS
5572 /* tell verifier to check for equivalent states
5573 * after every call and jump
5574 */
c3de6317 5575 if (t + 1 < insn_cnt)
5d839021 5576 init_explored_state(env, t + 1);
475fb78f
AS
5577 } else {
5578 /* conditional jump with two edges */
5d839021 5579 init_explored_state(env, t);
475fb78f
AS
5580 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5581 if (ret == 1)
5582 goto peek_stack;
5583 else if (ret < 0)
5584 goto err_free;
5585
5586 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
5587 if (ret == 1)
5588 goto peek_stack;
5589 else if (ret < 0)
5590 goto err_free;
5591 }
5592 } else {
5593 /* all other non-branch instructions with single
5594 * fall-through edge
5595 */
5596 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5597 if (ret == 1)
5598 goto peek_stack;
5599 else if (ret < 0)
5600 goto err_free;
5601 }
5602
5603mark_explored:
5604 insn_state[t] = EXPLORED;
7df737e9 5605 if (env->cfg.cur_stack-- <= 0) {
61bd5218 5606 verbose(env, "pop stack internal bug\n");
475fb78f
AS
5607 ret = -EFAULT;
5608 goto err_free;
5609 }
5610 goto peek_stack;
5611
5612check_state:
5613 for (i = 0; i < insn_cnt; i++) {
5614 if (insn_state[i] != EXPLORED) {
61bd5218 5615 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
5616 ret = -EINVAL;
5617 goto err_free;
5618 }
5619 }
5620 ret = 0; /* cfg looks good */
5621
5622err_free:
71dde681
AS
5623 kvfree(insn_state);
5624 kvfree(insn_stack);
7df737e9 5625 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
5626 return ret;
5627}
5628
838e9690
YS
5629/* The minimum supported BTF func info size */
5630#define MIN_BPF_FUNCINFO_SIZE 8
5631#define MAX_FUNCINFO_REC_SIZE 252
5632
c454a46b
MKL
5633static int check_btf_func(struct bpf_verifier_env *env,
5634 const union bpf_attr *attr,
5635 union bpf_attr __user *uattr)
838e9690 5636{
d0b2818e 5637 u32 i, nfuncs, urec_size, min_size;
838e9690 5638 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 5639 struct bpf_func_info *krecord;
838e9690 5640 const struct btf_type *type;
c454a46b
MKL
5641 struct bpf_prog *prog;
5642 const struct btf *btf;
838e9690 5643 void __user *urecord;
d0b2818e 5644 u32 prev_offset = 0;
838e9690
YS
5645 int ret = 0;
5646
5647 nfuncs = attr->func_info_cnt;
5648 if (!nfuncs)
5649 return 0;
5650
5651 if (nfuncs != env->subprog_cnt) {
5652 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
5653 return -EINVAL;
5654 }
5655
5656 urec_size = attr->func_info_rec_size;
5657 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
5658 urec_size > MAX_FUNCINFO_REC_SIZE ||
5659 urec_size % sizeof(u32)) {
5660 verbose(env, "invalid func info rec size %u\n", urec_size);
5661 return -EINVAL;
5662 }
5663
c454a46b
MKL
5664 prog = env->prog;
5665 btf = prog->aux->btf;
838e9690
YS
5666
5667 urecord = u64_to_user_ptr(attr->func_info);
5668 min_size = min_t(u32, krec_size, urec_size);
5669
ba64e7d8 5670 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
5671 if (!krecord)
5672 return -ENOMEM;
ba64e7d8 5673
838e9690
YS
5674 for (i = 0; i < nfuncs; i++) {
5675 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
5676 if (ret) {
5677 if (ret == -E2BIG) {
5678 verbose(env, "nonzero tailing record in func info");
5679 /* set the size kernel expects so loader can zero
5680 * out the rest of the record.
5681 */
5682 if (put_user(min_size, &uattr->func_info_rec_size))
5683 ret = -EFAULT;
5684 }
c454a46b 5685 goto err_free;
838e9690
YS
5686 }
5687
ba64e7d8 5688 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 5689 ret = -EFAULT;
c454a46b 5690 goto err_free;
838e9690
YS
5691 }
5692
d30d42e0 5693 /* check insn_off */
838e9690 5694 if (i == 0) {
d30d42e0 5695 if (krecord[i].insn_off) {
838e9690 5696 verbose(env,
d30d42e0
MKL
5697 "nonzero insn_off %u for the first func info record",
5698 krecord[i].insn_off);
838e9690 5699 ret = -EINVAL;
c454a46b 5700 goto err_free;
838e9690 5701 }
d30d42e0 5702 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
5703 verbose(env,
5704 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 5705 krecord[i].insn_off, prev_offset);
838e9690 5706 ret = -EINVAL;
c454a46b 5707 goto err_free;
838e9690
YS
5708 }
5709
d30d42e0 5710 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690
YS
5711 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
5712 ret = -EINVAL;
c454a46b 5713 goto err_free;
838e9690
YS
5714 }
5715
5716 /* check type_id */
ba64e7d8 5717 type = btf_type_by_id(btf, krecord[i].type_id);
838e9690
YS
5718 if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) {
5719 verbose(env, "invalid type id %d in func info",
ba64e7d8 5720 krecord[i].type_id);
838e9690 5721 ret = -EINVAL;
c454a46b 5722 goto err_free;
838e9690
YS
5723 }
5724
d30d42e0 5725 prev_offset = krecord[i].insn_off;
838e9690
YS
5726 urecord += urec_size;
5727 }
5728
ba64e7d8
YS
5729 prog->aux->func_info = krecord;
5730 prog->aux->func_info_cnt = nfuncs;
838e9690
YS
5731 return 0;
5732
c454a46b 5733err_free:
ba64e7d8 5734 kvfree(krecord);
838e9690
YS
5735 return ret;
5736}
5737
ba64e7d8
YS
5738static void adjust_btf_func(struct bpf_verifier_env *env)
5739{
5740 int i;
5741
5742 if (!env->prog->aux->func_info)
5743 return;
5744
5745 for (i = 0; i < env->subprog_cnt; i++)
d30d42e0 5746 env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
5747}
5748
c454a46b
MKL
5749#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
5750 sizeof(((struct bpf_line_info *)(0))->line_col))
5751#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
5752
5753static int check_btf_line(struct bpf_verifier_env *env,
5754 const union bpf_attr *attr,
5755 union bpf_attr __user *uattr)
5756{
5757 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
5758 struct bpf_subprog_info *sub;
5759 struct bpf_line_info *linfo;
5760 struct bpf_prog *prog;
5761 const struct btf *btf;
5762 void __user *ulinfo;
5763 int err;
5764
5765 nr_linfo = attr->line_info_cnt;
5766 if (!nr_linfo)
5767 return 0;
5768
5769 rec_size = attr->line_info_rec_size;
5770 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
5771 rec_size > MAX_LINEINFO_REC_SIZE ||
5772 rec_size & (sizeof(u32) - 1))
5773 return -EINVAL;
5774
5775 /* Need to zero it in case the userspace may
5776 * pass in a smaller bpf_line_info object.
5777 */
5778 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
5779 GFP_KERNEL | __GFP_NOWARN);
5780 if (!linfo)
5781 return -ENOMEM;
5782
5783 prog = env->prog;
5784 btf = prog->aux->btf;
5785
5786 s = 0;
5787 sub = env->subprog_info;
5788 ulinfo = u64_to_user_ptr(attr->line_info);
5789 expected_size = sizeof(struct bpf_line_info);
5790 ncopy = min_t(u32, expected_size, rec_size);
5791 for (i = 0; i < nr_linfo; i++) {
5792 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
5793 if (err) {
5794 if (err == -E2BIG) {
5795 verbose(env, "nonzero tailing record in line_info");
5796 if (put_user(expected_size,
5797 &uattr->line_info_rec_size))
5798 err = -EFAULT;
5799 }
5800 goto err_free;
5801 }
5802
5803 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
5804 err = -EFAULT;
5805 goto err_free;
5806 }
5807
5808 /*
5809 * Check insn_off to ensure
5810 * 1) strictly increasing AND
5811 * 2) bounded by prog->len
5812 *
5813 * The linfo[0].insn_off == 0 check logically falls into
5814 * the later "missing bpf_line_info for func..." case
5815 * because the first linfo[0].insn_off must be the
5816 * first sub also and the first sub must have
5817 * subprog_info[0].start == 0.
5818 */
5819 if ((i && linfo[i].insn_off <= prev_offset) ||
5820 linfo[i].insn_off >= prog->len) {
5821 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
5822 i, linfo[i].insn_off, prev_offset,
5823 prog->len);
5824 err = -EINVAL;
5825 goto err_free;
5826 }
5827
fdbaa0be
MKL
5828 if (!prog->insnsi[linfo[i].insn_off].code) {
5829 verbose(env,
5830 "Invalid insn code at line_info[%u].insn_off\n",
5831 i);
5832 err = -EINVAL;
5833 goto err_free;
5834 }
5835
23127b33
MKL
5836 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
5837 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
5838 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
5839 err = -EINVAL;
5840 goto err_free;
5841 }
5842
5843 if (s != env->subprog_cnt) {
5844 if (linfo[i].insn_off == sub[s].start) {
5845 sub[s].linfo_idx = i;
5846 s++;
5847 } else if (sub[s].start < linfo[i].insn_off) {
5848 verbose(env, "missing bpf_line_info for func#%u\n", s);
5849 err = -EINVAL;
5850 goto err_free;
5851 }
5852 }
5853
5854 prev_offset = linfo[i].insn_off;
5855 ulinfo += rec_size;
5856 }
5857
5858 if (s != env->subprog_cnt) {
5859 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
5860 env->subprog_cnt - s, s);
5861 err = -EINVAL;
5862 goto err_free;
5863 }
5864
5865 prog->aux->linfo = linfo;
5866 prog->aux->nr_linfo = nr_linfo;
5867
5868 return 0;
5869
5870err_free:
5871 kvfree(linfo);
5872 return err;
5873}
5874
5875static int check_btf_info(struct bpf_verifier_env *env,
5876 const union bpf_attr *attr,
5877 union bpf_attr __user *uattr)
5878{
5879 struct btf *btf;
5880 int err;
5881
5882 if (!attr->func_info_cnt && !attr->line_info_cnt)
5883 return 0;
5884
5885 btf = btf_get_by_fd(attr->prog_btf_fd);
5886 if (IS_ERR(btf))
5887 return PTR_ERR(btf);
5888 env->prog->aux->btf = btf;
5889
5890 err = check_btf_func(env, attr, uattr);
5891 if (err)
5892 return err;
5893
5894 err = check_btf_line(env, attr, uattr);
5895 if (err)
5896 return err;
5897
5898 return 0;
ba64e7d8
YS
5899}
5900
f1174f77
EC
5901/* check %cur's range satisfies %old's */
5902static bool range_within(struct bpf_reg_state *old,
5903 struct bpf_reg_state *cur)
5904{
b03c9f9f
EC
5905 return old->umin_value <= cur->umin_value &&
5906 old->umax_value >= cur->umax_value &&
5907 old->smin_value <= cur->smin_value &&
5908 old->smax_value >= cur->smax_value;
f1174f77
EC
5909}
5910
5911/* Maximum number of register states that can exist at once */
5912#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
5913struct idpair {
5914 u32 old;
5915 u32 cur;
5916};
5917
5918/* If in the old state two registers had the same id, then they need to have
5919 * the same id in the new state as well. But that id could be different from
5920 * the old state, so we need to track the mapping from old to new ids.
5921 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
5922 * regs with old id 5 must also have new id 9 for the new state to be safe. But
5923 * regs with a different old id could still have new id 9, we don't care about
5924 * that.
5925 * So we look through our idmap to see if this old id has been seen before. If
5926 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 5927 */
f1174f77 5928static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 5929{
f1174f77 5930 unsigned int i;
969bf05e 5931
f1174f77
EC
5932 for (i = 0; i < ID_MAP_SIZE; i++) {
5933 if (!idmap[i].old) {
5934 /* Reached an empty slot; haven't seen this id before */
5935 idmap[i].old = old_id;
5936 idmap[i].cur = cur_id;
5937 return true;
5938 }
5939 if (idmap[i].old == old_id)
5940 return idmap[i].cur == cur_id;
5941 }
5942 /* We ran out of idmap slots, which should be impossible */
5943 WARN_ON_ONCE(1);
5944 return false;
5945}
5946
9242b5f5
AS
5947static void clean_func_state(struct bpf_verifier_env *env,
5948 struct bpf_func_state *st)
5949{
5950 enum bpf_reg_liveness live;
5951 int i, j;
5952
5953 for (i = 0; i < BPF_REG_FP; i++) {
5954 live = st->regs[i].live;
5955 /* liveness must not touch this register anymore */
5956 st->regs[i].live |= REG_LIVE_DONE;
5957 if (!(live & REG_LIVE_READ))
5958 /* since the register is unused, clear its state
5959 * to make further comparison simpler
5960 */
5961 __mark_reg_not_init(&st->regs[i]);
5962 }
5963
5964 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
5965 live = st->stack[i].spilled_ptr.live;
5966 /* liveness must not touch this stack slot anymore */
5967 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
5968 if (!(live & REG_LIVE_READ)) {
5969 __mark_reg_not_init(&st->stack[i].spilled_ptr);
5970 for (j = 0; j < BPF_REG_SIZE; j++)
5971 st->stack[i].slot_type[j] = STACK_INVALID;
5972 }
5973 }
5974}
5975
5976static void clean_verifier_state(struct bpf_verifier_env *env,
5977 struct bpf_verifier_state *st)
5978{
5979 int i;
5980
5981 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
5982 /* all regs in this state in all frames were already marked */
5983 return;
5984
5985 for (i = 0; i <= st->curframe; i++)
5986 clean_func_state(env, st->frame[i]);
5987}
5988
5989/* the parentage chains form a tree.
5990 * the verifier states are added to state lists at given insn and
5991 * pushed into state stack for future exploration.
5992 * when the verifier reaches bpf_exit insn some of the verifer states
5993 * stored in the state lists have their final liveness state already,
5994 * but a lot of states will get revised from liveness point of view when
5995 * the verifier explores other branches.
5996 * Example:
5997 * 1: r0 = 1
5998 * 2: if r1 == 100 goto pc+1
5999 * 3: r0 = 2
6000 * 4: exit
6001 * when the verifier reaches exit insn the register r0 in the state list of
6002 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
6003 * of insn 2 and goes exploring further. At the insn 4 it will walk the
6004 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
6005 *
6006 * Since the verifier pushes the branch states as it sees them while exploring
6007 * the program the condition of walking the branch instruction for the second
6008 * time means that all states below this branch were already explored and
6009 * their final liveness markes are already propagated.
6010 * Hence when the verifier completes the search of state list in is_state_visited()
6011 * we can call this clean_live_states() function to mark all liveness states
6012 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
6013 * will not be used.
6014 * This function also clears the registers and stack for states that !READ
6015 * to simplify state merging.
6016 *
6017 * Important note here that walking the same branch instruction in the callee
6018 * doesn't meant that the states are DONE. The verifier has to compare
6019 * the callsites
6020 */
6021static void clean_live_states(struct bpf_verifier_env *env, int insn,
6022 struct bpf_verifier_state *cur)
6023{
6024 struct bpf_verifier_state_list *sl;
6025 int i;
6026
5d839021 6027 sl = *explored_state(env, insn);
a8f500af 6028 while (sl) {
dc2a4ebc
AS
6029 if (sl->state.insn_idx != insn ||
6030 sl->state.curframe != cur->curframe)
9242b5f5
AS
6031 goto next;
6032 for (i = 0; i <= cur->curframe; i++)
6033 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
6034 goto next;
6035 clean_verifier_state(env, &sl->state);
6036next:
6037 sl = sl->next;
6038 }
6039}
6040
f1174f77 6041/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
6042static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
6043 struct idpair *idmap)
f1174f77 6044{
f4d7e40a
AS
6045 bool equal;
6046
dc503a8a
EC
6047 if (!(rold->live & REG_LIVE_READ))
6048 /* explored state didn't use this */
6049 return true;
6050
679c782d 6051 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
6052
6053 if (rold->type == PTR_TO_STACK)
6054 /* two stack pointers are equal only if they're pointing to
6055 * the same stack frame, since fp-8 in foo != fp-8 in bar
6056 */
6057 return equal && rold->frameno == rcur->frameno;
6058
6059 if (equal)
969bf05e
AS
6060 return true;
6061
f1174f77
EC
6062 if (rold->type == NOT_INIT)
6063 /* explored state can't have used this */
969bf05e 6064 return true;
f1174f77
EC
6065 if (rcur->type == NOT_INIT)
6066 return false;
6067 switch (rold->type) {
6068 case SCALAR_VALUE:
6069 if (rcur->type == SCALAR_VALUE) {
6070 /* new val must satisfy old val knowledge */
6071 return range_within(rold, rcur) &&
6072 tnum_in(rold->var_off, rcur->var_off);
6073 } else {
179d1c56
JH
6074 /* We're trying to use a pointer in place of a scalar.
6075 * Even if the scalar was unbounded, this could lead to
6076 * pointer leaks because scalars are allowed to leak
6077 * while pointers are not. We could make this safe in
6078 * special cases if root is calling us, but it's
6079 * probably not worth the hassle.
f1174f77 6080 */
179d1c56 6081 return false;
f1174f77
EC
6082 }
6083 case PTR_TO_MAP_VALUE:
1b688a19
EC
6084 /* If the new min/max/var_off satisfy the old ones and
6085 * everything else matches, we are OK.
d83525ca
AS
6086 * 'id' is not compared, since it's only used for maps with
6087 * bpf_spin_lock inside map element and in such cases if
6088 * the rest of the prog is valid for one map element then
6089 * it's valid for all map elements regardless of the key
6090 * used in bpf_map_lookup()
1b688a19
EC
6091 */
6092 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
6093 range_within(rold, rcur) &&
6094 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
6095 case PTR_TO_MAP_VALUE_OR_NULL:
6096 /* a PTR_TO_MAP_VALUE could be safe to use as a
6097 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
6098 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
6099 * checked, doing so could have affected others with the same
6100 * id, and we can't check for that because we lost the id when
6101 * we converted to a PTR_TO_MAP_VALUE.
6102 */
6103 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
6104 return false;
6105 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
6106 return false;
6107 /* Check our ids match any regs they're supposed to */
6108 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 6109 case PTR_TO_PACKET_META:
f1174f77 6110 case PTR_TO_PACKET:
de8f3a83 6111 if (rcur->type != rold->type)
f1174f77
EC
6112 return false;
6113 /* We must have at least as much range as the old ptr
6114 * did, so that any accesses which were safe before are
6115 * still safe. This is true even if old range < old off,
6116 * since someone could have accessed through (ptr - k), or
6117 * even done ptr -= k in a register, to get a safe access.
6118 */
6119 if (rold->range > rcur->range)
6120 return false;
6121 /* If the offsets don't match, we can't trust our alignment;
6122 * nor can we be sure that we won't fall out of range.
6123 */
6124 if (rold->off != rcur->off)
6125 return false;
6126 /* id relations must be preserved */
6127 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
6128 return false;
6129 /* new val must satisfy old val knowledge */
6130 return range_within(rold, rcur) &&
6131 tnum_in(rold->var_off, rcur->var_off);
6132 case PTR_TO_CTX:
6133 case CONST_PTR_TO_MAP:
f1174f77 6134 case PTR_TO_PACKET_END:
d58e468b 6135 case PTR_TO_FLOW_KEYS:
c64b7983
JS
6136 case PTR_TO_SOCKET:
6137 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6138 case PTR_TO_SOCK_COMMON:
6139 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6140 case PTR_TO_TCP_SOCK:
6141 case PTR_TO_TCP_SOCK_OR_NULL:
f1174f77
EC
6142 /* Only valid matches are exact, which memcmp() above
6143 * would have accepted
6144 */
6145 default:
6146 /* Don't know what's going on, just say it's not safe */
6147 return false;
6148 }
969bf05e 6149
f1174f77
EC
6150 /* Shouldn't get here; if we do, say it's not safe */
6151 WARN_ON_ONCE(1);
969bf05e
AS
6152 return false;
6153}
6154
f4d7e40a
AS
6155static bool stacksafe(struct bpf_func_state *old,
6156 struct bpf_func_state *cur,
638f5b90
AS
6157 struct idpair *idmap)
6158{
6159 int i, spi;
6160
638f5b90
AS
6161 /* walk slots of the explored stack and ignore any additional
6162 * slots in the current stack, since explored(safe) state
6163 * didn't use them
6164 */
6165 for (i = 0; i < old->allocated_stack; i++) {
6166 spi = i / BPF_REG_SIZE;
6167
b233920c
AS
6168 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
6169 i += BPF_REG_SIZE - 1;
cc2b14d5 6170 /* explored state didn't use this */
fd05e57b 6171 continue;
b233920c 6172 }
cc2b14d5 6173
638f5b90
AS
6174 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
6175 continue;
19e2dbb7
AS
6176
6177 /* explored stack has more populated slots than current stack
6178 * and these slots were used
6179 */
6180 if (i >= cur->allocated_stack)
6181 return false;
6182
cc2b14d5
AS
6183 /* if old state was safe with misc data in the stack
6184 * it will be safe with zero-initialized stack.
6185 * The opposite is not true
6186 */
6187 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
6188 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
6189 continue;
638f5b90
AS
6190 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
6191 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
6192 /* Ex: old explored (safe) state has STACK_SPILL in
6193 * this stack slot, but current has has STACK_MISC ->
6194 * this verifier states are not equivalent,
6195 * return false to continue verification of this path
6196 */
6197 return false;
6198 if (i % BPF_REG_SIZE)
6199 continue;
6200 if (old->stack[spi].slot_type[0] != STACK_SPILL)
6201 continue;
6202 if (!regsafe(&old->stack[spi].spilled_ptr,
6203 &cur->stack[spi].spilled_ptr,
6204 idmap))
6205 /* when explored and current stack slot are both storing
6206 * spilled registers, check that stored pointers types
6207 * are the same as well.
6208 * Ex: explored safe path could have stored
6209 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
6210 * but current path has stored:
6211 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
6212 * such verifier states are not equivalent.
6213 * return false to continue verification of this path
6214 */
6215 return false;
6216 }
6217 return true;
6218}
6219
fd978bf7
JS
6220static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
6221{
6222 if (old->acquired_refs != cur->acquired_refs)
6223 return false;
6224 return !memcmp(old->refs, cur->refs,
6225 sizeof(*old->refs) * old->acquired_refs);
6226}
6227
f1bca824
AS
6228/* compare two verifier states
6229 *
6230 * all states stored in state_list are known to be valid, since
6231 * verifier reached 'bpf_exit' instruction through them
6232 *
6233 * this function is called when verifier exploring different branches of
6234 * execution popped from the state stack. If it sees an old state that has
6235 * more strict register state and more strict stack state then this execution
6236 * branch doesn't need to be explored further, since verifier already
6237 * concluded that more strict state leads to valid finish.
6238 *
6239 * Therefore two states are equivalent if register state is more conservative
6240 * and explored stack state is more conservative than the current one.
6241 * Example:
6242 * explored current
6243 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
6244 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
6245 *
6246 * In other words if current stack state (one being explored) has more
6247 * valid slots than old one that already passed validation, it means
6248 * the verifier can stop exploring and conclude that current state is valid too
6249 *
6250 * Similarly with registers. If explored state has register type as invalid
6251 * whereas register type in current state is meaningful, it means that
6252 * the current state will reach 'bpf_exit' instruction safely
6253 */
f4d7e40a
AS
6254static bool func_states_equal(struct bpf_func_state *old,
6255 struct bpf_func_state *cur)
f1bca824 6256{
f1174f77
EC
6257 struct idpair *idmap;
6258 bool ret = false;
f1bca824
AS
6259 int i;
6260
f1174f77
EC
6261 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
6262 /* If we failed to allocate the idmap, just say it's not safe */
6263 if (!idmap)
1a0dc1ac 6264 return false;
f1174f77
EC
6265
6266 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 6267 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 6268 goto out_free;
f1bca824
AS
6269 }
6270
638f5b90
AS
6271 if (!stacksafe(old, cur, idmap))
6272 goto out_free;
fd978bf7
JS
6273
6274 if (!refsafe(old, cur))
6275 goto out_free;
f1174f77
EC
6276 ret = true;
6277out_free:
6278 kfree(idmap);
6279 return ret;
f1bca824
AS
6280}
6281
f4d7e40a
AS
6282static bool states_equal(struct bpf_verifier_env *env,
6283 struct bpf_verifier_state *old,
6284 struct bpf_verifier_state *cur)
6285{
6286 int i;
6287
6288 if (old->curframe != cur->curframe)
6289 return false;
6290
979d63d5
DB
6291 /* Verification state from speculative execution simulation
6292 * must never prune a non-speculative execution one.
6293 */
6294 if (old->speculative && !cur->speculative)
6295 return false;
6296
d83525ca
AS
6297 if (old->active_spin_lock != cur->active_spin_lock)
6298 return false;
6299
f4d7e40a
AS
6300 /* for states to be equal callsites have to be the same
6301 * and all frame states need to be equivalent
6302 */
6303 for (i = 0; i <= old->curframe; i++) {
6304 if (old->frame[i]->callsite != cur->frame[i]->callsite)
6305 return false;
6306 if (!func_states_equal(old->frame[i], cur->frame[i]))
6307 return false;
6308 }
6309 return true;
6310}
6311
55e7f3b5
JW
6312static int propagate_liveness_reg(struct bpf_verifier_env *env,
6313 struct bpf_reg_state *reg,
6314 struct bpf_reg_state *parent_reg)
6315{
6316 int err;
6317
6318 if (parent_reg->live & REG_LIVE_READ || !(reg->live & REG_LIVE_READ))
6319 return 0;
6320
6321 err = mark_reg_read(env, reg, parent_reg);
6322 if (err)
6323 return err;
6324
6325 return 0;
6326}
6327
8e9cd9ce 6328/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
6329 * straight-line code between a state and its parent. When we arrive at an
6330 * equivalent state (jump target or such) we didn't arrive by the straight-line
6331 * code, so read marks in the state must propagate to the parent regardless
6332 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 6333 * in mark_reg_read() is for.
8e9cd9ce 6334 */
f4d7e40a
AS
6335static int propagate_liveness(struct bpf_verifier_env *env,
6336 const struct bpf_verifier_state *vstate,
6337 struct bpf_verifier_state *vparent)
dc503a8a 6338{
3f8cafa4 6339 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 6340 struct bpf_func_state *state, *parent;
3f8cafa4 6341 int i, frame, err = 0;
dc503a8a 6342
f4d7e40a
AS
6343 if (vparent->curframe != vstate->curframe) {
6344 WARN(1, "propagate_live: parent frame %d current frame %d\n",
6345 vparent->curframe, vstate->curframe);
6346 return -EFAULT;
6347 }
dc503a8a
EC
6348 /* Propagate read liveness of registers... */
6349 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 6350 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
6351 parent = vparent->frame[frame];
6352 state = vstate->frame[frame];
6353 parent_reg = parent->regs;
6354 state_reg = state->regs;
83d16312
JK
6355 /* We don't need to worry about FP liveness, it's read-only */
6356 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
6357 err = propagate_liveness_reg(env, &state_reg[i],
6358 &parent_reg[i]);
3f8cafa4
JW
6359 if (err)
6360 return err;
dc503a8a 6361 }
f4d7e40a 6362
1b04aee7 6363 /* Propagate stack slots. */
f4d7e40a
AS
6364 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
6365 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
6366 parent_reg = &parent->stack[i].spilled_ptr;
6367 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
6368 err = propagate_liveness_reg(env, state_reg,
6369 parent_reg);
3f8cafa4
JW
6370 if (err)
6371 return err;
dc503a8a
EC
6372 }
6373 }
f4d7e40a 6374 return err;
dc503a8a
EC
6375}
6376
58e2af8b 6377static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 6378{
58e2af8b 6379 struct bpf_verifier_state_list *new_sl;
9f4686c4 6380 struct bpf_verifier_state_list *sl, **pprev;
679c782d 6381 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 6382 int i, j, err, states_cnt = 0;
f1bca824 6383
a8f500af 6384 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
6385 /* this 'insn_idx' instruction wasn't marked, so we will not
6386 * be doing state search here
6387 */
6388 return 0;
6389
a8f500af
AS
6390 pprev = explored_state(env, insn_idx);
6391 sl = *pprev;
6392
9242b5f5
AS
6393 clean_live_states(env, insn_idx, cur);
6394
a8f500af 6395 while (sl) {
dc2a4ebc
AS
6396 states_cnt++;
6397 if (sl->state.insn_idx != insn_idx)
6398 goto next;
638f5b90 6399 if (states_equal(env, &sl->state, cur)) {
9f4686c4 6400 sl->hit_cnt++;
f1bca824 6401 /* reached equivalent register/stack state,
dc503a8a
EC
6402 * prune the search.
6403 * Registers read by the continuation are read by us.
8e9cd9ce
EC
6404 * If we have any write marks in env->cur_state, they
6405 * will prevent corresponding reads in the continuation
6406 * from reaching our parent (an explored_state). Our
6407 * own state will get the read marks recorded, but
6408 * they'll be immediately forgotten as we're pruning
6409 * this state and will pop a new one.
f1bca824 6410 */
f4d7e40a
AS
6411 err = propagate_liveness(env, &sl->state, cur);
6412 if (err)
6413 return err;
f1bca824 6414 return 1;
dc503a8a 6415 }
9f4686c4
AS
6416 sl->miss_cnt++;
6417 /* heuristic to determine whether this state is beneficial
6418 * to keep checking from state equivalence point of view.
6419 * Higher numbers increase max_states_per_insn and verification time,
6420 * but do not meaningfully decrease insn_processed.
6421 */
6422 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
6423 /* the state is unlikely to be useful. Remove it to
6424 * speed up verification
6425 */
6426 *pprev = sl->next;
6427 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
6428 free_verifier_state(&sl->state, false);
6429 kfree(sl);
6430 env->peak_states--;
6431 } else {
6432 /* cannot free this state, since parentage chain may
6433 * walk it later. Add it for free_list instead to
6434 * be freed at the end of verification
6435 */
6436 sl->next = env->free_list;
6437 env->free_list = sl;
6438 }
6439 sl = *pprev;
6440 continue;
6441 }
dc2a4ebc 6442next:
9f4686c4
AS
6443 pprev = &sl->next;
6444 sl = *pprev;
f1bca824
AS
6445 }
6446
06ee7115
AS
6447 if (env->max_states_per_insn < states_cnt)
6448 env->max_states_per_insn = states_cnt;
6449
ceefbc96
AS
6450 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
6451 return 0;
6452
f1bca824
AS
6453 /* there were no equivalent states, remember current one.
6454 * technically the current state is not proven to be safe yet,
f4d7e40a
AS
6455 * but it will either reach outer most bpf_exit (which means it's safe)
6456 * or it will be rejected. Since there are no loops, we won't be
6457 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
6458 * again on the way to bpf_exit
f1bca824 6459 */
638f5b90 6460 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
6461 if (!new_sl)
6462 return -ENOMEM;
06ee7115
AS
6463 env->total_states++;
6464 env->peak_states++;
f1bca824
AS
6465
6466 /* add new state to the head of linked list */
679c782d
EC
6467 new = &new_sl->state;
6468 err = copy_verifier_state(new, cur);
1969db47 6469 if (err) {
679c782d 6470 free_verifier_state(new, false);
1969db47
AS
6471 kfree(new_sl);
6472 return err;
6473 }
dc2a4ebc 6474 new->insn_idx = insn_idx;
5d839021
AS
6475 new_sl->next = *explored_state(env, insn_idx);
6476 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
6477 /* connect new state to parentage chain. Current frame needs all
6478 * registers connected. Only r6 - r9 of the callers are alive (pushed
6479 * to the stack implicitly by JITs) so in callers' frames connect just
6480 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
6481 * the state of the call instruction (with WRITTEN set), and r0 comes
6482 * from callee with its full parentage chain, anyway.
6483 */
6484 for (j = 0; j <= cur->curframe; j++)
6485 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
6486 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
8e9cd9ce
EC
6487 /* clear write marks in current state: the writes we did are not writes
6488 * our child did, so they don't screen off its reads from us.
6489 * (There are no read marks in current state, because reads always mark
6490 * their parent and current state never has children yet. Only
6491 * explored_states can get read marks.)
6492 */
dc503a8a 6493 for (i = 0; i < BPF_REG_FP; i++)
f4d7e40a
AS
6494 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
6495
6496 /* all stack frames are accessible from callee, clear them all */
6497 for (j = 0; j <= cur->curframe; j++) {
6498 struct bpf_func_state *frame = cur->frame[j];
679c782d 6499 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 6500
679c782d 6501 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 6502 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
6503 frame->stack[i].spilled_ptr.parent =
6504 &newframe->stack[i].spilled_ptr;
6505 }
f4d7e40a 6506 }
f1bca824
AS
6507 return 0;
6508}
6509
c64b7983
JS
6510/* Return true if it's OK to have the same insn return a different type. */
6511static bool reg_type_mismatch_ok(enum bpf_reg_type type)
6512{
6513 switch (type) {
6514 case PTR_TO_CTX:
6515 case PTR_TO_SOCKET:
6516 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6517 case PTR_TO_SOCK_COMMON:
6518 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6519 case PTR_TO_TCP_SOCK:
6520 case PTR_TO_TCP_SOCK_OR_NULL:
c64b7983
JS
6521 return false;
6522 default:
6523 return true;
6524 }
6525}
6526
6527/* If an instruction was previously used with particular pointer types, then we
6528 * need to be careful to avoid cases such as the below, where it may be ok
6529 * for one branch accessing the pointer, but not ok for the other branch:
6530 *
6531 * R1 = sock_ptr
6532 * goto X;
6533 * ...
6534 * R1 = some_other_valid_ptr;
6535 * goto X;
6536 * ...
6537 * R2 = *(u32 *)(R1 + 0);
6538 */
6539static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
6540{
6541 return src != prev && (!reg_type_mismatch_ok(src) ||
6542 !reg_type_mismatch_ok(prev));
6543}
6544
58e2af8b 6545static int do_check(struct bpf_verifier_env *env)
17a52670 6546{
638f5b90 6547 struct bpf_verifier_state *state;
17a52670 6548 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 6549 struct bpf_reg_state *regs;
06ee7115 6550 int insn_cnt = env->prog->len;
17a52670
AS
6551 bool do_print_state = false;
6552
d9762e84
MKL
6553 env->prev_linfo = NULL;
6554
638f5b90
AS
6555 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
6556 if (!state)
6557 return -ENOMEM;
f4d7e40a 6558 state->curframe = 0;
979d63d5 6559 state->speculative = false;
f4d7e40a
AS
6560 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
6561 if (!state->frame[0]) {
6562 kfree(state);
6563 return -ENOMEM;
6564 }
6565 env->cur_state = state;
6566 init_func_state(env, state->frame[0],
6567 BPF_MAIN_FUNC /* callsite */,
6568 0 /* frameno */,
6569 0 /* subprogno, zero == main subprog */);
c08435ec 6570
17a52670
AS
6571 for (;;) {
6572 struct bpf_insn *insn;
6573 u8 class;
6574 int err;
6575
c08435ec 6576 if (env->insn_idx >= insn_cnt) {
61bd5218 6577 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 6578 env->insn_idx, insn_cnt);
17a52670
AS
6579 return -EFAULT;
6580 }
6581
c08435ec 6582 insn = &insns[env->insn_idx];
17a52670
AS
6583 class = BPF_CLASS(insn->code);
6584
06ee7115 6585 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
6586 verbose(env,
6587 "BPF program is too large. Processed %d insn\n",
06ee7115 6588 env->insn_processed);
17a52670
AS
6589 return -E2BIG;
6590 }
6591
c08435ec 6592 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
6593 if (err < 0)
6594 return err;
6595 if (err == 1) {
6596 /* found equivalent state, can prune the search */
06ee7115 6597 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 6598 if (do_print_state)
979d63d5
DB
6599 verbose(env, "\nfrom %d to %d%s: safe\n",
6600 env->prev_insn_idx, env->insn_idx,
6601 env->cur_state->speculative ?
6602 " (speculative execution)" : "");
f1bca824 6603 else
c08435ec 6604 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
6605 }
6606 goto process_bpf_exit;
6607 }
6608
c3494801
AS
6609 if (signal_pending(current))
6610 return -EAGAIN;
6611
3c2ce60b
DB
6612 if (need_resched())
6613 cond_resched();
6614
06ee7115
AS
6615 if (env->log.level & BPF_LOG_LEVEL2 ||
6616 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
6617 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 6618 verbose(env, "%d:", env->insn_idx);
c5fc9692 6619 else
979d63d5
DB
6620 verbose(env, "\nfrom %d to %d%s:",
6621 env->prev_insn_idx, env->insn_idx,
6622 env->cur_state->speculative ?
6623 " (speculative execution)" : "");
f4d7e40a 6624 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
6625 do_print_state = false;
6626 }
6627
06ee7115 6628 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
6629 const struct bpf_insn_cbs cbs = {
6630 .cb_print = verbose,
abe08840 6631 .private_data = env,
7105e828
DB
6632 };
6633
c08435ec
DB
6634 verbose_linfo(env, env->insn_idx, "; ");
6635 verbose(env, "%d: ", env->insn_idx);
abe08840 6636 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
6637 }
6638
cae1927c 6639 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
6640 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
6641 env->prev_insn_idx);
cae1927c
JK
6642 if (err)
6643 return err;
6644 }
13a27dfc 6645
638f5b90 6646 regs = cur_regs(env);
c08435ec 6647 env->insn_aux_data[env->insn_idx].seen = true;
fd978bf7 6648
17a52670 6649 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 6650 err = check_alu_op(env, insn);
17a52670
AS
6651 if (err)
6652 return err;
6653
6654 } else if (class == BPF_LDX) {
3df126f3 6655 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
6656
6657 /* check for reserved fields is already done */
6658
17a52670 6659 /* check src operand */
dc503a8a 6660 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6661 if (err)
6662 return err;
6663
dc503a8a 6664 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
6665 if (err)
6666 return err;
6667
725f9dcd
AS
6668 src_reg_type = regs[insn->src_reg].type;
6669
17a52670
AS
6670 /* check that memory (src_reg + off) is readable,
6671 * the state of dst_reg will be updated by this func
6672 */
c08435ec
DB
6673 err = check_mem_access(env, env->insn_idx, insn->src_reg,
6674 insn->off, BPF_SIZE(insn->code),
6675 BPF_READ, insn->dst_reg, false);
17a52670
AS
6676 if (err)
6677 return err;
6678
c08435ec 6679 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
6680
6681 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
6682 /* saw a valid insn
6683 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 6684 * save type to validate intersecting paths
9bac3d6d 6685 */
3df126f3 6686 *prev_src_type = src_reg_type;
9bac3d6d 6687
c64b7983 6688 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
6689 /* ABuser program is trying to use the same insn
6690 * dst_reg = *(u32*) (src_reg + off)
6691 * with different pointer types:
6692 * src_reg == ctx in one branch and
6693 * src_reg == stack|map in some other branch.
6694 * Reject it.
6695 */
61bd5218 6696 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
6697 return -EINVAL;
6698 }
6699
17a52670 6700 } else if (class == BPF_STX) {
3df126f3 6701 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 6702
17a52670 6703 if (BPF_MODE(insn->code) == BPF_XADD) {
c08435ec 6704 err = check_xadd(env, env->insn_idx, insn);
17a52670
AS
6705 if (err)
6706 return err;
c08435ec 6707 env->insn_idx++;
17a52670
AS
6708 continue;
6709 }
6710
17a52670 6711 /* check src1 operand */
dc503a8a 6712 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6713 if (err)
6714 return err;
6715 /* check src2 operand */
dc503a8a 6716 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6717 if (err)
6718 return err;
6719
d691f9e8
AS
6720 dst_reg_type = regs[insn->dst_reg].type;
6721
17a52670 6722 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
6723 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
6724 insn->off, BPF_SIZE(insn->code),
6725 BPF_WRITE, insn->src_reg, false);
17a52670
AS
6726 if (err)
6727 return err;
6728
c08435ec 6729 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
6730
6731 if (*prev_dst_type == NOT_INIT) {
6732 *prev_dst_type = dst_reg_type;
c64b7983 6733 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 6734 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
6735 return -EINVAL;
6736 }
6737
17a52670
AS
6738 } else if (class == BPF_ST) {
6739 if (BPF_MODE(insn->code) != BPF_MEM ||
6740 insn->src_reg != BPF_REG_0) {
61bd5218 6741 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
6742 return -EINVAL;
6743 }
6744 /* check src operand */
dc503a8a 6745 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6746 if (err)
6747 return err;
6748
f37a8cb8 6749 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 6750 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
6751 insn->dst_reg,
6752 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
6753 return -EACCES;
6754 }
6755
17a52670 6756 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
6757 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
6758 insn->off, BPF_SIZE(insn->code),
6759 BPF_WRITE, -1, false);
17a52670
AS
6760 if (err)
6761 return err;
6762
092ed096 6763 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
6764 u8 opcode = BPF_OP(insn->code);
6765
6766 if (opcode == BPF_CALL) {
6767 if (BPF_SRC(insn->code) != BPF_K ||
6768 insn->off != 0 ||
f4d7e40a
AS
6769 (insn->src_reg != BPF_REG_0 &&
6770 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
6771 insn->dst_reg != BPF_REG_0 ||
6772 class == BPF_JMP32) {
61bd5218 6773 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
6774 return -EINVAL;
6775 }
6776
d83525ca
AS
6777 if (env->cur_state->active_spin_lock &&
6778 (insn->src_reg == BPF_PSEUDO_CALL ||
6779 insn->imm != BPF_FUNC_spin_unlock)) {
6780 verbose(env, "function calls are not allowed while holding a lock\n");
6781 return -EINVAL;
6782 }
f4d7e40a 6783 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 6784 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 6785 else
c08435ec 6786 err = check_helper_call(env, insn->imm, env->insn_idx);
17a52670
AS
6787 if (err)
6788 return err;
6789
6790 } else if (opcode == BPF_JA) {
6791 if (BPF_SRC(insn->code) != BPF_K ||
6792 insn->imm != 0 ||
6793 insn->src_reg != BPF_REG_0 ||
092ed096
JW
6794 insn->dst_reg != BPF_REG_0 ||
6795 class == BPF_JMP32) {
61bd5218 6796 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
6797 return -EINVAL;
6798 }
6799
c08435ec 6800 env->insn_idx += insn->off + 1;
17a52670
AS
6801 continue;
6802
6803 } else if (opcode == BPF_EXIT) {
6804 if (BPF_SRC(insn->code) != BPF_K ||
6805 insn->imm != 0 ||
6806 insn->src_reg != BPF_REG_0 ||
092ed096
JW
6807 insn->dst_reg != BPF_REG_0 ||
6808 class == BPF_JMP32) {
61bd5218 6809 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
6810 return -EINVAL;
6811 }
6812
d83525ca
AS
6813 if (env->cur_state->active_spin_lock) {
6814 verbose(env, "bpf_spin_unlock is missing\n");
6815 return -EINVAL;
6816 }
6817
f4d7e40a
AS
6818 if (state->curframe) {
6819 /* exit from nested function */
c08435ec
DB
6820 env->prev_insn_idx = env->insn_idx;
6821 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
6822 if (err)
6823 return err;
6824 do_print_state = true;
6825 continue;
6826 }
6827
fd978bf7
JS
6828 err = check_reference_leak(env);
6829 if (err)
6830 return err;
6831
17a52670
AS
6832 /* eBPF calling convetion is such that R0 is used
6833 * to return the value from eBPF program.
6834 * Make sure that it's readable at this time
6835 * of bpf_exit, which means that program wrote
6836 * something into it earlier
6837 */
dc503a8a 6838 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
17a52670
AS
6839 if (err)
6840 return err;
6841
1be7f75d 6842 if (is_pointer_value(env, BPF_REG_0)) {
61bd5218 6843 verbose(env, "R0 leaks addr as return value\n");
1be7f75d
AS
6844 return -EACCES;
6845 }
6846
390ee7e2
AS
6847 err = check_return_code(env);
6848 if (err)
6849 return err;
f1bca824 6850process_bpf_exit:
c08435ec
DB
6851 err = pop_stack(env, &env->prev_insn_idx,
6852 &env->insn_idx);
638f5b90
AS
6853 if (err < 0) {
6854 if (err != -ENOENT)
6855 return err;
17a52670
AS
6856 break;
6857 } else {
6858 do_print_state = true;
6859 continue;
6860 }
6861 } else {
c08435ec 6862 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
6863 if (err)
6864 return err;
6865 }
6866 } else if (class == BPF_LD) {
6867 u8 mode = BPF_MODE(insn->code);
6868
6869 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
6870 err = check_ld_abs(env, insn);
6871 if (err)
6872 return err;
6873
17a52670
AS
6874 } else if (mode == BPF_IMM) {
6875 err = check_ld_imm(env, insn);
6876 if (err)
6877 return err;
6878
c08435ec
DB
6879 env->insn_idx++;
6880 env->insn_aux_data[env->insn_idx].seen = true;
17a52670 6881 } else {
61bd5218 6882 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
6883 return -EINVAL;
6884 }
6885 } else {
61bd5218 6886 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
6887 return -EINVAL;
6888 }
6889
c08435ec 6890 env->insn_idx++;
17a52670
AS
6891 }
6892
9c8105bd 6893 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17a52670
AS
6894 return 0;
6895}
6896
56f668df
MKL
6897static int check_map_prealloc(struct bpf_map *map)
6898{
6899 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
6900 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6901 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
6902 !(map->map_flags & BPF_F_NO_PREALLOC);
6903}
6904
d83525ca
AS
6905static bool is_tracing_prog_type(enum bpf_prog_type type)
6906{
6907 switch (type) {
6908 case BPF_PROG_TYPE_KPROBE:
6909 case BPF_PROG_TYPE_TRACEPOINT:
6910 case BPF_PROG_TYPE_PERF_EVENT:
6911 case BPF_PROG_TYPE_RAW_TRACEPOINT:
6912 return true;
6913 default:
6914 return false;
6915 }
6916}
6917
61bd5218
JK
6918static int check_map_prog_compatibility(struct bpf_verifier_env *env,
6919 struct bpf_map *map,
fdc15d38
AS
6920 struct bpf_prog *prog)
6921
6922{
56f668df
MKL
6923 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
6924 * preallocated hash maps, since doing memory allocation
6925 * in overflow_handler can crash depending on where nmi got
6926 * triggered.
6927 */
6928 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
6929 if (!check_map_prealloc(map)) {
61bd5218 6930 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
6931 return -EINVAL;
6932 }
6933 if (map->inner_map_meta &&
6934 !check_map_prealloc(map->inner_map_meta)) {
61bd5218 6935 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
56f668df
MKL
6936 return -EINVAL;
6937 }
fdc15d38 6938 }
a3884572 6939
d83525ca
AS
6940 if ((is_tracing_prog_type(prog->type) ||
6941 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
6942 map_value_has_spin_lock(map)) {
6943 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
6944 return -EINVAL;
6945 }
6946
a3884572 6947 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 6948 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
6949 verbose(env, "offload device mismatch between prog and map\n");
6950 return -EINVAL;
6951 }
6952
fdc15d38
AS
6953 return 0;
6954}
6955
b741f163
RG
6956static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
6957{
6958 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
6959 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
6960}
6961
0246e64d
AS
6962/* look for pseudo eBPF instructions that access map FDs and
6963 * replace them with actual map pointers
6964 */
58e2af8b 6965static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
6966{
6967 struct bpf_insn *insn = env->prog->insnsi;
6968 int insn_cnt = env->prog->len;
fdc15d38 6969 int i, j, err;
0246e64d 6970
f1f7714e 6971 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
6972 if (err)
6973 return err;
6974
0246e64d 6975 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 6976 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 6977 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 6978 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
6979 return -EINVAL;
6980 }
6981
d691f9e8
AS
6982 if (BPF_CLASS(insn->code) == BPF_STX &&
6983 ((BPF_MODE(insn->code) != BPF_MEM &&
6984 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 6985 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
6986 return -EINVAL;
6987 }
6988
0246e64d 6989 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 6990 struct bpf_insn_aux_data *aux;
0246e64d
AS
6991 struct bpf_map *map;
6992 struct fd f;
d8eca5bb 6993 u64 addr;
0246e64d
AS
6994
6995 if (i == insn_cnt - 1 || insn[1].code != 0 ||
6996 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
6997 insn[1].off != 0) {
61bd5218 6998 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
6999 return -EINVAL;
7000 }
7001
d8eca5bb 7002 if (insn[0].src_reg == 0)
0246e64d
AS
7003 /* valid generic load 64-bit imm */
7004 goto next_insn;
7005
d8eca5bb
DB
7006 /* In final convert_pseudo_ld_imm64() step, this is
7007 * converted into regular 64-bit imm load insn.
7008 */
7009 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
7010 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
7011 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
7012 insn[1].imm != 0)) {
7013 verbose(env,
7014 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
7015 return -EINVAL;
7016 }
7017
20182390 7018 f = fdget(insn[0].imm);
c2101297 7019 map = __bpf_map_get(f);
0246e64d 7020 if (IS_ERR(map)) {
61bd5218 7021 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 7022 insn[0].imm);
0246e64d
AS
7023 return PTR_ERR(map);
7024 }
7025
61bd5218 7026 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
7027 if (err) {
7028 fdput(f);
7029 return err;
7030 }
7031
d8eca5bb
DB
7032 aux = &env->insn_aux_data[i];
7033 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7034 addr = (unsigned long)map;
7035 } else {
7036 u32 off = insn[1].imm;
7037
7038 if (off >= BPF_MAX_VAR_OFF) {
7039 verbose(env, "direct value offset of %u is not allowed\n", off);
7040 fdput(f);
7041 return -EINVAL;
7042 }
7043
7044 if (!map->ops->map_direct_value_addr) {
7045 verbose(env, "no direct value access support for this map type\n");
7046 fdput(f);
7047 return -EINVAL;
7048 }
7049
7050 err = map->ops->map_direct_value_addr(map, &addr, off);
7051 if (err) {
7052 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
7053 map->value_size, off);
7054 fdput(f);
7055 return err;
7056 }
7057
7058 aux->map_off = off;
7059 addr += off;
7060 }
7061
7062 insn[0].imm = (u32)addr;
7063 insn[1].imm = addr >> 32;
0246e64d
AS
7064
7065 /* check whether we recorded this map already */
d8eca5bb 7066 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 7067 if (env->used_maps[j] == map) {
d8eca5bb 7068 aux->map_index = j;
0246e64d
AS
7069 fdput(f);
7070 goto next_insn;
7071 }
d8eca5bb 7072 }
0246e64d
AS
7073
7074 if (env->used_map_cnt >= MAX_USED_MAPS) {
7075 fdput(f);
7076 return -E2BIG;
7077 }
7078
0246e64d
AS
7079 /* hold the map. If the program is rejected by verifier,
7080 * the map will be released by release_maps() or it
7081 * will be used by the valid program until it's unloaded
ab7f5bf0 7082 * and all maps are released in free_used_maps()
0246e64d 7083 */
92117d84
AS
7084 map = bpf_map_inc(map, false);
7085 if (IS_ERR(map)) {
7086 fdput(f);
7087 return PTR_ERR(map);
7088 }
d8eca5bb
DB
7089
7090 aux->map_index = env->used_map_cnt;
92117d84
AS
7091 env->used_maps[env->used_map_cnt++] = map;
7092
b741f163 7093 if (bpf_map_is_cgroup_storage(map) &&
de9cbbaa 7094 bpf_cgroup_storage_assign(env->prog, map)) {
b741f163 7095 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
7096 fdput(f);
7097 return -EBUSY;
7098 }
7099
0246e64d
AS
7100 fdput(f);
7101next_insn:
7102 insn++;
7103 i++;
5e581dad
DB
7104 continue;
7105 }
7106
7107 /* Basic sanity check before we invest more work here. */
7108 if (!bpf_opcode_in_insntable(insn->code)) {
7109 verbose(env, "unknown opcode %02x\n", insn->code);
7110 return -EINVAL;
0246e64d
AS
7111 }
7112 }
7113
7114 /* now all pseudo BPF_LD_IMM64 instructions load valid
7115 * 'struct bpf_map *' into a register instead of user map_fd.
7116 * These pointers will be used later by verifier to validate map access.
7117 */
7118 return 0;
7119}
7120
7121/* drop refcnt of maps used by the rejected program */
58e2af8b 7122static void release_maps(struct bpf_verifier_env *env)
0246e64d 7123{
8bad74f9 7124 enum bpf_cgroup_storage_type stype;
0246e64d
AS
7125 int i;
7126
8bad74f9
RG
7127 for_each_cgroup_storage_type(stype) {
7128 if (!env->prog->aux->cgroup_storage[stype])
7129 continue;
de9cbbaa 7130 bpf_cgroup_storage_release(env->prog,
8bad74f9
RG
7131 env->prog->aux->cgroup_storage[stype]);
7132 }
de9cbbaa 7133
0246e64d
AS
7134 for (i = 0; i < env->used_map_cnt; i++)
7135 bpf_map_put(env->used_maps[i]);
7136}
7137
7138/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 7139static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
7140{
7141 struct bpf_insn *insn = env->prog->insnsi;
7142 int insn_cnt = env->prog->len;
7143 int i;
7144
7145 for (i = 0; i < insn_cnt; i++, insn++)
7146 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
7147 insn->src_reg = 0;
7148}
7149
8041902d
AS
7150/* single env->prog->insni[off] instruction was replaced with the range
7151 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
7152 * [0, off) and [off, end) to new locations, so the patched range stays zero
7153 */
7154static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
7155 u32 off, u32 cnt)
7156{
7157 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
c131187d 7158 int i;
8041902d
AS
7159
7160 if (cnt == 1)
7161 return 0;
fad953ce
KC
7162 new_data = vzalloc(array_size(prog_len,
7163 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
7164 if (!new_data)
7165 return -ENOMEM;
7166 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
7167 memcpy(new_data + off + cnt - 1, old_data + off,
7168 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
c131187d
AS
7169 for (i = off; i < off + cnt - 1; i++)
7170 new_data[i].seen = true;
8041902d
AS
7171 env->insn_aux_data = new_data;
7172 vfree(old_data);
7173 return 0;
7174}
7175
cc8b0b92
AS
7176static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
7177{
7178 int i;
7179
7180 if (len == 1)
7181 return;
4cb3d99c
JW
7182 /* NOTE: fake 'exit' subprog should be updated as well. */
7183 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 7184 if (env->subprog_info[i].start <= off)
cc8b0b92 7185 continue;
9c8105bd 7186 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
7187 }
7188}
7189
8041902d
AS
7190static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
7191 const struct bpf_insn *patch, u32 len)
7192{
7193 struct bpf_prog *new_prog;
7194
7195 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
7196 if (IS_ERR(new_prog)) {
7197 if (PTR_ERR(new_prog) == -ERANGE)
7198 verbose(env,
7199 "insn %d cannot be patched due to 16-bit range\n",
7200 env->insn_aux_data[off].orig_idx);
8041902d 7201 return NULL;
4f73379e 7202 }
8041902d
AS
7203 if (adjust_insn_aux_data(env, new_prog->len, off, len))
7204 return NULL;
cc8b0b92 7205 adjust_subprog_starts(env, off, len);
8041902d
AS
7206 return new_prog;
7207}
7208
52875a04
JK
7209static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
7210 u32 off, u32 cnt)
7211{
7212 int i, j;
7213
7214 /* find first prog starting at or after off (first to remove) */
7215 for (i = 0; i < env->subprog_cnt; i++)
7216 if (env->subprog_info[i].start >= off)
7217 break;
7218 /* find first prog starting at or after off + cnt (first to stay) */
7219 for (j = i; j < env->subprog_cnt; j++)
7220 if (env->subprog_info[j].start >= off + cnt)
7221 break;
7222 /* if j doesn't start exactly at off + cnt, we are just removing
7223 * the front of previous prog
7224 */
7225 if (env->subprog_info[j].start != off + cnt)
7226 j--;
7227
7228 if (j > i) {
7229 struct bpf_prog_aux *aux = env->prog->aux;
7230 int move;
7231
7232 /* move fake 'exit' subprog as well */
7233 move = env->subprog_cnt + 1 - j;
7234
7235 memmove(env->subprog_info + i,
7236 env->subprog_info + j,
7237 sizeof(*env->subprog_info) * move);
7238 env->subprog_cnt -= j - i;
7239
7240 /* remove func_info */
7241 if (aux->func_info) {
7242 move = aux->func_info_cnt - j;
7243
7244 memmove(aux->func_info + i,
7245 aux->func_info + j,
7246 sizeof(*aux->func_info) * move);
7247 aux->func_info_cnt -= j - i;
7248 /* func_info->insn_off is set after all code rewrites,
7249 * in adjust_btf_func() - no need to adjust
7250 */
7251 }
7252 } else {
7253 /* convert i from "first prog to remove" to "first to adjust" */
7254 if (env->subprog_info[i].start == off)
7255 i++;
7256 }
7257
7258 /* update fake 'exit' subprog as well */
7259 for (; i <= env->subprog_cnt; i++)
7260 env->subprog_info[i].start -= cnt;
7261
7262 return 0;
7263}
7264
7265static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
7266 u32 cnt)
7267{
7268 struct bpf_prog *prog = env->prog;
7269 u32 i, l_off, l_cnt, nr_linfo;
7270 struct bpf_line_info *linfo;
7271
7272 nr_linfo = prog->aux->nr_linfo;
7273 if (!nr_linfo)
7274 return 0;
7275
7276 linfo = prog->aux->linfo;
7277
7278 /* find first line info to remove, count lines to be removed */
7279 for (i = 0; i < nr_linfo; i++)
7280 if (linfo[i].insn_off >= off)
7281 break;
7282
7283 l_off = i;
7284 l_cnt = 0;
7285 for (; i < nr_linfo; i++)
7286 if (linfo[i].insn_off < off + cnt)
7287 l_cnt++;
7288 else
7289 break;
7290
7291 /* First live insn doesn't match first live linfo, it needs to "inherit"
7292 * last removed linfo. prog is already modified, so prog->len == off
7293 * means no live instructions after (tail of the program was removed).
7294 */
7295 if (prog->len != off && l_cnt &&
7296 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
7297 l_cnt--;
7298 linfo[--i].insn_off = off + cnt;
7299 }
7300
7301 /* remove the line info which refer to the removed instructions */
7302 if (l_cnt) {
7303 memmove(linfo + l_off, linfo + i,
7304 sizeof(*linfo) * (nr_linfo - i));
7305
7306 prog->aux->nr_linfo -= l_cnt;
7307 nr_linfo = prog->aux->nr_linfo;
7308 }
7309
7310 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
7311 for (i = l_off; i < nr_linfo; i++)
7312 linfo[i].insn_off -= cnt;
7313
7314 /* fix up all subprogs (incl. 'exit') which start >= off */
7315 for (i = 0; i <= env->subprog_cnt; i++)
7316 if (env->subprog_info[i].linfo_idx > l_off) {
7317 /* program may have started in the removed region but
7318 * may not be fully removed
7319 */
7320 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
7321 env->subprog_info[i].linfo_idx -= l_cnt;
7322 else
7323 env->subprog_info[i].linfo_idx = l_off;
7324 }
7325
7326 return 0;
7327}
7328
7329static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
7330{
7331 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7332 unsigned int orig_prog_len = env->prog->len;
7333 int err;
7334
08ca90af
JK
7335 if (bpf_prog_is_dev_bound(env->prog->aux))
7336 bpf_prog_offload_remove_insns(env, off, cnt);
7337
52875a04
JK
7338 err = bpf_remove_insns(env->prog, off, cnt);
7339 if (err)
7340 return err;
7341
7342 err = adjust_subprog_starts_after_remove(env, off, cnt);
7343 if (err)
7344 return err;
7345
7346 err = bpf_adj_linfo_after_remove(env, off, cnt);
7347 if (err)
7348 return err;
7349
7350 memmove(aux_data + off, aux_data + off + cnt,
7351 sizeof(*aux_data) * (orig_prog_len - off - cnt));
7352
7353 return 0;
7354}
7355
2a5418a1
DB
7356/* The verifier does more data flow analysis than llvm and will not
7357 * explore branches that are dead at run time. Malicious programs can
7358 * have dead code too. Therefore replace all dead at-run-time code
7359 * with 'ja -1'.
7360 *
7361 * Just nops are not optimal, e.g. if they would sit at the end of the
7362 * program and through another bug we would manage to jump there, then
7363 * we'd execute beyond program memory otherwise. Returning exception
7364 * code also wouldn't work since we can have subprogs where the dead
7365 * code could be located.
c131187d
AS
7366 */
7367static void sanitize_dead_code(struct bpf_verifier_env *env)
7368{
7369 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 7370 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
7371 struct bpf_insn *insn = env->prog->insnsi;
7372 const int insn_cnt = env->prog->len;
7373 int i;
7374
7375 for (i = 0; i < insn_cnt; i++) {
7376 if (aux_data[i].seen)
7377 continue;
2a5418a1 7378 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
7379 }
7380}
7381
e2ae4ca2
JK
7382static bool insn_is_cond_jump(u8 code)
7383{
7384 u8 op;
7385
092ed096
JW
7386 if (BPF_CLASS(code) == BPF_JMP32)
7387 return true;
7388
e2ae4ca2
JK
7389 if (BPF_CLASS(code) != BPF_JMP)
7390 return false;
7391
7392 op = BPF_OP(code);
7393 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
7394}
7395
7396static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
7397{
7398 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7399 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
7400 struct bpf_insn *insn = env->prog->insnsi;
7401 const int insn_cnt = env->prog->len;
7402 int i;
7403
7404 for (i = 0; i < insn_cnt; i++, insn++) {
7405 if (!insn_is_cond_jump(insn->code))
7406 continue;
7407
7408 if (!aux_data[i + 1].seen)
7409 ja.off = insn->off;
7410 else if (!aux_data[i + 1 + insn->off].seen)
7411 ja.off = 0;
7412 else
7413 continue;
7414
08ca90af
JK
7415 if (bpf_prog_is_dev_bound(env->prog->aux))
7416 bpf_prog_offload_replace_insn(env, i, &ja);
7417
e2ae4ca2
JK
7418 memcpy(insn, &ja, sizeof(ja));
7419 }
7420}
7421
52875a04
JK
7422static int opt_remove_dead_code(struct bpf_verifier_env *env)
7423{
7424 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7425 int insn_cnt = env->prog->len;
7426 int i, err;
7427
7428 for (i = 0; i < insn_cnt; i++) {
7429 int j;
7430
7431 j = 0;
7432 while (i + j < insn_cnt && !aux_data[i + j].seen)
7433 j++;
7434 if (!j)
7435 continue;
7436
7437 err = verifier_remove_insns(env, i, j);
7438 if (err)
7439 return err;
7440 insn_cnt = env->prog->len;
7441 }
7442
7443 return 0;
7444}
7445
a1b14abc
JK
7446static int opt_remove_nops(struct bpf_verifier_env *env)
7447{
7448 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
7449 struct bpf_insn *insn = env->prog->insnsi;
7450 int insn_cnt = env->prog->len;
7451 int i, err;
7452
7453 for (i = 0; i < insn_cnt; i++) {
7454 if (memcmp(&insn[i], &ja, sizeof(ja)))
7455 continue;
7456
7457 err = verifier_remove_insns(env, i, 1);
7458 if (err)
7459 return err;
7460 insn_cnt--;
7461 i--;
7462 }
7463
7464 return 0;
7465}
7466
c64b7983
JS
7467/* convert load instructions that access fields of a context type into a
7468 * sequence of instructions that access fields of the underlying structure:
7469 * struct __sk_buff -> struct sk_buff
7470 * struct bpf_sock_ops -> struct sock
9bac3d6d 7471 */
58e2af8b 7472static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 7473{
00176a34 7474 const struct bpf_verifier_ops *ops = env->ops;
f96da094 7475 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 7476 const int insn_cnt = env->prog->len;
36bbef52 7477 struct bpf_insn insn_buf[16], *insn;
46f53a65 7478 u32 target_size, size_default, off;
9bac3d6d 7479 struct bpf_prog *new_prog;
d691f9e8 7480 enum bpf_access_type type;
f96da094 7481 bool is_narrower_load;
9bac3d6d 7482
b09928b9
DB
7483 if (ops->gen_prologue || env->seen_direct_write) {
7484 if (!ops->gen_prologue) {
7485 verbose(env, "bpf verifier is misconfigured\n");
7486 return -EINVAL;
7487 }
36bbef52
DB
7488 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
7489 env->prog);
7490 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 7491 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
7492 return -EINVAL;
7493 } else if (cnt) {
8041902d 7494 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
7495 if (!new_prog)
7496 return -ENOMEM;
8041902d 7497
36bbef52 7498 env->prog = new_prog;
3df126f3 7499 delta += cnt - 1;
36bbef52
DB
7500 }
7501 }
7502
c64b7983 7503 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
7504 return 0;
7505
3df126f3 7506 insn = env->prog->insnsi + delta;
36bbef52 7507
9bac3d6d 7508 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
7509 bpf_convert_ctx_access_t convert_ctx_access;
7510
62c7989b
DB
7511 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
7512 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
7513 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 7514 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 7515 type = BPF_READ;
62c7989b
DB
7516 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
7517 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
7518 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 7519 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
7520 type = BPF_WRITE;
7521 else
9bac3d6d
AS
7522 continue;
7523
af86ca4e
AS
7524 if (type == BPF_WRITE &&
7525 env->insn_aux_data[i + delta].sanitize_stack_off) {
7526 struct bpf_insn patch[] = {
7527 /* Sanitize suspicious stack slot with zero.
7528 * There are no memory dependencies for this store,
7529 * since it's only using frame pointer and immediate
7530 * constant of zero
7531 */
7532 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
7533 env->insn_aux_data[i + delta].sanitize_stack_off,
7534 0),
7535 /* the original STX instruction will immediately
7536 * overwrite the same stack slot with appropriate value
7537 */
7538 *insn,
7539 };
7540
7541 cnt = ARRAY_SIZE(patch);
7542 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
7543 if (!new_prog)
7544 return -ENOMEM;
7545
7546 delta += cnt - 1;
7547 env->prog = new_prog;
7548 insn = new_prog->insnsi + i + delta;
7549 continue;
7550 }
7551
c64b7983
JS
7552 switch (env->insn_aux_data[i + delta].ptr_type) {
7553 case PTR_TO_CTX:
7554 if (!ops->convert_ctx_access)
7555 continue;
7556 convert_ctx_access = ops->convert_ctx_access;
7557 break;
7558 case PTR_TO_SOCKET:
46f8bc92 7559 case PTR_TO_SOCK_COMMON:
c64b7983
JS
7560 convert_ctx_access = bpf_sock_convert_ctx_access;
7561 break;
655a51e5
MKL
7562 case PTR_TO_TCP_SOCK:
7563 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
7564 break;
c64b7983 7565 default:
9bac3d6d 7566 continue;
c64b7983 7567 }
9bac3d6d 7568
31fd8581 7569 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 7570 size = BPF_LDST_BYTES(insn);
31fd8581
YS
7571
7572 /* If the read access is a narrower load of the field,
7573 * convert to a 4/8-byte load, to minimum program type specific
7574 * convert_ctx_access changes. If conversion is successful,
7575 * we will apply proper mask to the result.
7576 */
f96da094 7577 is_narrower_load = size < ctx_field_size;
46f53a65
AI
7578 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
7579 off = insn->off;
31fd8581 7580 if (is_narrower_load) {
f96da094
DB
7581 u8 size_code;
7582
7583 if (type == BPF_WRITE) {
61bd5218 7584 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
7585 return -EINVAL;
7586 }
31fd8581 7587
f96da094 7588 size_code = BPF_H;
31fd8581
YS
7589 if (ctx_field_size == 4)
7590 size_code = BPF_W;
7591 else if (ctx_field_size == 8)
7592 size_code = BPF_DW;
f96da094 7593
bc23105c 7594 insn->off = off & ~(size_default - 1);
31fd8581
YS
7595 insn->code = BPF_LDX | BPF_MEM | size_code;
7596 }
f96da094
DB
7597
7598 target_size = 0;
c64b7983
JS
7599 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
7600 &target_size);
f96da094
DB
7601 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
7602 (ctx_field_size && !target_size)) {
61bd5218 7603 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
7604 return -EINVAL;
7605 }
f96da094
DB
7606
7607 if (is_narrower_load && size < target_size) {
46f53a65
AI
7608 u8 shift = (off & (size_default - 1)) * 8;
7609
7610 if (ctx_field_size <= 4) {
7611 if (shift)
7612 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
7613 insn->dst_reg,
7614 shift);
31fd8581 7615 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 7616 (1 << size * 8) - 1);
46f53a65
AI
7617 } else {
7618 if (shift)
7619 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
7620 insn->dst_reg,
7621 shift);
31fd8581 7622 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 7623 (1ULL << size * 8) - 1);
46f53a65 7624 }
31fd8581 7625 }
9bac3d6d 7626
8041902d 7627 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
7628 if (!new_prog)
7629 return -ENOMEM;
7630
3df126f3 7631 delta += cnt - 1;
9bac3d6d
AS
7632
7633 /* keep walking new program and skip insns we just inserted */
7634 env->prog = new_prog;
3df126f3 7635 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
7636 }
7637
7638 return 0;
7639}
7640
1c2a088a
AS
7641static int jit_subprogs(struct bpf_verifier_env *env)
7642{
7643 struct bpf_prog *prog = env->prog, **func, *tmp;
7644 int i, j, subprog_start, subprog_end = 0, len, subprog;
7105e828 7645 struct bpf_insn *insn;
1c2a088a 7646 void *old_bpf_func;
c454a46b 7647 int err;
1c2a088a 7648
f910cefa 7649 if (env->subprog_cnt <= 1)
1c2a088a
AS
7650 return 0;
7651
7105e828 7652 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1c2a088a
AS
7653 if (insn->code != (BPF_JMP | BPF_CALL) ||
7654 insn->src_reg != BPF_PSEUDO_CALL)
7655 continue;
c7a89784
DB
7656 /* Upon error here we cannot fall back to interpreter but
7657 * need a hard reject of the program. Thus -EFAULT is
7658 * propagated in any case.
7659 */
1c2a088a
AS
7660 subprog = find_subprog(env, i + insn->imm + 1);
7661 if (subprog < 0) {
7662 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7663 i + insn->imm + 1);
7664 return -EFAULT;
7665 }
7666 /* temporarily remember subprog id inside insn instead of
7667 * aux_data, since next loop will split up all insns into funcs
7668 */
f910cefa 7669 insn->off = subprog;
1c2a088a
AS
7670 /* remember original imm in case JIT fails and fallback
7671 * to interpreter will be needed
7672 */
7673 env->insn_aux_data[i].call_imm = insn->imm;
7674 /* point imm to __bpf_call_base+1 from JITs point of view */
7675 insn->imm = 1;
7676 }
7677
c454a46b
MKL
7678 err = bpf_prog_alloc_jited_linfo(prog);
7679 if (err)
7680 goto out_undo_insn;
7681
7682 err = -ENOMEM;
6396bb22 7683 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 7684 if (!func)
c7a89784 7685 goto out_undo_insn;
1c2a088a 7686
f910cefa 7687 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 7688 subprog_start = subprog_end;
4cb3d99c 7689 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
7690
7691 len = subprog_end - subprog_start;
492ecee8
AS
7692 /* BPF_PROG_RUN doesn't call subprogs directly,
7693 * hence main prog stats include the runtime of subprogs.
7694 * subprogs don't have IDs and not reachable via prog_get_next_id
7695 * func[i]->aux->stats will never be accessed and stays NULL
7696 */
7697 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
7698 if (!func[i])
7699 goto out_free;
7700 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
7701 len * sizeof(struct bpf_insn));
4f74d809 7702 func[i]->type = prog->type;
1c2a088a 7703 func[i]->len = len;
4f74d809
DB
7704 if (bpf_prog_calc_tag(func[i]))
7705 goto out_free;
1c2a088a 7706 func[i]->is_func = 1;
ba64e7d8
YS
7707 func[i]->aux->func_idx = i;
7708 /* the btf and func_info will be freed only at prog->aux */
7709 func[i]->aux->btf = prog->aux->btf;
7710 func[i]->aux->func_info = prog->aux->func_info;
7711
1c2a088a
AS
7712 /* Use bpf_prog_F_tag to indicate functions in stack traces.
7713 * Long term would need debug info to populate names
7714 */
7715 func[i]->aux->name[0] = 'F';
9c8105bd 7716 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 7717 func[i]->jit_requested = 1;
c454a46b
MKL
7718 func[i]->aux->linfo = prog->aux->linfo;
7719 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
7720 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
7721 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
1c2a088a
AS
7722 func[i] = bpf_int_jit_compile(func[i]);
7723 if (!func[i]->jited) {
7724 err = -ENOTSUPP;
7725 goto out_free;
7726 }
7727 cond_resched();
7728 }
7729 /* at this point all bpf functions were successfully JITed
7730 * now populate all bpf_calls with correct addresses and
7731 * run last pass of JIT
7732 */
f910cefa 7733 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
7734 insn = func[i]->insnsi;
7735 for (j = 0; j < func[i]->len; j++, insn++) {
7736 if (insn->code != (BPF_JMP | BPF_CALL) ||
7737 insn->src_reg != BPF_PSEUDO_CALL)
7738 continue;
7739 subprog = insn->off;
0d306c31
PB
7740 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
7741 __bpf_call_base;
1c2a088a 7742 }
2162fed4
SD
7743
7744 /* we use the aux data to keep a list of the start addresses
7745 * of the JITed images for each function in the program
7746 *
7747 * for some architectures, such as powerpc64, the imm field
7748 * might not be large enough to hold the offset of the start
7749 * address of the callee's JITed image from __bpf_call_base
7750 *
7751 * in such cases, we can lookup the start address of a callee
7752 * by using its subprog id, available from the off field of
7753 * the call instruction, as an index for this list
7754 */
7755 func[i]->aux->func = func;
7756 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 7757 }
f910cefa 7758 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
7759 old_bpf_func = func[i]->bpf_func;
7760 tmp = bpf_int_jit_compile(func[i]);
7761 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
7762 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 7763 err = -ENOTSUPP;
1c2a088a
AS
7764 goto out_free;
7765 }
7766 cond_resched();
7767 }
7768
7769 /* finally lock prog and jit images for all functions and
7770 * populate kallsysm
7771 */
f910cefa 7772 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
7773 bpf_prog_lock_ro(func[i]);
7774 bpf_prog_kallsyms_add(func[i]);
7775 }
7105e828
DB
7776
7777 /* Last step: make now unused interpreter insns from main
7778 * prog consistent for later dump requests, so they can
7779 * later look the same as if they were interpreted only.
7780 */
7781 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7105e828
DB
7782 if (insn->code != (BPF_JMP | BPF_CALL) ||
7783 insn->src_reg != BPF_PSEUDO_CALL)
7784 continue;
7785 insn->off = env->insn_aux_data[i].call_imm;
7786 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 7787 insn->imm = subprog;
7105e828
DB
7788 }
7789
1c2a088a
AS
7790 prog->jited = 1;
7791 prog->bpf_func = func[0]->bpf_func;
7792 prog->aux->func = func;
f910cefa 7793 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 7794 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
7795 return 0;
7796out_free:
f910cefa 7797 for (i = 0; i < env->subprog_cnt; i++)
1c2a088a
AS
7798 if (func[i])
7799 bpf_jit_free(func[i]);
7800 kfree(func);
c7a89784 7801out_undo_insn:
1c2a088a
AS
7802 /* cleanup main prog to be interpreted */
7803 prog->jit_requested = 0;
7804 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7805 if (insn->code != (BPF_JMP | BPF_CALL) ||
7806 insn->src_reg != BPF_PSEUDO_CALL)
7807 continue;
7808 insn->off = 0;
7809 insn->imm = env->insn_aux_data[i].call_imm;
7810 }
c454a46b 7811 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
7812 return err;
7813}
7814
1ea47e01
AS
7815static int fixup_call_args(struct bpf_verifier_env *env)
7816{
19d28fbd 7817#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
7818 struct bpf_prog *prog = env->prog;
7819 struct bpf_insn *insn = prog->insnsi;
7820 int i, depth;
19d28fbd 7821#endif
e4052d06 7822 int err = 0;
1ea47e01 7823
e4052d06
QM
7824 if (env->prog->jit_requested &&
7825 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
7826 err = jit_subprogs(env);
7827 if (err == 0)
1c2a088a 7828 return 0;
c7a89784
DB
7829 if (err == -EFAULT)
7830 return err;
19d28fbd
DM
7831 }
7832#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
7833 for (i = 0; i < prog->len; i++, insn++) {
7834 if (insn->code != (BPF_JMP | BPF_CALL) ||
7835 insn->src_reg != BPF_PSEUDO_CALL)
7836 continue;
7837 depth = get_callee_stack_depth(env, insn, i);
7838 if (depth < 0)
7839 return depth;
7840 bpf_patch_call_args(insn, depth);
7841 }
19d28fbd
DM
7842 err = 0;
7843#endif
7844 return err;
1ea47e01
AS
7845}
7846
79741b3b 7847/* fixup insn->imm field of bpf_call instructions
81ed18ab 7848 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
7849 *
7850 * this function is called after eBPF program passed verification
7851 */
79741b3b 7852static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 7853{
79741b3b
AS
7854 struct bpf_prog *prog = env->prog;
7855 struct bpf_insn *insn = prog->insnsi;
e245c5c6 7856 const struct bpf_func_proto *fn;
79741b3b 7857 const int insn_cnt = prog->len;
09772d92 7858 const struct bpf_map_ops *ops;
c93552c4 7859 struct bpf_insn_aux_data *aux;
81ed18ab
AS
7860 struct bpf_insn insn_buf[16];
7861 struct bpf_prog *new_prog;
7862 struct bpf_map *map_ptr;
7863 int i, cnt, delta = 0;
e245c5c6 7864
79741b3b 7865 for (i = 0; i < insn_cnt; i++, insn++) {
f6b1b3bf
DB
7866 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
7867 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
7868 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 7869 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf
DB
7870 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
7871 struct bpf_insn mask_and_div[] = {
7872 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
7873 /* Rx div 0 -> 0 */
7874 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
7875 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
7876 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7877 *insn,
7878 };
7879 struct bpf_insn mask_and_mod[] = {
7880 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
7881 /* Rx mod 0 -> Rx */
7882 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
7883 *insn,
7884 };
7885 struct bpf_insn *patchlet;
7886
7887 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
7888 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
7889 patchlet = mask_and_div + (is64 ? 1 : 0);
7890 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
7891 } else {
7892 patchlet = mask_and_mod + (is64 ? 1 : 0);
7893 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
7894 }
7895
7896 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
7897 if (!new_prog)
7898 return -ENOMEM;
7899
7900 delta += cnt - 1;
7901 env->prog = prog = new_prog;
7902 insn = new_prog->insnsi + i + delta;
7903 continue;
7904 }
7905
e0cea7ce
DB
7906 if (BPF_CLASS(insn->code) == BPF_LD &&
7907 (BPF_MODE(insn->code) == BPF_ABS ||
7908 BPF_MODE(insn->code) == BPF_IND)) {
7909 cnt = env->ops->gen_ld_abs(insn, insn_buf);
7910 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
7911 verbose(env, "bpf verifier is misconfigured\n");
7912 return -EINVAL;
7913 }
7914
7915 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7916 if (!new_prog)
7917 return -ENOMEM;
7918
7919 delta += cnt - 1;
7920 env->prog = prog = new_prog;
7921 insn = new_prog->insnsi + i + delta;
7922 continue;
7923 }
7924
979d63d5
DB
7925 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
7926 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
7927 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
7928 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
7929 struct bpf_insn insn_buf[16];
7930 struct bpf_insn *patch = &insn_buf[0];
7931 bool issrc, isneg;
7932 u32 off_reg;
7933
7934 aux = &env->insn_aux_data[i + delta];
3612af78
DB
7935 if (!aux->alu_state ||
7936 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
7937 continue;
7938
7939 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
7940 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
7941 BPF_ALU_SANITIZE_SRC;
7942
7943 off_reg = issrc ? insn->src_reg : insn->dst_reg;
7944 if (isneg)
7945 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
7946 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
7947 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
7948 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
7949 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
7950 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
7951 if (issrc) {
7952 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
7953 off_reg);
7954 insn->src_reg = BPF_REG_AX;
7955 } else {
7956 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
7957 BPF_REG_AX);
7958 }
7959 if (isneg)
7960 insn->code = insn->code == code_add ?
7961 code_sub : code_add;
7962 *patch++ = *insn;
7963 if (issrc && isneg)
7964 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
7965 cnt = patch - insn_buf;
7966
7967 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7968 if (!new_prog)
7969 return -ENOMEM;
7970
7971 delta += cnt - 1;
7972 env->prog = prog = new_prog;
7973 insn = new_prog->insnsi + i + delta;
7974 continue;
7975 }
7976
79741b3b
AS
7977 if (insn->code != (BPF_JMP | BPF_CALL))
7978 continue;
cc8b0b92
AS
7979 if (insn->src_reg == BPF_PSEUDO_CALL)
7980 continue;
e245c5c6 7981
79741b3b
AS
7982 if (insn->imm == BPF_FUNC_get_route_realm)
7983 prog->dst_needed = 1;
7984 if (insn->imm == BPF_FUNC_get_prandom_u32)
7985 bpf_user_rnd_init_once();
9802d865
JB
7986 if (insn->imm == BPF_FUNC_override_return)
7987 prog->kprobe_override = 1;
79741b3b 7988 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
7989 /* If we tail call into other programs, we
7990 * cannot make any assumptions since they can
7991 * be replaced dynamically during runtime in
7992 * the program array.
7993 */
7994 prog->cb_access = 1;
80a58d02 7995 env->prog->aux->stack_depth = MAX_BPF_STACK;
e647815a 7996 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 7997
79741b3b
AS
7998 /* mark bpf_tail_call as different opcode to avoid
7999 * conditional branch in the interpeter for every normal
8000 * call and to prevent accidental JITing by JIT compiler
8001 * that doesn't support bpf_tail_call yet
e245c5c6 8002 */
79741b3b 8003 insn->imm = 0;
71189fa9 8004 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 8005
c93552c4
DB
8006 aux = &env->insn_aux_data[i + delta];
8007 if (!bpf_map_ptr_unpriv(aux))
8008 continue;
8009
b2157399
AS
8010 /* instead of changing every JIT dealing with tail_call
8011 * emit two extra insns:
8012 * if (index >= max_entries) goto out;
8013 * index &= array->index_mask;
8014 * to avoid out-of-bounds cpu speculation
8015 */
c93552c4 8016 if (bpf_map_ptr_poisoned(aux)) {
40950343 8017 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
8018 return -EINVAL;
8019 }
c93552c4
DB
8020
8021 map_ptr = BPF_MAP_PTR(aux->map_state);
b2157399
AS
8022 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
8023 map_ptr->max_entries, 2);
8024 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
8025 container_of(map_ptr,
8026 struct bpf_array,
8027 map)->index_mask);
8028 insn_buf[2] = *insn;
8029 cnt = 3;
8030 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
8031 if (!new_prog)
8032 return -ENOMEM;
8033
8034 delta += cnt - 1;
8035 env->prog = prog = new_prog;
8036 insn = new_prog->insnsi + i + delta;
79741b3b
AS
8037 continue;
8038 }
e245c5c6 8039
89c63074 8040 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
8041 * and other inlining handlers are currently limited to 64 bit
8042 * only.
89c63074 8043 */
60b58afc 8044 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
8045 (insn->imm == BPF_FUNC_map_lookup_elem ||
8046 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
8047 insn->imm == BPF_FUNC_map_delete_elem ||
8048 insn->imm == BPF_FUNC_map_push_elem ||
8049 insn->imm == BPF_FUNC_map_pop_elem ||
8050 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
8051 aux = &env->insn_aux_data[i + delta];
8052 if (bpf_map_ptr_poisoned(aux))
8053 goto patch_call_imm;
8054
8055 map_ptr = BPF_MAP_PTR(aux->map_state);
09772d92
DB
8056 ops = map_ptr->ops;
8057 if (insn->imm == BPF_FUNC_map_lookup_elem &&
8058 ops->map_gen_lookup) {
8059 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
8060 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
8061 verbose(env, "bpf verifier is misconfigured\n");
8062 return -EINVAL;
8063 }
81ed18ab 8064
09772d92
DB
8065 new_prog = bpf_patch_insn_data(env, i + delta,
8066 insn_buf, cnt);
8067 if (!new_prog)
8068 return -ENOMEM;
81ed18ab 8069
09772d92
DB
8070 delta += cnt - 1;
8071 env->prog = prog = new_prog;
8072 insn = new_prog->insnsi + i + delta;
8073 continue;
8074 }
81ed18ab 8075
09772d92
DB
8076 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
8077 (void *(*)(struct bpf_map *map, void *key))NULL));
8078 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
8079 (int (*)(struct bpf_map *map, void *key))NULL));
8080 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
8081 (int (*)(struct bpf_map *map, void *key, void *value,
8082 u64 flags))NULL));
84430d42
DB
8083 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
8084 (int (*)(struct bpf_map *map, void *value,
8085 u64 flags))NULL));
8086 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
8087 (int (*)(struct bpf_map *map, void *value))NULL));
8088 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
8089 (int (*)(struct bpf_map *map, void *value))NULL));
8090
09772d92
DB
8091 switch (insn->imm) {
8092 case BPF_FUNC_map_lookup_elem:
8093 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
8094 __bpf_call_base;
8095 continue;
8096 case BPF_FUNC_map_update_elem:
8097 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
8098 __bpf_call_base;
8099 continue;
8100 case BPF_FUNC_map_delete_elem:
8101 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
8102 __bpf_call_base;
8103 continue;
84430d42
DB
8104 case BPF_FUNC_map_push_elem:
8105 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
8106 __bpf_call_base;
8107 continue;
8108 case BPF_FUNC_map_pop_elem:
8109 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
8110 __bpf_call_base;
8111 continue;
8112 case BPF_FUNC_map_peek_elem:
8113 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
8114 __bpf_call_base;
8115 continue;
09772d92 8116 }
81ed18ab 8117
09772d92 8118 goto patch_call_imm;
81ed18ab
AS
8119 }
8120
8121patch_call_imm:
5e43f899 8122 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
8123 /* all functions that have prototype and verifier allowed
8124 * programs to call them, must be real in-kernel functions
8125 */
8126 if (!fn->func) {
61bd5218
JK
8127 verbose(env,
8128 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
8129 func_id_name(insn->imm), insn->imm);
8130 return -EFAULT;
e245c5c6 8131 }
79741b3b 8132 insn->imm = fn->func - __bpf_call_base;
e245c5c6 8133 }
e245c5c6 8134
79741b3b
AS
8135 return 0;
8136}
e245c5c6 8137
58e2af8b 8138static void free_states(struct bpf_verifier_env *env)
f1bca824 8139{
58e2af8b 8140 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
8141 int i;
8142
9f4686c4
AS
8143 sl = env->free_list;
8144 while (sl) {
8145 sln = sl->next;
8146 free_verifier_state(&sl->state, false);
8147 kfree(sl);
8148 sl = sln;
8149 }
8150
f1bca824
AS
8151 if (!env->explored_states)
8152 return;
8153
dc2a4ebc 8154 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
8155 sl = env->explored_states[i];
8156
a8f500af
AS
8157 while (sl) {
8158 sln = sl->next;
8159 free_verifier_state(&sl->state, false);
8160 kfree(sl);
8161 sl = sln;
8162 }
f1bca824
AS
8163 }
8164
71dde681 8165 kvfree(env->explored_states);
f1bca824
AS
8166}
8167
06ee7115
AS
8168static void print_verification_stats(struct bpf_verifier_env *env)
8169{
8170 int i;
8171
8172 if (env->log.level & BPF_LOG_STATS) {
8173 verbose(env, "verification time %lld usec\n",
8174 div_u64(env->verification_time, 1000));
8175 verbose(env, "stack depth ");
8176 for (i = 0; i < env->subprog_cnt; i++) {
8177 u32 depth = env->subprog_info[i].stack_depth;
8178
8179 verbose(env, "%d", depth);
8180 if (i + 1 < env->subprog_cnt)
8181 verbose(env, "+");
8182 }
8183 verbose(env, "\n");
8184 }
8185 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
8186 "total_states %d peak_states %d mark_read %d\n",
8187 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
8188 env->max_states_per_insn, env->total_states,
8189 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
8190}
8191
838e9690
YS
8192int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
8193 union bpf_attr __user *uattr)
51580e79 8194{
06ee7115 8195 u64 start_time = ktime_get_ns();
58e2af8b 8196 struct bpf_verifier_env *env;
b9193c1b 8197 struct bpf_verifier_log *log;
9e4c24e7 8198 int i, len, ret = -EINVAL;
e2ae4ca2 8199 bool is_priv;
51580e79 8200
eba0c929
AB
8201 /* no program is valid */
8202 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
8203 return -EINVAL;
8204
58e2af8b 8205 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
8206 * allocate/free it every time bpf_check() is called
8207 */
58e2af8b 8208 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
8209 if (!env)
8210 return -ENOMEM;
61bd5218 8211 log = &env->log;
cbd35700 8212
9e4c24e7 8213 len = (*prog)->len;
fad953ce 8214 env->insn_aux_data =
9e4c24e7 8215 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
8216 ret = -ENOMEM;
8217 if (!env->insn_aux_data)
8218 goto err_free_env;
9e4c24e7
JK
8219 for (i = 0; i < len; i++)
8220 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 8221 env->prog = *prog;
00176a34 8222 env->ops = bpf_verifier_ops[env->prog->type];
45a73c17 8223 is_priv = capable(CAP_SYS_ADMIN);
0246e64d 8224
cbd35700 8225 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
8226 if (!is_priv)
8227 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
8228
8229 if (attr->log_level || attr->log_buf || attr->log_size) {
8230 /* user requested verbose verifier output
8231 * and supplied buffer to store the verification trace
8232 */
e7bf8249
JK
8233 log->level = attr->log_level;
8234 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
8235 log->len_total = attr->log_size;
cbd35700
AS
8236
8237 ret = -EINVAL;
e7bf8249 8238 /* log attributes have to be sane */
7a9f5c65 8239 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 8240 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 8241 goto err_unlock;
cbd35700 8242 }
1ad2f583
DB
8243
8244 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
8245 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 8246 env->strict_alignment = true;
e9ee9efc
DM
8247 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
8248 env->strict_alignment = false;
cbd35700 8249
e2ae4ca2
JK
8250 env->allow_ptr_leaks = is_priv;
8251
f4e3ec0d
JK
8252 ret = replace_map_fd_with_map_ptr(env);
8253 if (ret < 0)
8254 goto skip_full_check;
8255
cae1927c 8256 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 8257 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 8258 if (ret)
f4e3ec0d 8259 goto skip_full_check;
ab3f0063
JK
8260 }
8261
dc2a4ebc 8262 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 8263 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
8264 GFP_USER);
8265 ret = -ENOMEM;
8266 if (!env->explored_states)
8267 goto skip_full_check;
8268
d9762e84 8269 ret = check_subprogs(env);
475fb78f
AS
8270 if (ret < 0)
8271 goto skip_full_check;
8272
c454a46b 8273 ret = check_btf_info(env, attr, uattr);
838e9690
YS
8274 if (ret < 0)
8275 goto skip_full_check;
8276
d9762e84
MKL
8277 ret = check_cfg(env);
8278 if (ret < 0)
8279 goto skip_full_check;
8280
17a52670 8281 ret = do_check(env);
8c01c4f8
CG
8282 if (env->cur_state) {
8283 free_verifier_state(env->cur_state, true);
8284 env->cur_state = NULL;
8285 }
cbd35700 8286
c941ce9c
QM
8287 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
8288 ret = bpf_prog_offload_finalize(env);
8289
0246e64d 8290skip_full_check:
638f5b90 8291 while (!pop_stack(env, NULL, NULL));
f1bca824 8292 free_states(env);
0246e64d 8293
c131187d 8294 if (ret == 0)
9b38c405 8295 ret = check_max_stack_depth(env);
c131187d 8296
9b38c405 8297 /* instruction rewrites happen after this point */
e2ae4ca2
JK
8298 if (is_priv) {
8299 if (ret == 0)
8300 opt_hard_wire_dead_code_branches(env);
52875a04
JK
8301 if (ret == 0)
8302 ret = opt_remove_dead_code(env);
a1b14abc
JK
8303 if (ret == 0)
8304 ret = opt_remove_nops(env);
52875a04
JK
8305 } else {
8306 if (ret == 0)
8307 sanitize_dead_code(env);
e2ae4ca2
JK
8308 }
8309
9bac3d6d
AS
8310 if (ret == 0)
8311 /* program is valid, convert *(u32*)(ctx + off) accesses */
8312 ret = convert_ctx_accesses(env);
8313
e245c5c6 8314 if (ret == 0)
79741b3b 8315 ret = fixup_bpf_calls(env);
e245c5c6 8316
1ea47e01
AS
8317 if (ret == 0)
8318 ret = fixup_call_args(env);
8319
06ee7115
AS
8320 env->verification_time = ktime_get_ns() - start_time;
8321 print_verification_stats(env);
8322
a2a7d570 8323 if (log->level && bpf_verifier_log_full(log))
cbd35700 8324 ret = -ENOSPC;
a2a7d570 8325 if (log->level && !log->ubuf) {
cbd35700 8326 ret = -EFAULT;
a2a7d570 8327 goto err_release_maps;
cbd35700
AS
8328 }
8329
0246e64d
AS
8330 if (ret == 0 && env->used_map_cnt) {
8331 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
8332 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
8333 sizeof(env->used_maps[0]),
8334 GFP_KERNEL);
0246e64d 8335
9bac3d6d 8336 if (!env->prog->aux->used_maps) {
0246e64d 8337 ret = -ENOMEM;
a2a7d570 8338 goto err_release_maps;
0246e64d
AS
8339 }
8340
9bac3d6d 8341 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 8342 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 8343 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
8344
8345 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
8346 * bpf_ld_imm64 instructions
8347 */
8348 convert_pseudo_ld_imm64(env);
8349 }
cbd35700 8350
ba64e7d8
YS
8351 if (ret == 0)
8352 adjust_btf_func(env);
8353
a2a7d570 8354err_release_maps:
9bac3d6d 8355 if (!env->prog->aux->used_maps)
0246e64d 8356 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 8357 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
8358 */
8359 release_maps(env);
9bac3d6d 8360 *prog = env->prog;
3df126f3 8361err_unlock:
45a73c17
AS
8362 if (!is_priv)
8363 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
8364 vfree(env->insn_aux_data);
8365err_free_env:
8366 kfree(env);
51580e79
AS
8367 return ret;
8368}