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