]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - kernel/bpf/verifier.c
bpf: move global verifier log into verifier environment
[mirror_ubuntu-jammy-kernel.git] / kernel / bpf / verifier.c
CommitLineData
51580e79 1/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 2 * Copyright (c) 2016 Facebook
51580e79
AS
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13#include <linux/kernel.h>
14#include <linux/types.h>
15#include <linux/slab.h>
16#include <linux/bpf.h>
58e2af8b 17#include <linux/bpf_verifier.h>
51580e79
AS
18#include <linux/filter.h>
19#include <net/netlink.h>
20#include <linux/file.h>
21#include <linux/vmalloc.h>
ebb676da 22#include <linux/stringify.h>
51580e79
AS
23
24/* bpf_check() is a static code analyzer that walks eBPF program
25 * instruction by instruction and updates register/stack state.
26 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
27 *
28 * The first pass is depth-first-search to check that the program is a DAG.
29 * It rejects the following programs:
30 * - larger than BPF_MAXINSNS insns
31 * - if loop is present (detected via back-edge)
32 * - unreachable insns exist (shouldn't be a forest. program = one function)
33 * - out of bounds or malformed jumps
34 * The second pass is all possible path descent from the 1st insn.
35 * Since it's analyzing all pathes through the program, the length of the
eba38a96 36 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
37 * insn is less then 4K, but there are too many branches that change stack/regs.
38 * Number of 'branches to be analyzed' is limited to 1k
39 *
40 * On entry to each instruction, each register has a type, and the instruction
41 * changes the types of the registers depending on instruction semantics.
42 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
43 * copied to R1.
44 *
45 * All registers are 64-bit.
46 * R0 - return register
47 * R1-R5 argument passing registers
48 * R6-R9 callee saved registers
49 * R10 - frame pointer read-only
50 *
51 * At the start of BPF program the register R1 contains a pointer to bpf_context
52 * and has type PTR_TO_CTX.
53 *
54 * Verifier tracks arithmetic operations on pointers in case:
55 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
56 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
57 * 1st insn copies R10 (which has FRAME_PTR) type into R1
58 * and 2nd arithmetic instruction is pattern matched to recognize
59 * that it wants to construct a pointer to some element within stack.
60 * So after 2nd insn, the register R1 has type PTR_TO_STACK
61 * (and -20 constant is saved for further stack bounds checking).
62 * Meaning that this reg is a pointer to stack plus known immediate constant.
63 *
f1174f77 64 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 65 * means the register has some value, but it's not a valid pointer.
f1174f77 66 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
67 *
68 * When verifier sees load or store instructions the type of base register
f1174f77 69 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
51580e79
AS
70 * types recognized by check_mem_access() function.
71 *
72 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
73 * and the range of [ptr, ptr + map's value_size) is accessible.
74 *
75 * registers used to pass values to function calls are checked against
76 * function argument constraints.
77 *
78 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
79 * It means that the register type passed to this function must be
80 * PTR_TO_STACK and it will be used inside the function as
81 * 'pointer to map element key'
82 *
83 * For example the argument constraints for bpf_map_lookup_elem():
84 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
85 * .arg1_type = ARG_CONST_MAP_PTR,
86 * .arg2_type = ARG_PTR_TO_MAP_KEY,
87 *
88 * ret_type says that this function returns 'pointer to map elem value or null'
89 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
90 * 2nd argument should be a pointer to stack, which will be used inside
91 * the helper function as a pointer to map element key.
92 *
93 * On the kernel side the helper function looks like:
94 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
95 * {
96 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
97 * void *key = (void *) (unsigned long) r2;
98 * void *value;
99 *
100 * here kernel can access 'key' and 'map' pointers safely, knowing that
101 * [key, key + map->key_size) bytes are valid and were initialized on
102 * the stack of eBPF program.
103 * }
104 *
105 * Corresponding eBPF program may look like:
106 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
107 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
108 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
109 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
110 * here verifier looks at prototype of map_lookup_elem() and sees:
111 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
112 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
113 *
114 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
115 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
116 * and were initialized prior to this call.
117 * If it's ok, then verifier allows this BPF_CALL insn and looks at
118 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
119 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
120 * returns ether pointer to map value or NULL.
121 *
122 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
123 * insn, the register holding that pointer in the true branch changes state to
124 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
125 * branch. See check_cond_jmp_op().
126 *
127 * After the call R0 is set to return type of the function and registers R1-R5
128 * are set to NOT_INIT to indicate that they are no longer readable.
129 */
130
17a52670 131/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 132struct bpf_verifier_stack_elem {
17a52670
AS
133 /* verifer state is 'st'
134 * before processing instruction 'insn_idx'
135 * and after processing instruction 'prev_insn_idx'
136 */
58e2af8b 137 struct bpf_verifier_state st;
17a52670
AS
138 int insn_idx;
139 int prev_insn_idx;
58e2af8b 140 struct bpf_verifier_stack_elem *next;
cbd35700
AS
141};
142
8e17c1b1 143#define BPF_COMPLEXITY_LIMIT_INSNS 131072
07016151
DB
144#define BPF_COMPLEXITY_LIMIT_STACK 1024
145
fad73a1a
MKL
146#define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
147
33ff9823
DB
148struct bpf_call_arg_meta {
149 struct bpf_map *map_ptr;
435faee1 150 bool raw_mode;
36bbef52 151 bool pkt_access;
435faee1
DB
152 int regno;
153 int access_size;
33ff9823
DB
154};
155
cbd35700
AS
156static DEFINE_MUTEX(bpf_verifier_lock);
157
158/* log_level controls verbosity level of eBPF verifier.
159 * verbose() is used to dump the verification trace to the log, so the user
160 * can figure out what's wrong with the program
161 */
61bd5218
JK
162static __printf(2, 3) void verbose(struct bpf_verifier_env *env,
163 const char *fmt, ...)
cbd35700 164{
61bd5218 165 struct bpf_verifer_log *log = &env->log;
cbd35700
AS
166 va_list args;
167
e7bf8249 168 if (!log->level || bpf_verifier_log_full(log))
cbd35700
AS
169 return;
170
171 va_start(args, fmt);
e7bf8249
JK
172 log->len_used += vscnprintf(log->kbuf + log->len_used,
173 log->len_total - log->len_used, fmt, args);
cbd35700
AS
174 va_end(args);
175}
176
de8f3a83
DB
177static bool type_is_pkt_pointer(enum bpf_reg_type type)
178{
179 return type == PTR_TO_PACKET ||
180 type == PTR_TO_PACKET_META;
181}
182
17a52670
AS
183/* string representation of 'enum bpf_reg_type' */
184static const char * const reg_type_str[] = {
185 [NOT_INIT] = "?",
f1174f77 186 [SCALAR_VALUE] = "inv",
17a52670
AS
187 [PTR_TO_CTX] = "ctx",
188 [CONST_PTR_TO_MAP] = "map_ptr",
189 [PTR_TO_MAP_VALUE] = "map_value",
190 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 191 [PTR_TO_STACK] = "fp",
969bf05e 192 [PTR_TO_PACKET] = "pkt",
de8f3a83 193 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 194 [PTR_TO_PACKET_END] = "pkt_end",
17a52670
AS
195};
196
ebb676da
TG
197#define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
198static const char * const func_id_str[] = {
199 __BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
200};
201#undef __BPF_FUNC_STR_FN
202
203static const char *func_id_name(int id)
204{
205 BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID);
206
207 if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id])
208 return func_id_str[id];
209 else
210 return "unknown";
211}
212
61bd5218
JK
213static void print_verifier_state(struct bpf_verifier_env *env,
214 struct bpf_verifier_state *state)
17a52670 215{
58e2af8b 216 struct bpf_reg_state *reg;
17a52670
AS
217 enum bpf_reg_type t;
218 int i;
219
220 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
221 reg = &state->regs[i];
222 t = reg->type;
17a52670
AS
223 if (t == NOT_INIT)
224 continue;
61bd5218 225 verbose(env, " R%d=%s", i, reg_type_str[t]);
f1174f77
EC
226 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
227 tnum_is_const(reg->var_off)) {
228 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 229 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 230 } else {
61bd5218 231 verbose(env, "(id=%d", reg->id);
f1174f77 232 if (t != SCALAR_VALUE)
61bd5218 233 verbose(env, ",off=%d", reg->off);
de8f3a83 234 if (type_is_pkt_pointer(t))
61bd5218 235 verbose(env, ",r=%d", reg->range);
f1174f77
EC
236 else if (t == CONST_PTR_TO_MAP ||
237 t == PTR_TO_MAP_VALUE ||
238 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 239 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
240 reg->map_ptr->key_size,
241 reg->map_ptr->value_size);
7d1238f2
EC
242 if (tnum_is_const(reg->var_off)) {
243 /* Typically an immediate SCALAR_VALUE, but
244 * could be a pointer whose offset is too big
245 * for reg->off
246 */
61bd5218 247 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
248 } else {
249 if (reg->smin_value != reg->umin_value &&
250 reg->smin_value != S64_MIN)
61bd5218 251 verbose(env, ",smin_value=%lld",
7d1238f2
EC
252 (long long)reg->smin_value);
253 if (reg->smax_value != reg->umax_value &&
254 reg->smax_value != S64_MAX)
61bd5218 255 verbose(env, ",smax_value=%lld",
7d1238f2
EC
256 (long long)reg->smax_value);
257 if (reg->umin_value != 0)
61bd5218 258 verbose(env, ",umin_value=%llu",
7d1238f2
EC
259 (unsigned long long)reg->umin_value);
260 if (reg->umax_value != U64_MAX)
61bd5218 261 verbose(env, ",umax_value=%llu",
7d1238f2
EC
262 (unsigned long long)reg->umax_value);
263 if (!tnum_is_unknown(reg->var_off)) {
264 char tn_buf[48];
f1174f77 265
7d1238f2 266 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 267 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 268 }
f1174f77 269 }
61bd5218 270 verbose(env, ")");
f1174f77 271 }
17a52670 272 }
9c399760 273 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1a0dc1ac 274 if (state->stack_slot_type[i] == STACK_SPILL)
61bd5218 275 verbose(env, " fp%d=%s", -MAX_BPF_STACK + i,
1a0dc1ac 276 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
17a52670 277 }
61bd5218 278 verbose(env, "\n");
17a52670
AS
279}
280
cbd35700
AS
281static const char *const bpf_class_string[] = {
282 [BPF_LD] = "ld",
283 [BPF_LDX] = "ldx",
284 [BPF_ST] = "st",
285 [BPF_STX] = "stx",
286 [BPF_ALU] = "alu",
287 [BPF_JMP] = "jmp",
288 [BPF_RET] = "BUG",
289 [BPF_ALU64] = "alu64",
290};
291
687f0715 292static const char *const bpf_alu_string[16] = {
cbd35700
AS
293 [BPF_ADD >> 4] = "+=",
294 [BPF_SUB >> 4] = "-=",
295 [BPF_MUL >> 4] = "*=",
296 [BPF_DIV >> 4] = "/=",
297 [BPF_OR >> 4] = "|=",
298 [BPF_AND >> 4] = "&=",
299 [BPF_LSH >> 4] = "<<=",
300 [BPF_RSH >> 4] = ">>=",
301 [BPF_NEG >> 4] = "neg",
302 [BPF_MOD >> 4] = "%=",
303 [BPF_XOR >> 4] = "^=",
304 [BPF_MOV >> 4] = "=",
305 [BPF_ARSH >> 4] = "s>>=",
306 [BPF_END >> 4] = "endian",
307};
308
309static const char *const bpf_ldst_string[] = {
310 [BPF_W >> 3] = "u32",
311 [BPF_H >> 3] = "u16",
312 [BPF_B >> 3] = "u8",
313 [BPF_DW >> 3] = "u64",
314};
315
687f0715 316static const char *const bpf_jmp_string[16] = {
cbd35700
AS
317 [BPF_JA >> 4] = "jmp",
318 [BPF_JEQ >> 4] = "==",
319 [BPF_JGT >> 4] = ">",
b4e432f1 320 [BPF_JLT >> 4] = "<",
cbd35700 321 [BPF_JGE >> 4] = ">=",
b4e432f1 322 [BPF_JLE >> 4] = "<=",
cbd35700
AS
323 [BPF_JSET >> 4] = "&",
324 [BPF_JNE >> 4] = "!=",
325 [BPF_JSGT >> 4] = "s>",
b4e432f1 326 [BPF_JSLT >> 4] = "s<",
cbd35700 327 [BPF_JSGE >> 4] = "s>=",
b4e432f1 328 [BPF_JSLE >> 4] = "s<=",
cbd35700
AS
329 [BPF_CALL >> 4] = "call",
330 [BPF_EXIT >> 4] = "exit",
331};
332
61bd5218 333static void print_bpf_end_insn(struct bpf_verifier_env *env,
2b7c6ba9
EC
334 const struct bpf_insn *insn)
335{
61bd5218 336 verbose(env, "(%02x) r%d = %s%d r%d\n", insn->code, insn->dst_reg,
2b7c6ba9
EC
337 BPF_SRC(insn->code) == BPF_TO_BE ? "be" : "le",
338 insn->imm, insn->dst_reg);
339}
340
61bd5218 341static void print_bpf_insn(struct bpf_verifier_env *env,
0d0e5769 342 const struct bpf_insn *insn)
cbd35700
AS
343{
344 u8 class = BPF_CLASS(insn->code);
345
346 if (class == BPF_ALU || class == BPF_ALU64) {
2b7c6ba9
EC
347 if (BPF_OP(insn->code) == BPF_END) {
348 if (class == BPF_ALU64)
61bd5218 349 verbose(env, "BUG_alu64_%02x\n", insn->code);
2b7c6ba9
EC
350 else
351 print_bpf_end_insn(env, insn);
73c864b3 352 } else if (BPF_OP(insn->code) == BPF_NEG) {
61bd5218 353 verbose(env, "(%02x) r%d = %s-r%d\n",
73c864b3
EC
354 insn->code, insn->dst_reg,
355 class == BPF_ALU ? "(u32) " : "",
356 insn->dst_reg);
2b7c6ba9 357 } else if (BPF_SRC(insn->code) == BPF_X) {
61bd5218 358 verbose(env, "(%02x) %sr%d %s %sr%d\n",
cbd35700
AS
359 insn->code, class == BPF_ALU ? "(u32) " : "",
360 insn->dst_reg,
361 bpf_alu_string[BPF_OP(insn->code) >> 4],
362 class == BPF_ALU ? "(u32) " : "",
363 insn->src_reg);
2b7c6ba9 364 } else {
61bd5218 365 verbose(env, "(%02x) %sr%d %s %s%d\n",
cbd35700
AS
366 insn->code, class == BPF_ALU ? "(u32) " : "",
367 insn->dst_reg,
368 bpf_alu_string[BPF_OP(insn->code) >> 4],
369 class == BPF_ALU ? "(u32) " : "",
370 insn->imm);
2b7c6ba9 371 }
cbd35700
AS
372 } else if (class == BPF_STX) {
373 if (BPF_MODE(insn->code) == BPF_MEM)
61bd5218 374 verbose(env, "(%02x) *(%s *)(r%d %+d) = r%d\n",
cbd35700
AS
375 insn->code,
376 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
377 insn->dst_reg,
378 insn->off, insn->src_reg);
379 else if (BPF_MODE(insn->code) == BPF_XADD)
61bd5218 380 verbose(env, "(%02x) lock *(%s *)(r%d %+d) += r%d\n",
cbd35700
AS
381 insn->code,
382 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
383 insn->dst_reg, insn->off,
384 insn->src_reg);
385 else
61bd5218 386 verbose(env, "BUG_%02x\n", insn->code);
cbd35700
AS
387 } else if (class == BPF_ST) {
388 if (BPF_MODE(insn->code) != BPF_MEM) {
61bd5218 389 verbose(env, "BUG_st_%02x\n", insn->code);
cbd35700
AS
390 return;
391 }
61bd5218 392 verbose(env, "(%02x) *(%s *)(r%d %+d) = %d\n",
cbd35700
AS
393 insn->code,
394 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
395 insn->dst_reg,
396 insn->off, insn->imm);
397 } else if (class == BPF_LDX) {
398 if (BPF_MODE(insn->code) != BPF_MEM) {
61bd5218 399 verbose(env, "BUG_ldx_%02x\n", insn->code);
cbd35700
AS
400 return;
401 }
61bd5218 402 verbose(env, "(%02x) r%d = *(%s *)(r%d %+d)\n",
cbd35700
AS
403 insn->code, insn->dst_reg,
404 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
405 insn->src_reg, insn->off);
406 } else if (class == BPF_LD) {
407 if (BPF_MODE(insn->code) == BPF_ABS) {
61bd5218 408 verbose(env, "(%02x) r0 = *(%s *)skb[%d]\n",
cbd35700
AS
409 insn->code,
410 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
411 insn->imm);
412 } else if (BPF_MODE(insn->code) == BPF_IND) {
61bd5218 413 verbose(env, "(%02x) r0 = *(%s *)skb[r%d + %d]\n",
cbd35700
AS
414 insn->code,
415 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
416 insn->src_reg, insn->imm);
0d0e5769
DB
417 } else if (BPF_MODE(insn->code) == BPF_IMM &&
418 BPF_SIZE(insn->code) == BPF_DW) {
419 /* At this point, we already made sure that the second
420 * part of the ldimm64 insn is accessible.
421 */
422 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
423 bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
424
425 if (map_ptr && !env->allow_ptr_leaks)
426 imm = 0;
427
61bd5218 428 verbose(env, "(%02x) r%d = 0x%llx\n", insn->code,
0d0e5769 429 insn->dst_reg, (unsigned long long)imm);
cbd35700 430 } else {
61bd5218 431 verbose(env, "BUG_ld_%02x\n", insn->code);
cbd35700
AS
432 return;
433 }
434 } else if (class == BPF_JMP) {
435 u8 opcode = BPF_OP(insn->code);
436
437 if (opcode == BPF_CALL) {
61bd5218 438 verbose(env, "(%02x) call %s#%d\n", insn->code,
ebb676da 439 func_id_name(insn->imm), insn->imm);
cbd35700 440 } else if (insn->code == (BPF_JMP | BPF_JA)) {
61bd5218 441 verbose(env, "(%02x) goto pc%+d\n",
cbd35700
AS
442 insn->code, insn->off);
443 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
61bd5218 444 verbose(env, "(%02x) exit\n", insn->code);
cbd35700 445 } else if (BPF_SRC(insn->code) == BPF_X) {
61bd5218 446 verbose(env, "(%02x) if r%d %s r%d goto pc%+d\n",
cbd35700
AS
447 insn->code, insn->dst_reg,
448 bpf_jmp_string[BPF_OP(insn->code) >> 4],
449 insn->src_reg, insn->off);
450 } else {
61bd5218 451 verbose(env, "(%02x) if r%d %s 0x%x goto pc%+d\n",
cbd35700
AS
452 insn->code, insn->dst_reg,
453 bpf_jmp_string[BPF_OP(insn->code) >> 4],
454 insn->imm, insn->off);
455 }
456 } else {
61bd5218
JK
457 verbose(env, "(%02x) %s\n",
458 insn->code, bpf_class_string[class]);
cbd35700
AS
459 }
460}
461
58e2af8b 462static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
17a52670 463{
58e2af8b 464 struct bpf_verifier_stack_elem *elem;
17a52670
AS
465 int insn_idx;
466
467 if (env->head == NULL)
468 return -1;
469
470 memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
471 insn_idx = env->head->insn_idx;
472 if (prev_insn_idx)
473 *prev_insn_idx = env->head->prev_insn_idx;
474 elem = env->head->next;
475 kfree(env->head);
476 env->head = elem;
477 env->stack_size--;
478 return insn_idx;
479}
480
58e2af8b
JK
481static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
482 int insn_idx, int prev_insn_idx)
17a52670 483{
58e2af8b 484 struct bpf_verifier_stack_elem *elem;
17a52670 485
58e2af8b 486 elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
487 if (!elem)
488 goto err;
489
490 memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
491 elem->insn_idx = insn_idx;
492 elem->prev_insn_idx = prev_insn_idx;
493 elem->next = env->head;
494 env->head = elem;
495 env->stack_size++;
07016151 496 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
61bd5218 497 verbose(env, "BPF program is too complex\n");
17a52670
AS
498 goto err;
499 }
500 return &elem->st;
501err:
502 /* pop all elements and return */
503 while (pop_stack(env, NULL) >= 0);
504 return NULL;
505}
506
507#define CALLER_SAVED_REGS 6
508static const int caller_saved[CALLER_SAVED_REGS] = {
509 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
510};
511
f1174f77
EC
512static void __mark_reg_not_init(struct bpf_reg_state *reg);
513
b03c9f9f
EC
514/* Mark the unknown part of a register (variable offset or scalar value) as
515 * known to have the value @imm.
516 */
517static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
518{
519 reg->id = 0;
520 reg->var_off = tnum_const(imm);
521 reg->smin_value = (s64)imm;
522 reg->smax_value = (s64)imm;
523 reg->umin_value = imm;
524 reg->umax_value = imm;
525}
526
f1174f77
EC
527/* Mark the 'variable offset' part of a register as zero. This should be
528 * used only on registers holding a pointer type.
529 */
530static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 531{
b03c9f9f 532 __mark_reg_known(reg, 0);
f1174f77 533}
a9789ef9 534
61bd5218
JK
535static void mark_reg_known_zero(struct bpf_verifier_env *env,
536 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
537{
538 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 539 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
540 /* Something bad happened, let's kill all regs */
541 for (regno = 0; regno < MAX_BPF_REG; regno++)
542 __mark_reg_not_init(regs + regno);
543 return;
544 }
545 __mark_reg_known_zero(regs + regno);
546}
547
de8f3a83
DB
548static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
549{
550 return type_is_pkt_pointer(reg->type);
551}
552
553static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
554{
555 return reg_is_pkt_pointer(reg) ||
556 reg->type == PTR_TO_PACKET_END;
557}
558
559/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
560static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
561 enum bpf_reg_type which)
562{
563 /* The register can already have a range from prior markings.
564 * This is fine as long as it hasn't been advanced from its
565 * origin.
566 */
567 return reg->type == which &&
568 reg->id == 0 &&
569 reg->off == 0 &&
570 tnum_equals_const(reg->var_off, 0);
571}
572
b03c9f9f
EC
573/* Attempts to improve min/max values based on var_off information */
574static void __update_reg_bounds(struct bpf_reg_state *reg)
575{
576 /* min signed is max(sign bit) | min(other bits) */
577 reg->smin_value = max_t(s64, reg->smin_value,
578 reg->var_off.value | (reg->var_off.mask & S64_MIN));
579 /* max signed is min(sign bit) | max(other bits) */
580 reg->smax_value = min_t(s64, reg->smax_value,
581 reg->var_off.value | (reg->var_off.mask & S64_MAX));
582 reg->umin_value = max(reg->umin_value, reg->var_off.value);
583 reg->umax_value = min(reg->umax_value,
584 reg->var_off.value | reg->var_off.mask);
585}
586
587/* Uses signed min/max values to inform unsigned, and vice-versa */
588static void __reg_deduce_bounds(struct bpf_reg_state *reg)
589{
590 /* Learn sign from signed bounds.
591 * If we cannot cross the sign boundary, then signed and unsigned bounds
592 * are the same, so combine. This works even in the negative case, e.g.
593 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
594 */
595 if (reg->smin_value >= 0 || reg->smax_value < 0) {
596 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
597 reg->umin_value);
598 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
599 reg->umax_value);
600 return;
601 }
602 /* Learn sign from unsigned bounds. Signed bounds cross the sign
603 * boundary, so we must be careful.
604 */
605 if ((s64)reg->umax_value >= 0) {
606 /* Positive. We can't learn anything from the smin, but smax
607 * is positive, hence safe.
608 */
609 reg->smin_value = reg->umin_value;
610 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
611 reg->umax_value);
612 } else if ((s64)reg->umin_value < 0) {
613 /* Negative. We can't learn anything from the smax, but smin
614 * is negative, hence safe.
615 */
616 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
617 reg->umin_value);
618 reg->smax_value = reg->umax_value;
619 }
620}
621
622/* Attempts to improve var_off based on unsigned min/max information */
623static void __reg_bound_offset(struct bpf_reg_state *reg)
624{
625 reg->var_off = tnum_intersect(reg->var_off,
626 tnum_range(reg->umin_value,
627 reg->umax_value));
628}
629
630/* Reset the min/max bounds of a register */
631static void __mark_reg_unbounded(struct bpf_reg_state *reg)
632{
633 reg->smin_value = S64_MIN;
634 reg->smax_value = S64_MAX;
635 reg->umin_value = 0;
636 reg->umax_value = U64_MAX;
637}
638
f1174f77
EC
639/* Mark a register as having a completely unknown (scalar) value. */
640static void __mark_reg_unknown(struct bpf_reg_state *reg)
641{
642 reg->type = SCALAR_VALUE;
643 reg->id = 0;
644 reg->off = 0;
645 reg->var_off = tnum_unknown;
b03c9f9f 646 __mark_reg_unbounded(reg);
f1174f77
EC
647}
648
61bd5218
JK
649static void mark_reg_unknown(struct bpf_verifier_env *env,
650 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
651{
652 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 653 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
f1174f77
EC
654 /* Something bad happened, let's kill all regs */
655 for (regno = 0; regno < MAX_BPF_REG; regno++)
656 __mark_reg_not_init(regs + regno);
657 return;
658 }
659 __mark_reg_unknown(regs + regno);
660}
661
662static void __mark_reg_not_init(struct bpf_reg_state *reg)
663{
664 __mark_reg_unknown(reg);
665 reg->type = NOT_INIT;
666}
667
61bd5218
JK
668static void mark_reg_not_init(struct bpf_verifier_env *env,
669 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
670{
671 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 672 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
f1174f77
EC
673 /* Something bad happened, let's kill all regs */
674 for (regno = 0; regno < MAX_BPF_REG; regno++)
675 __mark_reg_not_init(regs + regno);
676 return;
677 }
678 __mark_reg_not_init(regs + regno);
a9789ef9
DB
679}
680
61bd5218
JK
681static void init_reg_state(struct bpf_verifier_env *env,
682 struct bpf_reg_state *regs)
17a52670
AS
683{
684 int i;
685
dc503a8a 686 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 687 mark_reg_not_init(env, regs, i);
dc503a8a
EC
688 regs[i].live = REG_LIVE_NONE;
689 }
17a52670
AS
690
691 /* frame pointer */
f1174f77 692 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 693 mark_reg_known_zero(env, regs, BPF_REG_FP);
17a52670
AS
694
695 /* 1st arg to a function */
696 regs[BPF_REG_1].type = PTR_TO_CTX;
61bd5218 697 mark_reg_known_zero(env, regs, BPF_REG_1);
6760bf2d
DB
698}
699
17a52670
AS
700enum reg_arg_type {
701 SRC_OP, /* register is used as source operand */
702 DST_OP, /* register is used as destination operand */
703 DST_OP_NO_MARK /* same as above, check only, don't mark */
704};
705
dc503a8a
EC
706static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno)
707{
708 struct bpf_verifier_state *parent = state->parent;
709
8fe2d6cc
AS
710 if (regno == BPF_REG_FP)
711 /* We don't need to worry about FP liveness because it's read-only */
712 return;
713
dc503a8a
EC
714 while (parent) {
715 /* if read wasn't screened by an earlier write ... */
716 if (state->regs[regno].live & REG_LIVE_WRITTEN)
717 break;
718 /* ... then we depend on parent's value */
719 parent->regs[regno].live |= REG_LIVE_READ;
720 state = parent;
721 parent = state->parent;
722 }
723}
724
725static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
726 enum reg_arg_type t)
727{
dc503a8a
EC
728 struct bpf_reg_state *regs = env->cur_state.regs;
729
17a52670 730 if (regno >= MAX_BPF_REG) {
61bd5218 731 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
732 return -EINVAL;
733 }
734
735 if (t == SRC_OP) {
736 /* check whether register used as source operand can be read */
737 if (regs[regno].type == NOT_INIT) {
61bd5218 738 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
739 return -EACCES;
740 }
dc503a8a 741 mark_reg_read(&env->cur_state, regno);
17a52670
AS
742 } else {
743 /* check whether register used as dest operand can be written to */
744 if (regno == BPF_REG_FP) {
61bd5218 745 verbose(env, "frame pointer is read only\n");
17a52670
AS
746 return -EACCES;
747 }
dc503a8a 748 regs[regno].live |= REG_LIVE_WRITTEN;
17a52670 749 if (t == DST_OP)
61bd5218 750 mark_reg_unknown(env, regs, regno);
17a52670
AS
751 }
752 return 0;
753}
754
1be7f75d
AS
755static bool is_spillable_regtype(enum bpf_reg_type type)
756{
757 switch (type) {
758 case PTR_TO_MAP_VALUE:
759 case PTR_TO_MAP_VALUE_OR_NULL:
760 case PTR_TO_STACK:
761 case PTR_TO_CTX:
969bf05e 762 case PTR_TO_PACKET:
de8f3a83 763 case PTR_TO_PACKET_META:
969bf05e 764 case PTR_TO_PACKET_END:
1be7f75d
AS
765 case CONST_PTR_TO_MAP:
766 return true;
767 default:
768 return false;
769 }
770}
771
17a52670
AS
772/* check_stack_read/write functions track spill/fill of registers,
773 * stack boundary and alignment are checked in check_mem_access()
774 */
61bd5218
JK
775static int check_stack_write(struct bpf_verifier_env *env,
776 struct bpf_verifier_state *state, int off,
58e2af8b 777 int size, int value_regno)
17a52670 778{
dc503a8a 779 int i, spi = (MAX_BPF_STACK + off) / BPF_REG_SIZE;
9c399760
AS
780 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
781 * so it's aligned access and [off, off + size) are within stack limits
782 */
17a52670
AS
783
784 if (value_regno >= 0 &&
1be7f75d 785 is_spillable_regtype(state->regs[value_regno].type)) {
17a52670
AS
786
787 /* register containing pointer is being spilled into stack */
9c399760 788 if (size != BPF_REG_SIZE) {
61bd5218 789 verbose(env, "invalid size of register spill\n");
17a52670
AS
790 return -EACCES;
791 }
792
17a52670 793 /* save register state */
dc503a8a
EC
794 state->spilled_regs[spi] = state->regs[value_regno];
795 state->spilled_regs[spi].live |= REG_LIVE_WRITTEN;
17a52670 796
9c399760
AS
797 for (i = 0; i < BPF_REG_SIZE; i++)
798 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
799 } else {
17a52670 800 /* regular write of data into stack */
dc503a8a 801 state->spilled_regs[spi] = (struct bpf_reg_state) {};
9c399760
AS
802
803 for (i = 0; i < size; i++)
804 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
17a52670
AS
805 }
806 return 0;
807}
808
dc503a8a
EC
809static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
810{
811 struct bpf_verifier_state *parent = state->parent;
812
813 while (parent) {
814 /* if read wasn't screened by an earlier write ... */
815 if (state->spilled_regs[slot].live & REG_LIVE_WRITTEN)
816 break;
817 /* ... then we depend on parent's value */
818 parent->spilled_regs[slot].live |= REG_LIVE_READ;
819 state = parent;
820 parent = state->parent;
821 }
822}
823
61bd5218
JK
824static int check_stack_read(struct bpf_verifier_env *env,
825 struct bpf_verifier_state *state, int off, int size,
17a52670
AS
826 int value_regno)
827{
9c399760 828 u8 *slot_type;
dc503a8a 829 int i, spi;
17a52670 830
9c399760 831 slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
17a52670 832
9c399760
AS
833 if (slot_type[0] == STACK_SPILL) {
834 if (size != BPF_REG_SIZE) {
61bd5218 835 verbose(env, "invalid size of register spill\n");
17a52670
AS
836 return -EACCES;
837 }
9c399760
AS
838 for (i = 1; i < BPF_REG_SIZE; i++) {
839 if (slot_type[i] != STACK_SPILL) {
61bd5218 840 verbose(env, "corrupted spill memory\n");
17a52670
AS
841 return -EACCES;
842 }
843 }
844
dc503a8a
EC
845 spi = (MAX_BPF_STACK + off) / BPF_REG_SIZE;
846
847 if (value_regno >= 0) {
17a52670 848 /* restore register state from stack */
dc503a8a
EC
849 state->regs[value_regno] = state->spilled_regs[spi];
850 mark_stack_slot_read(state, spi);
851 }
17a52670
AS
852 return 0;
853 } else {
854 for (i = 0; i < size; i++) {
9c399760 855 if (slot_type[i] != STACK_MISC) {
61bd5218 856 verbose(env, "invalid read from stack off %d+%d size %d\n",
17a52670
AS
857 off, i, size);
858 return -EACCES;
859 }
860 }
861 if (value_regno >= 0)
862 /* have read misc data from the stack */
61bd5218 863 mark_reg_unknown(env, state->regs, value_regno);
17a52670
AS
864 return 0;
865 }
866}
867
868/* check read/write into map element returned by bpf_map_lookup_elem() */
f1174f77 869static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
17a52670
AS
870 int size)
871{
872 struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
873
5722569b 874 if (off < 0 || size <= 0 || off + size > map->value_size) {
61bd5218 875 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
17a52670
AS
876 map->value_size, off, size);
877 return -EACCES;
878 }
879 return 0;
880}
881
f1174f77
EC
882/* check read/write into a map element with possible variable offset */
883static int check_map_access(struct bpf_verifier_env *env, u32 regno,
dbcfe5f7
GB
884 int off, int size)
885{
886 struct bpf_verifier_state *state = &env->cur_state;
887 struct bpf_reg_state *reg = &state->regs[regno];
888 int err;
889
f1174f77
EC
890 /* We may have adjusted the register to this map value, so we
891 * need to try adding each of min_value and max_value to off
892 * to make sure our theoretical access will be safe.
dbcfe5f7 893 */
61bd5218
JK
894 if (env->log.level)
895 print_verifier_state(env, state);
dbcfe5f7
GB
896 /* The minimum value is only important with signed
897 * comparisons where we can't assume the floor of a
898 * value is 0. If we are using signed variables for our
899 * index'es we need to make sure that whatever we use
900 * will have a set floor within our range.
901 */
b03c9f9f 902 if (reg->smin_value < 0) {
61bd5218 903 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
904 regno);
905 return -EACCES;
906 }
b03c9f9f 907 err = __check_map_access(env, regno, reg->smin_value + off, size);
dbcfe5f7 908 if (err) {
61bd5218
JK
909 verbose(env, "R%d min value is outside of the array range\n",
910 regno);
dbcfe5f7
GB
911 return err;
912 }
913
b03c9f9f
EC
914 /* If we haven't set a max value then we need to bail since we can't be
915 * sure we won't do bad things.
916 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 917 */
b03c9f9f 918 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
61bd5218 919 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
dbcfe5f7
GB
920 regno);
921 return -EACCES;
922 }
b03c9f9f 923 err = __check_map_access(env, regno, reg->umax_value + off, size);
f1174f77 924 if (err)
61bd5218
JK
925 verbose(env, "R%d max value is outside of the array range\n",
926 regno);
f1174f77 927 return err;
dbcfe5f7
GB
928}
929
969bf05e
AS
930#define MAX_PACKET_OFF 0xffff
931
58e2af8b 932static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
933 const struct bpf_call_arg_meta *meta,
934 enum bpf_access_type t)
4acf6c0b 935{
36bbef52 936 switch (env->prog->type) {
3a0af8fd
TG
937 case BPF_PROG_TYPE_LWT_IN:
938 case BPF_PROG_TYPE_LWT_OUT:
939 /* dst_input() and dst_output() can't write for now */
940 if (t == BPF_WRITE)
941 return false;
7e57fbb2 942 /* fallthrough */
36bbef52
DB
943 case BPF_PROG_TYPE_SCHED_CLS:
944 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 945 case BPF_PROG_TYPE_XDP:
3a0af8fd 946 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 947 case BPF_PROG_TYPE_SK_SKB:
36bbef52
DB
948 if (meta)
949 return meta->pkt_access;
950
951 env->seen_direct_write = true;
4acf6c0b
BB
952 return true;
953 default:
954 return false;
955 }
956}
957
f1174f77
EC
958static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
959 int off, int size)
969bf05e 960{
58e2af8b
JK
961 struct bpf_reg_state *regs = env->cur_state.regs;
962 struct bpf_reg_state *reg = &regs[regno];
969bf05e 963
f1174f77 964 if (off < 0 || size <= 0 || (u64)off + size > reg->range) {
61bd5218 965 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
d91b28ed 966 off, size, regno, reg->id, reg->off, reg->range);
969bf05e
AS
967 return -EACCES;
968 }
969 return 0;
970}
971
f1174f77
EC
972static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
973 int size)
974{
975 struct bpf_reg_state *regs = env->cur_state.regs;
976 struct bpf_reg_state *reg = &regs[regno];
977 int err;
978
979 /* We may have added a variable offset to the packet pointer; but any
980 * reg->range we have comes after that. We are only checking the fixed
981 * offset.
982 */
983
984 /* We don't allow negative numbers, because we aren't tracking enough
985 * detail to prove they're safe.
986 */
b03c9f9f 987 if (reg->smin_value < 0) {
61bd5218 988 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
989 regno);
990 return -EACCES;
991 }
992 err = __check_packet_access(env, regno, off, size);
993 if (err) {
61bd5218 994 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
995 return err;
996 }
997 return err;
998}
999
1000/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 1001static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
19de99f7 1002 enum bpf_access_type t, enum bpf_reg_type *reg_type)
17a52670 1003{
f96da094
DB
1004 struct bpf_insn_access_aux info = {
1005 .reg_type = *reg_type,
1006 };
31fd8581 1007
13a27dfc
JK
1008 /* for analyzer ctx accesses are already validated and converted */
1009 if (env->analyzer_ops)
1010 return 0;
1011
17a52670 1012 if (env->prog->aux->ops->is_valid_access &&
23994631 1013 env->prog->aux->ops->is_valid_access(off, size, t, &info)) {
f96da094
DB
1014 /* A non zero info.ctx_field_size indicates that this field is a
1015 * candidate for later verifier transformation to load the whole
1016 * field and then apply a mask when accessed with a narrower
1017 * access than actual ctx access size. A zero info.ctx_field_size
1018 * will only allow for whole field access and rejects any other
1019 * type of narrower access.
31fd8581 1020 */
f96da094 1021 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
23994631 1022 *reg_type = info.reg_type;
31fd8581 1023
32bbe007
AS
1024 /* remember the offset of last byte accessed in ctx */
1025 if (env->prog->aux->max_ctx_offset < off + size)
1026 env->prog->aux->max_ctx_offset = off + size;
17a52670 1027 return 0;
32bbe007 1028 }
17a52670 1029
61bd5218 1030 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
1031 return -EACCES;
1032}
1033
4cabc5b1
DB
1034static bool __is_pointer_value(bool allow_ptr_leaks,
1035 const struct bpf_reg_state *reg)
1be7f75d 1036{
4cabc5b1 1037 if (allow_ptr_leaks)
1be7f75d
AS
1038 return false;
1039
f1174f77 1040 return reg->type != SCALAR_VALUE;
1be7f75d
AS
1041}
1042
4cabc5b1
DB
1043static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1044{
1045 return __is_pointer_value(env->allow_ptr_leaks, &env->cur_state.regs[regno]);
1046}
1047
61bd5218
JK
1048static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1049 const struct bpf_reg_state *reg,
d1174416 1050 int off, int size, bool strict)
969bf05e 1051{
f1174f77 1052 struct tnum reg_off;
e07b98d9 1053 int ip_align;
d1174416
DM
1054
1055 /* Byte size accesses are always allowed. */
1056 if (!strict || size == 1)
1057 return 0;
1058
e4eda884
DM
1059 /* For platforms that do not have a Kconfig enabling
1060 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1061 * NET_IP_ALIGN is universally set to '2'. And on platforms
1062 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1063 * to this code only in strict mode where we want to emulate
1064 * the NET_IP_ALIGN==2 checking. Therefore use an
1065 * unconditional IP align value of '2'.
e07b98d9 1066 */
e4eda884 1067 ip_align = 2;
f1174f77
EC
1068
1069 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1070 if (!tnum_is_aligned(reg_off, size)) {
1071 char tn_buf[48];
1072
1073 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
1074 verbose(env,
1075 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 1076 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
1077 return -EACCES;
1078 }
79adffcd 1079
969bf05e
AS
1080 return 0;
1081}
1082
61bd5218
JK
1083static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1084 const struct bpf_reg_state *reg,
f1174f77
EC
1085 const char *pointer_desc,
1086 int off, int size, bool strict)
79adffcd 1087{
f1174f77
EC
1088 struct tnum reg_off;
1089
1090 /* Byte size accesses are always allowed. */
1091 if (!strict || size == 1)
1092 return 0;
1093
1094 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1095 if (!tnum_is_aligned(reg_off, size)) {
1096 char tn_buf[48];
1097
1098 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 1099 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 1100 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
1101 return -EACCES;
1102 }
1103
969bf05e
AS
1104 return 0;
1105}
1106
e07b98d9
DM
1107static int check_ptr_alignment(struct bpf_verifier_env *env,
1108 const struct bpf_reg_state *reg,
79adffcd
DB
1109 int off, int size)
1110{
e07b98d9 1111 bool strict = env->strict_alignment;
f1174f77 1112 const char *pointer_desc = "";
d1174416 1113
79adffcd
DB
1114 switch (reg->type) {
1115 case PTR_TO_PACKET:
de8f3a83
DB
1116 case PTR_TO_PACKET_META:
1117 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1118 * right in front, treat it the very same way.
1119 */
61bd5218 1120 return check_pkt_ptr_alignment(env, reg, off, size, strict);
f1174f77
EC
1121 case PTR_TO_MAP_VALUE:
1122 pointer_desc = "value ";
1123 break;
1124 case PTR_TO_CTX:
1125 pointer_desc = "context ";
1126 break;
1127 case PTR_TO_STACK:
1128 pointer_desc = "stack ";
1129 break;
79adffcd 1130 default:
f1174f77 1131 break;
79adffcd 1132 }
61bd5218
JK
1133 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1134 strict);
79adffcd
DB
1135}
1136
17a52670
AS
1137/* check whether memory at (regno + off) is accessible for t = (read | write)
1138 * if t==write, value_regno is a register which value is stored into memory
1139 * if t==read, value_regno is a register which will receive the value from memory
1140 * if t==write && value_regno==-1, some unknown value is stored into memory
1141 * if t==read && value_regno==-1, don't care what we read from memory
1142 */
31fd8581 1143static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
17a52670
AS
1144 int bpf_size, enum bpf_access_type t,
1145 int value_regno)
1146{
58e2af8b
JK
1147 struct bpf_verifier_state *state = &env->cur_state;
1148 struct bpf_reg_state *reg = &state->regs[regno];
17a52670
AS
1149 int size, err = 0;
1150
1151 size = bpf_size_to_bytes(bpf_size);
1152 if (size < 0)
1153 return size;
1154
f1174f77 1155 /* alignment checks will add in reg->off themselves */
e07b98d9 1156 err = check_ptr_alignment(env, reg, off, size);
969bf05e
AS
1157 if (err)
1158 return err;
17a52670 1159
f1174f77
EC
1160 /* for access checks, reg->off is just part of off */
1161 off += reg->off;
1162
1163 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
1164 if (t == BPF_WRITE && value_regno >= 0 &&
1165 is_pointer_value(env, value_regno)) {
61bd5218 1166 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
1167 return -EACCES;
1168 }
48461135 1169
f1174f77 1170 err = check_map_access(env, regno, off, size);
17a52670 1171 if (!err && t == BPF_READ && value_regno >= 0)
61bd5218 1172 mark_reg_unknown(env, state->regs, value_regno);
17a52670 1173
1a0dc1ac 1174 } else if (reg->type == PTR_TO_CTX) {
f1174f77 1175 enum bpf_reg_type reg_type = SCALAR_VALUE;
19de99f7 1176
1be7f75d
AS
1177 if (t == BPF_WRITE && value_regno >= 0 &&
1178 is_pointer_value(env, value_regno)) {
61bd5218 1179 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
1180 return -EACCES;
1181 }
f1174f77
EC
1182 /* ctx accesses must be at a fixed offset, so that we can
1183 * determine what type of data were returned.
1184 */
1185 if (!tnum_is_const(reg->var_off)) {
1186 char tn_buf[48];
1187
1188 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
1189 verbose(env,
1190 "variable ctx access var_off=%s off=%d size=%d",
f1174f77
EC
1191 tn_buf, off, size);
1192 return -EACCES;
1193 }
1194 off += reg->var_off.value;
31fd8581 1195 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
969bf05e 1196 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 1197 /* ctx access returns either a scalar, or a
de8f3a83
DB
1198 * PTR_TO_PACKET[_META,_END]. In the latter
1199 * case, we know the offset is zero.
f1174f77
EC
1200 */
1201 if (reg_type == SCALAR_VALUE)
61bd5218 1202 mark_reg_unknown(env, state->regs, value_regno);
f1174f77 1203 else
61bd5218
JK
1204 mark_reg_known_zero(env, state->regs,
1205 value_regno);
f1174f77
EC
1206 state->regs[value_regno].id = 0;
1207 state->regs[value_regno].off = 0;
1208 state->regs[value_regno].range = 0;
1955351d 1209 state->regs[value_regno].type = reg_type;
969bf05e 1210 }
17a52670 1211
f1174f77
EC
1212 } else if (reg->type == PTR_TO_STACK) {
1213 /* stack accesses must be at a fixed offset, so that we can
1214 * determine what type of data were returned.
1215 * See check_stack_read().
1216 */
1217 if (!tnum_is_const(reg->var_off)) {
1218 char tn_buf[48];
1219
1220 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 1221 verbose(env, "variable stack access var_off=%s off=%d size=%d",
f1174f77
EC
1222 tn_buf, off, size);
1223 return -EACCES;
1224 }
1225 off += reg->var_off.value;
17a52670 1226 if (off >= 0 || off < -MAX_BPF_STACK) {
61bd5218
JK
1227 verbose(env, "invalid stack off=%d size=%d\n", off,
1228 size);
17a52670
AS
1229 return -EACCES;
1230 }
8726679a
AS
1231
1232 if (env->prog->aux->stack_depth < -off)
1233 env->prog->aux->stack_depth = -off;
1234
1be7f75d
AS
1235 if (t == BPF_WRITE) {
1236 if (!env->allow_ptr_leaks &&
1237 state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
1238 size != BPF_REG_SIZE) {
61bd5218 1239 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1be7f75d
AS
1240 return -EACCES;
1241 }
61bd5218
JK
1242 err = check_stack_write(env, state, off, size,
1243 value_regno);
1be7f75d 1244 } else {
61bd5218
JK
1245 err = check_stack_read(env, state, off, size,
1246 value_regno);
1be7f75d 1247 }
de8f3a83 1248 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 1249 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 1250 verbose(env, "cannot write into packet\n");
969bf05e
AS
1251 return -EACCES;
1252 }
4acf6c0b
BB
1253 if (t == BPF_WRITE && value_regno >= 0 &&
1254 is_pointer_value(env, value_regno)) {
61bd5218
JK
1255 verbose(env, "R%d leaks addr into packet\n",
1256 value_regno);
4acf6c0b
BB
1257 return -EACCES;
1258 }
969bf05e
AS
1259 err = check_packet_access(env, regno, off, size);
1260 if (!err && t == BPF_READ && value_regno >= 0)
61bd5218 1261 mark_reg_unknown(env, state->regs, value_regno);
17a52670 1262 } else {
61bd5218
JK
1263 verbose(env, "R%d invalid mem access '%s'\n", regno,
1264 reg_type_str[reg->type]);
17a52670
AS
1265 return -EACCES;
1266 }
969bf05e 1267
f1174f77
EC
1268 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1269 state->regs[value_regno].type == SCALAR_VALUE) {
1270 /* b/h/w load zero-extends, mark upper bits as known 0 */
1271 state->regs[value_regno].var_off = tnum_cast(
1272 state->regs[value_regno].var_off, size);
b03c9f9f 1273 __update_reg_bounds(&state->regs[value_regno]);
969bf05e 1274 }
17a52670
AS
1275 return err;
1276}
1277
31fd8581 1278static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 1279{
17a52670
AS
1280 int err;
1281
1282 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1283 insn->imm != 0) {
61bd5218 1284 verbose(env, "BPF_XADD uses reserved fields\n");
17a52670
AS
1285 return -EINVAL;
1286 }
1287
1288 /* check src1 operand */
dc503a8a 1289 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
1290 if (err)
1291 return err;
1292
1293 /* check src2 operand */
dc503a8a 1294 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
1295 if (err)
1296 return err;
1297
6bdf6abc 1298 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 1299 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
1300 return -EACCES;
1301 }
1302
17a52670 1303 /* check whether atomic_add can read the memory */
31fd8581 1304 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
17a52670
AS
1305 BPF_SIZE(insn->code), BPF_READ, -1);
1306 if (err)
1307 return err;
1308
1309 /* check whether atomic_add can write into the same memory */
31fd8581 1310 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
17a52670
AS
1311 BPF_SIZE(insn->code), BPF_WRITE, -1);
1312}
1313
f1174f77
EC
1314/* Does this register contain a constant zero? */
1315static bool register_is_null(struct bpf_reg_state reg)
1316{
1317 return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
1318}
1319
17a52670
AS
1320/* when register 'regno' is passed into function that will read 'access_size'
1321 * bytes from that pointer, make sure that it's within stack boundary
f1174f77
EC
1322 * and all elements of stack are initialized.
1323 * Unlike most pointer bounds-checking functions, this one doesn't take an
1324 * 'off' argument, so it has to add in reg->off itself.
17a52670 1325 */
58e2af8b 1326static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
1327 int access_size, bool zero_size_allowed,
1328 struct bpf_call_arg_meta *meta)
17a52670 1329{
58e2af8b
JK
1330 struct bpf_verifier_state *state = &env->cur_state;
1331 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1332 int off, i;
1333
8e2fe1d9 1334 if (regs[regno].type != PTR_TO_STACK) {
f1174f77 1335 /* Allow zero-byte read from NULL, regardless of pointer type */
8e2fe1d9 1336 if (zero_size_allowed && access_size == 0 &&
f1174f77 1337 register_is_null(regs[regno]))
8e2fe1d9
DB
1338 return 0;
1339
61bd5218 1340 verbose(env, "R%d type=%s expected=%s\n", regno,
8e2fe1d9
DB
1341 reg_type_str[regs[regno].type],
1342 reg_type_str[PTR_TO_STACK]);
17a52670 1343 return -EACCES;
8e2fe1d9 1344 }
17a52670 1345
f1174f77
EC
1346 /* Only allow fixed-offset stack reads */
1347 if (!tnum_is_const(regs[regno].var_off)) {
1348 char tn_buf[48];
1349
1350 tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
61bd5218 1351 verbose(env, "invalid variable stack read R%d var_off=%s\n",
f1174f77
EC
1352 regno, tn_buf);
1353 }
1354 off = regs[regno].off + regs[regno].var_off.value;
17a52670
AS
1355 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1356 access_size <= 0) {
61bd5218 1357 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
17a52670
AS
1358 regno, off, access_size);
1359 return -EACCES;
1360 }
1361
8726679a
AS
1362 if (env->prog->aux->stack_depth < -off)
1363 env->prog->aux->stack_depth = -off;
1364
435faee1
DB
1365 if (meta && meta->raw_mode) {
1366 meta->access_size = access_size;
1367 meta->regno = regno;
1368 return 0;
1369 }
1370
17a52670 1371 for (i = 0; i < access_size; i++) {
9c399760 1372 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
61bd5218 1373 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
17a52670
AS
1374 off, i, access_size);
1375 return -EACCES;
1376 }
1377 }
1378 return 0;
1379}
1380
06c1c049
GB
1381static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1382 int access_size, bool zero_size_allowed,
1383 struct bpf_call_arg_meta *meta)
1384{
f1174f77 1385 struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
06c1c049 1386
f1174f77 1387 switch (reg->type) {
06c1c049 1388 case PTR_TO_PACKET:
de8f3a83 1389 case PTR_TO_PACKET_META:
f1174f77 1390 return check_packet_access(env, regno, reg->off, access_size);
06c1c049 1391 case PTR_TO_MAP_VALUE:
f1174f77
EC
1392 return check_map_access(env, regno, reg->off, access_size);
1393 default: /* scalar_value|ptr_to_stack or invalid ptr */
06c1c049
GB
1394 return check_stack_boundary(env, regno, access_size,
1395 zero_size_allowed, meta);
1396 }
1397}
1398
58e2af8b 1399static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
33ff9823
DB
1400 enum bpf_arg_type arg_type,
1401 struct bpf_call_arg_meta *meta)
17a52670 1402{
58e2af8b 1403 struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
6841de8b 1404 enum bpf_reg_type expected_type, type = reg->type;
17a52670
AS
1405 int err = 0;
1406
80f1d68c 1407 if (arg_type == ARG_DONTCARE)
17a52670
AS
1408 return 0;
1409
dc503a8a
EC
1410 err = check_reg_arg(env, regno, SRC_OP);
1411 if (err)
1412 return err;
17a52670 1413
1be7f75d
AS
1414 if (arg_type == ARG_ANYTHING) {
1415 if (is_pointer_value(env, regno)) {
61bd5218
JK
1416 verbose(env, "R%d leaks addr into helper function\n",
1417 regno);
1be7f75d
AS
1418 return -EACCES;
1419 }
80f1d68c 1420 return 0;
1be7f75d 1421 }
80f1d68c 1422
de8f3a83 1423 if (type_is_pkt_pointer(type) &&
3a0af8fd 1424 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 1425 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
1426 return -EACCES;
1427 }
1428
8e2fe1d9 1429 if (arg_type == ARG_PTR_TO_MAP_KEY ||
17a52670
AS
1430 arg_type == ARG_PTR_TO_MAP_VALUE) {
1431 expected_type = PTR_TO_STACK;
de8f3a83
DB
1432 if (!type_is_pkt_pointer(type) &&
1433 type != expected_type)
6841de8b 1434 goto err_type;
39f19ebb
AS
1435 } else if (arg_type == ARG_CONST_SIZE ||
1436 arg_type == ARG_CONST_SIZE_OR_ZERO) {
f1174f77
EC
1437 expected_type = SCALAR_VALUE;
1438 if (type != expected_type)
6841de8b 1439 goto err_type;
17a52670
AS
1440 } else if (arg_type == ARG_CONST_MAP_PTR) {
1441 expected_type = CONST_PTR_TO_MAP;
6841de8b
AS
1442 if (type != expected_type)
1443 goto err_type;
608cd71a
AS
1444 } else if (arg_type == ARG_PTR_TO_CTX) {
1445 expected_type = PTR_TO_CTX;
6841de8b
AS
1446 if (type != expected_type)
1447 goto err_type;
39f19ebb
AS
1448 } else if (arg_type == ARG_PTR_TO_MEM ||
1449 arg_type == ARG_PTR_TO_UNINIT_MEM) {
8e2fe1d9
DB
1450 expected_type = PTR_TO_STACK;
1451 /* One exception here. In case function allows for NULL to be
f1174f77 1452 * passed in as argument, it's a SCALAR_VALUE type. Final test
8e2fe1d9
DB
1453 * happens during stack boundary checking.
1454 */
f1174f77 1455 if (register_is_null(*reg))
6841de8b 1456 /* final test in check_stack_boundary() */;
de8f3a83
DB
1457 else if (!type_is_pkt_pointer(type) &&
1458 type != PTR_TO_MAP_VALUE &&
f1174f77 1459 type != expected_type)
6841de8b 1460 goto err_type;
39f19ebb 1461 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
17a52670 1462 } else {
61bd5218 1463 verbose(env, "unsupported arg_type %d\n", arg_type);
17a52670
AS
1464 return -EFAULT;
1465 }
1466
17a52670
AS
1467 if (arg_type == ARG_CONST_MAP_PTR) {
1468 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 1469 meta->map_ptr = reg->map_ptr;
17a52670
AS
1470 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1471 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1472 * check that [key, key + map->key_size) are within
1473 * stack limits and initialized
1474 */
33ff9823 1475 if (!meta->map_ptr) {
17a52670
AS
1476 /* in function declaration map_ptr must come before
1477 * map_key, so that it's verified and known before
1478 * we have to check map_key here. Otherwise it means
1479 * that kernel subsystem misconfigured verifier
1480 */
61bd5218 1481 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
1482 return -EACCES;
1483 }
de8f3a83 1484 if (type_is_pkt_pointer(type))
f1174f77 1485 err = check_packet_access(env, regno, reg->off,
6841de8b
AS
1486 meta->map_ptr->key_size);
1487 else
1488 err = check_stack_boundary(env, regno,
1489 meta->map_ptr->key_size,
1490 false, NULL);
17a52670
AS
1491 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1492 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1493 * check [value, value + map->value_size) validity
1494 */
33ff9823 1495 if (!meta->map_ptr) {
17a52670 1496 /* kernel subsystem misconfigured verifier */
61bd5218 1497 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
1498 return -EACCES;
1499 }
de8f3a83 1500 if (type_is_pkt_pointer(type))
f1174f77 1501 err = check_packet_access(env, regno, reg->off,
6841de8b
AS
1502 meta->map_ptr->value_size);
1503 else
1504 err = check_stack_boundary(env, regno,
1505 meta->map_ptr->value_size,
1506 false, NULL);
39f19ebb
AS
1507 } else if (arg_type == ARG_CONST_SIZE ||
1508 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1509 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 1510
17a52670
AS
1511 /* bpf_xxx(..., buf, len) call will access 'len' bytes
1512 * from stack pointer 'buf'. Check it
1513 * note: regno == len, regno - 1 == buf
1514 */
1515 if (regno == 0) {
1516 /* kernel subsystem misconfigured verifier */
61bd5218
JK
1517 verbose(env,
1518 "ARG_CONST_SIZE cannot be first argument\n");
17a52670
AS
1519 return -EACCES;
1520 }
06c1c049 1521
f1174f77
EC
1522 /* The register is SCALAR_VALUE; the access check
1523 * happens using its boundaries.
06c1c049 1524 */
f1174f77
EC
1525
1526 if (!tnum_is_const(reg->var_off))
06c1c049
GB
1527 /* For unprivileged variable accesses, disable raw
1528 * mode so that the program is required to
1529 * initialize all the memory that the helper could
1530 * just partially fill up.
1531 */
1532 meta = NULL;
1533
b03c9f9f 1534 if (reg->smin_value < 0) {
61bd5218 1535 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
1536 regno);
1537 return -EACCES;
1538 }
06c1c049 1539
b03c9f9f 1540 if (reg->umin_value == 0) {
f1174f77
EC
1541 err = check_helper_mem_access(env, regno - 1, 0,
1542 zero_size_allowed,
1543 meta);
06c1c049
GB
1544 if (err)
1545 return err;
06c1c049 1546 }
f1174f77 1547
b03c9f9f 1548 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 1549 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
1550 regno);
1551 return -EACCES;
1552 }
1553 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 1554 reg->umax_value,
f1174f77 1555 zero_size_allowed, meta);
17a52670
AS
1556 }
1557
1558 return err;
6841de8b 1559err_type:
61bd5218 1560 verbose(env, "R%d type=%s expected=%s\n", regno,
6841de8b
AS
1561 reg_type_str[type], reg_type_str[expected_type]);
1562 return -EACCES;
17a52670
AS
1563}
1564
61bd5218
JK
1565static int check_map_func_compatibility(struct bpf_verifier_env *env,
1566 struct bpf_map *map, int func_id)
35578d79 1567{
35578d79
KX
1568 if (!map)
1569 return 0;
1570
6aff67c8
AS
1571 /* We need a two way check, first is from map perspective ... */
1572 switch (map->map_type) {
1573 case BPF_MAP_TYPE_PROG_ARRAY:
1574 if (func_id != BPF_FUNC_tail_call)
1575 goto error;
1576 break;
1577 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1578 if (func_id != BPF_FUNC_perf_event_read &&
908432ca
YS
1579 func_id != BPF_FUNC_perf_event_output &&
1580 func_id != BPF_FUNC_perf_event_read_value)
6aff67c8
AS
1581 goto error;
1582 break;
1583 case BPF_MAP_TYPE_STACK_TRACE:
1584 if (func_id != BPF_FUNC_get_stackid)
1585 goto error;
1586 break;
4ed8ec52 1587 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 1588 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 1589 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
1590 goto error;
1591 break;
546ac1ff
JF
1592 /* devmap returns a pointer to a live net_device ifindex that we cannot
1593 * allow to be modified from bpf side. So do not allow lookup elements
1594 * for now.
1595 */
1596 case BPF_MAP_TYPE_DEVMAP:
2ddf71e2 1597 if (func_id != BPF_FUNC_redirect_map)
546ac1ff
JF
1598 goto error;
1599 break;
56f668df 1600 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 1601 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
1602 if (func_id != BPF_FUNC_map_lookup_elem)
1603 goto error;
16a43625 1604 break;
174a79ff
JF
1605 case BPF_MAP_TYPE_SOCKMAP:
1606 if (func_id != BPF_FUNC_sk_redirect_map &&
1607 func_id != BPF_FUNC_sock_map_update &&
1608 func_id != BPF_FUNC_map_delete_elem)
1609 goto error;
1610 break;
6aff67c8
AS
1611 default:
1612 break;
1613 }
1614
1615 /* ... and second from the function itself. */
1616 switch (func_id) {
1617 case BPF_FUNC_tail_call:
1618 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1619 goto error;
1620 break;
1621 case BPF_FUNC_perf_event_read:
1622 case BPF_FUNC_perf_event_output:
908432ca 1623 case BPF_FUNC_perf_event_read_value:
6aff67c8
AS
1624 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1625 goto error;
1626 break;
1627 case BPF_FUNC_get_stackid:
1628 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1629 goto error;
1630 break;
60d20f91 1631 case BPF_FUNC_current_task_under_cgroup:
747ea55e 1632 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
1633 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1634 goto error;
1635 break;
97f91a7c
JF
1636 case BPF_FUNC_redirect_map:
1637 if (map->map_type != BPF_MAP_TYPE_DEVMAP)
1638 goto error;
1639 break;
174a79ff
JF
1640 case BPF_FUNC_sk_redirect_map:
1641 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
1642 goto error;
1643 break;
1644 case BPF_FUNC_sock_map_update:
1645 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
1646 goto error;
1647 break;
6aff67c8
AS
1648 default:
1649 break;
35578d79
KX
1650 }
1651
1652 return 0;
6aff67c8 1653error:
61bd5218 1654 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 1655 map->map_type, func_id_name(func_id), func_id);
6aff67c8 1656 return -EINVAL;
35578d79
KX
1657}
1658
435faee1
DB
1659static int check_raw_mode(const struct bpf_func_proto *fn)
1660{
1661 int count = 0;
1662
39f19ebb 1663 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1664 count++;
39f19ebb 1665 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1666 count++;
39f19ebb 1667 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1668 count++;
39f19ebb 1669 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1670 count++;
39f19ebb 1671 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
1672 count++;
1673
1674 return count > 1 ? -EINVAL : 0;
1675}
1676
de8f3a83
DB
1677/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
1678 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 1679 */
58e2af8b 1680static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
969bf05e 1681{
58e2af8b
JK
1682 struct bpf_verifier_state *state = &env->cur_state;
1683 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
1684 int i;
1685
1686 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 1687 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 1688 mark_reg_unknown(env, regs, i);
969bf05e
AS
1689
1690 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1691 if (state->stack_slot_type[i] != STACK_SPILL)
1692 continue;
1693 reg = &state->spilled_regs[i / BPF_REG_SIZE];
de8f3a83
DB
1694 if (reg_is_pkt_pointer_any(reg))
1695 __mark_reg_unknown(reg);
969bf05e
AS
1696 }
1697}
1698
81ed18ab 1699static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 1700{
58e2af8b 1701 struct bpf_verifier_state *state = &env->cur_state;
17a52670 1702 const struct bpf_func_proto *fn = NULL;
58e2af8b 1703 struct bpf_reg_state *regs = state->regs;
33ff9823 1704 struct bpf_call_arg_meta meta;
969bf05e 1705 bool changes_data;
17a52670
AS
1706 int i, err;
1707
1708 /* find function prototype */
1709 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
1710 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
1711 func_id);
17a52670
AS
1712 return -EINVAL;
1713 }
1714
1715 if (env->prog->aux->ops->get_func_proto)
1716 fn = env->prog->aux->ops->get_func_proto(func_id);
1717
1718 if (!fn) {
61bd5218
JK
1719 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
1720 func_id);
17a52670
AS
1721 return -EINVAL;
1722 }
1723
1724 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 1725 if (!env->prog->gpl_compatible && fn->gpl_only) {
61bd5218 1726 verbose(env, "cannot call GPL only function from proprietary program\n");
17a52670
AS
1727 return -EINVAL;
1728 }
1729
17bedab2 1730 changes_data = bpf_helper_changes_pkt_data(fn->func);
969bf05e 1731
33ff9823 1732 memset(&meta, 0, sizeof(meta));
36bbef52 1733 meta.pkt_access = fn->pkt_access;
33ff9823 1734
435faee1
DB
1735 /* We only support one arg being in raw mode at the moment, which
1736 * is sufficient for the helper functions we have right now.
1737 */
1738 err = check_raw_mode(fn);
1739 if (err) {
61bd5218 1740 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 1741 func_id_name(func_id), func_id);
435faee1
DB
1742 return err;
1743 }
1744
17a52670 1745 /* check args */
33ff9823 1746 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
17a52670
AS
1747 if (err)
1748 return err;
33ff9823 1749 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
17a52670
AS
1750 if (err)
1751 return err;
33ff9823 1752 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
17a52670
AS
1753 if (err)
1754 return err;
33ff9823 1755 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
17a52670
AS
1756 if (err)
1757 return err;
33ff9823 1758 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
17a52670
AS
1759 if (err)
1760 return err;
1761
435faee1
DB
1762 /* Mark slots with STACK_MISC in case of raw mode, stack offset
1763 * is inferred from register state.
1764 */
1765 for (i = 0; i < meta.access_size; i++) {
31fd8581 1766 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
435faee1
DB
1767 if (err)
1768 return err;
1769 }
1770
17a52670 1771 /* reset caller saved regs */
dc503a8a 1772 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 1773 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
1774 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
1775 }
17a52670 1776
dc503a8a 1777 /* update return register (already marked as written above) */
17a52670 1778 if (fn->ret_type == RET_INTEGER) {
f1174f77 1779 /* sets type to SCALAR_VALUE */
61bd5218 1780 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
1781 } else if (fn->ret_type == RET_VOID) {
1782 regs[BPF_REG_0].type = NOT_INIT;
1783 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
fad73a1a
MKL
1784 struct bpf_insn_aux_data *insn_aux;
1785
17a52670 1786 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
f1174f77 1787 /* There is no offset yet applied, variable or fixed */
61bd5218 1788 mark_reg_known_zero(env, regs, BPF_REG_0);
f1174f77 1789 regs[BPF_REG_0].off = 0;
17a52670
AS
1790 /* remember map_ptr, so that check_map_access()
1791 * can check 'value_size' boundary of memory access
1792 * to map element returned from bpf_map_lookup_elem()
1793 */
33ff9823 1794 if (meta.map_ptr == NULL) {
61bd5218
JK
1795 verbose(env,
1796 "kernel subsystem misconfigured verifier\n");
17a52670
AS
1797 return -EINVAL;
1798 }
33ff9823 1799 regs[BPF_REG_0].map_ptr = meta.map_ptr;
57a09bf0 1800 regs[BPF_REG_0].id = ++env->id_gen;
fad73a1a
MKL
1801 insn_aux = &env->insn_aux_data[insn_idx];
1802 if (!insn_aux->map_ptr)
1803 insn_aux->map_ptr = meta.map_ptr;
1804 else if (insn_aux->map_ptr != meta.map_ptr)
1805 insn_aux->map_ptr = BPF_MAP_PTR_POISON;
17a52670 1806 } else {
61bd5218 1807 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 1808 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
1809 return -EINVAL;
1810 }
04fd61ab 1811
61bd5218 1812 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
1813 if (err)
1814 return err;
04fd61ab 1815
969bf05e
AS
1816 if (changes_data)
1817 clear_all_pkt_pointers(env);
1818 return 0;
1819}
1820
f1174f77
EC
1821static void coerce_reg_to_32(struct bpf_reg_state *reg)
1822{
f1174f77
EC
1823 /* clear high 32 bits */
1824 reg->var_off = tnum_cast(reg->var_off, 4);
b03c9f9f
EC
1825 /* Update bounds */
1826 __update_reg_bounds(reg);
1827}
1828
1829static bool signed_add_overflows(s64 a, s64 b)
1830{
1831 /* Do the add in u64, where overflow is well-defined */
1832 s64 res = (s64)((u64)a + (u64)b);
1833
1834 if (b < 0)
1835 return res > a;
1836 return res < a;
1837}
1838
1839static bool signed_sub_overflows(s64 a, s64 b)
1840{
1841 /* Do the sub in u64, where overflow is well-defined */
1842 s64 res = (s64)((u64)a - (u64)b);
1843
1844 if (b < 0)
1845 return res < a;
1846 return res > a;
969bf05e
AS
1847}
1848
f1174f77 1849/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
1850 * Caller should also handle BPF_MOV case separately.
1851 * If we return -EACCES, caller may want to try again treating pointer as a
1852 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
1853 */
1854static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
1855 struct bpf_insn *insn,
1856 const struct bpf_reg_state *ptr_reg,
1857 const struct bpf_reg_state *off_reg)
969bf05e 1858{
f1174f77
EC
1859 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1860 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
1861 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
1862 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
1863 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
1864 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
969bf05e 1865 u8 opcode = BPF_OP(insn->code);
f1174f77 1866 u32 dst = insn->dst_reg;
969bf05e 1867
f1174f77 1868 dst_reg = &regs[dst];
969bf05e 1869
b03c9f9f 1870 if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
61bd5218
JK
1871 print_verifier_state(env, &env->cur_state);
1872 verbose(env,
1873 "verifier internal error: known but bad sbounds\n");
b03c9f9f
EC
1874 return -EINVAL;
1875 }
1876 if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
61bd5218
JK
1877 print_verifier_state(env, &env->cur_state);
1878 verbose(env,
1879 "verifier internal error: known but bad ubounds\n");
f1174f77
EC
1880 return -EINVAL;
1881 }
1882
1883 if (BPF_CLASS(insn->code) != BPF_ALU64) {
1884 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
1885 if (!env->allow_ptr_leaks)
61bd5218
JK
1886 verbose(env,
1887 "R%d 32-bit pointer arithmetic prohibited\n",
f1174f77
EC
1888 dst);
1889 return -EACCES;
969bf05e
AS
1890 }
1891
f1174f77
EC
1892 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
1893 if (!env->allow_ptr_leaks)
61bd5218 1894 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
f1174f77
EC
1895 dst);
1896 return -EACCES;
1897 }
1898 if (ptr_reg->type == CONST_PTR_TO_MAP) {
1899 if (!env->allow_ptr_leaks)
61bd5218 1900 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
f1174f77
EC
1901 dst);
1902 return -EACCES;
1903 }
1904 if (ptr_reg->type == PTR_TO_PACKET_END) {
1905 if (!env->allow_ptr_leaks)
61bd5218 1906 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
f1174f77
EC
1907 dst);
1908 return -EACCES;
1909 }
1910
1911 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
1912 * The id may be overwritten later if we create a new variable offset.
969bf05e 1913 */
f1174f77
EC
1914 dst_reg->type = ptr_reg->type;
1915 dst_reg->id = ptr_reg->id;
969bf05e 1916
f1174f77
EC
1917 switch (opcode) {
1918 case BPF_ADD:
1919 /* We can take a fixed offset as long as it doesn't overflow
1920 * the s32 'off' field
969bf05e 1921 */
b03c9f9f
EC
1922 if (known && (ptr_reg->off + smin_val ==
1923 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 1924 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
1925 dst_reg->smin_value = smin_ptr;
1926 dst_reg->smax_value = smax_ptr;
1927 dst_reg->umin_value = umin_ptr;
1928 dst_reg->umax_value = umax_ptr;
f1174f77 1929 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 1930 dst_reg->off = ptr_reg->off + smin_val;
f1174f77
EC
1931 dst_reg->range = ptr_reg->range;
1932 break;
1933 }
f1174f77
EC
1934 /* A new variable offset is created. Note that off_reg->off
1935 * == 0, since it's a scalar.
1936 * dst_reg gets the pointer type and since some positive
1937 * integer value was added to the pointer, give it a new 'id'
1938 * if it's a PTR_TO_PACKET.
1939 * this creates a new 'base' pointer, off_reg (variable) gets
1940 * added into the variable offset, and we copy the fixed offset
1941 * from ptr_reg.
969bf05e 1942 */
b03c9f9f
EC
1943 if (signed_add_overflows(smin_ptr, smin_val) ||
1944 signed_add_overflows(smax_ptr, smax_val)) {
1945 dst_reg->smin_value = S64_MIN;
1946 dst_reg->smax_value = S64_MAX;
1947 } else {
1948 dst_reg->smin_value = smin_ptr + smin_val;
1949 dst_reg->smax_value = smax_ptr + smax_val;
1950 }
1951 if (umin_ptr + umin_val < umin_ptr ||
1952 umax_ptr + umax_val < umax_ptr) {
1953 dst_reg->umin_value = 0;
1954 dst_reg->umax_value = U64_MAX;
1955 } else {
1956 dst_reg->umin_value = umin_ptr + umin_val;
1957 dst_reg->umax_value = umax_ptr + umax_val;
1958 }
f1174f77
EC
1959 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
1960 dst_reg->off = ptr_reg->off;
de8f3a83 1961 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
1962 dst_reg->id = ++env->id_gen;
1963 /* something was added to pkt_ptr, set range to zero */
1964 dst_reg->range = 0;
1965 }
1966 break;
1967 case BPF_SUB:
1968 if (dst_reg == off_reg) {
1969 /* scalar -= pointer. Creates an unknown scalar */
1970 if (!env->allow_ptr_leaks)
61bd5218 1971 verbose(env, "R%d tried to subtract pointer from scalar\n",
f1174f77
EC
1972 dst);
1973 return -EACCES;
1974 }
1975 /* We don't allow subtraction from FP, because (according to
1976 * test_verifier.c test "invalid fp arithmetic", JITs might not
1977 * be able to deal with it.
969bf05e 1978 */
f1174f77
EC
1979 if (ptr_reg->type == PTR_TO_STACK) {
1980 if (!env->allow_ptr_leaks)
61bd5218 1981 verbose(env, "R%d subtraction from stack pointer prohibited\n",
f1174f77
EC
1982 dst);
1983 return -EACCES;
1984 }
b03c9f9f
EC
1985 if (known && (ptr_reg->off - smin_val ==
1986 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 1987 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
1988 dst_reg->smin_value = smin_ptr;
1989 dst_reg->smax_value = smax_ptr;
1990 dst_reg->umin_value = umin_ptr;
1991 dst_reg->umax_value = umax_ptr;
f1174f77
EC
1992 dst_reg->var_off = ptr_reg->var_off;
1993 dst_reg->id = ptr_reg->id;
b03c9f9f 1994 dst_reg->off = ptr_reg->off - smin_val;
f1174f77
EC
1995 dst_reg->range = ptr_reg->range;
1996 break;
1997 }
f1174f77
EC
1998 /* A new variable offset is created. If the subtrahend is known
1999 * nonnegative, then any reg->range we had before is still good.
969bf05e 2000 */
b03c9f9f
EC
2001 if (signed_sub_overflows(smin_ptr, smax_val) ||
2002 signed_sub_overflows(smax_ptr, smin_val)) {
2003 /* Overflow possible, we know nothing */
2004 dst_reg->smin_value = S64_MIN;
2005 dst_reg->smax_value = S64_MAX;
2006 } else {
2007 dst_reg->smin_value = smin_ptr - smax_val;
2008 dst_reg->smax_value = smax_ptr - smin_val;
2009 }
2010 if (umin_ptr < umax_val) {
2011 /* Overflow possible, we know nothing */
2012 dst_reg->umin_value = 0;
2013 dst_reg->umax_value = U64_MAX;
2014 } else {
2015 /* Cannot overflow (as long as bounds are consistent) */
2016 dst_reg->umin_value = umin_ptr - umax_val;
2017 dst_reg->umax_value = umax_ptr - umin_val;
2018 }
f1174f77
EC
2019 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
2020 dst_reg->off = ptr_reg->off;
de8f3a83 2021 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
2022 dst_reg->id = ++env->id_gen;
2023 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 2024 if (smin_val < 0)
f1174f77 2025 dst_reg->range = 0;
43188702 2026 }
f1174f77
EC
2027 break;
2028 case BPF_AND:
2029 case BPF_OR:
2030 case BPF_XOR:
2031 /* bitwise ops on pointers are troublesome, prohibit for now.
2032 * (However, in principle we could allow some cases, e.g.
2033 * ptr &= ~3 which would reduce min_value by 3.)
2034 */
2035 if (!env->allow_ptr_leaks)
61bd5218 2036 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
f1174f77
EC
2037 dst, bpf_alu_string[opcode >> 4]);
2038 return -EACCES;
2039 default:
2040 /* other operators (e.g. MUL,LSH) produce non-pointer results */
2041 if (!env->allow_ptr_leaks)
61bd5218 2042 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
f1174f77
EC
2043 dst, bpf_alu_string[opcode >> 4]);
2044 return -EACCES;
43188702
JF
2045 }
2046
b03c9f9f
EC
2047 __update_reg_bounds(dst_reg);
2048 __reg_deduce_bounds(dst_reg);
2049 __reg_bound_offset(dst_reg);
43188702
JF
2050 return 0;
2051}
2052
f1174f77
EC
2053static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
2054 struct bpf_insn *insn,
2055 struct bpf_reg_state *dst_reg,
2056 struct bpf_reg_state src_reg)
969bf05e 2057{
58e2af8b 2058 struct bpf_reg_state *regs = env->cur_state.regs;
48461135 2059 u8 opcode = BPF_OP(insn->code);
f1174f77 2060 bool src_known, dst_known;
b03c9f9f
EC
2061 s64 smin_val, smax_val;
2062 u64 umin_val, umax_val;
48461135 2063
f1174f77
EC
2064 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2065 /* 32-bit ALU ops are (32,32)->64 */
2066 coerce_reg_to_32(dst_reg);
2067 coerce_reg_to_32(&src_reg);
9305706c 2068 }
b03c9f9f
EC
2069 smin_val = src_reg.smin_value;
2070 smax_val = src_reg.smax_value;
2071 umin_val = src_reg.umin_value;
2072 umax_val = src_reg.umax_value;
f1174f77
EC
2073 src_known = tnum_is_const(src_reg.var_off);
2074 dst_known = tnum_is_const(dst_reg->var_off);
f23cc643 2075
48461135
JB
2076 switch (opcode) {
2077 case BPF_ADD:
b03c9f9f
EC
2078 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
2079 signed_add_overflows(dst_reg->smax_value, smax_val)) {
2080 dst_reg->smin_value = S64_MIN;
2081 dst_reg->smax_value = S64_MAX;
2082 } else {
2083 dst_reg->smin_value += smin_val;
2084 dst_reg->smax_value += smax_val;
2085 }
2086 if (dst_reg->umin_value + umin_val < umin_val ||
2087 dst_reg->umax_value + umax_val < umax_val) {
2088 dst_reg->umin_value = 0;
2089 dst_reg->umax_value = U64_MAX;
2090 } else {
2091 dst_reg->umin_value += umin_val;
2092 dst_reg->umax_value += umax_val;
2093 }
f1174f77 2094 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
2095 break;
2096 case BPF_SUB:
b03c9f9f
EC
2097 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
2098 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
2099 /* Overflow possible, we know nothing */
2100 dst_reg->smin_value = S64_MIN;
2101 dst_reg->smax_value = S64_MAX;
2102 } else {
2103 dst_reg->smin_value -= smax_val;
2104 dst_reg->smax_value -= smin_val;
2105 }
2106 if (dst_reg->umin_value < umax_val) {
2107 /* Overflow possible, we know nothing */
2108 dst_reg->umin_value = 0;
2109 dst_reg->umax_value = U64_MAX;
2110 } else {
2111 /* Cannot overflow (as long as bounds are consistent) */
2112 dst_reg->umin_value -= umax_val;
2113 dst_reg->umax_value -= umin_val;
2114 }
f1174f77 2115 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
2116 break;
2117 case BPF_MUL:
b03c9f9f
EC
2118 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
2119 if (smin_val < 0 || dst_reg->smin_value < 0) {
f1174f77 2120 /* Ain't nobody got time to multiply that sign */
b03c9f9f
EC
2121 __mark_reg_unbounded(dst_reg);
2122 __update_reg_bounds(dst_reg);
f1174f77
EC
2123 break;
2124 }
b03c9f9f
EC
2125 /* Both values are positive, so we can work with unsigned and
2126 * copy the result to signed (unless it exceeds S64_MAX).
f1174f77 2127 */
b03c9f9f
EC
2128 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
2129 /* Potential overflow, we know nothing */
2130 __mark_reg_unbounded(dst_reg);
2131 /* (except what we can learn from the var_off) */
2132 __update_reg_bounds(dst_reg);
2133 break;
2134 }
2135 dst_reg->umin_value *= umin_val;
2136 dst_reg->umax_value *= umax_val;
2137 if (dst_reg->umax_value > S64_MAX) {
2138 /* Overflow possible, we know nothing */
2139 dst_reg->smin_value = S64_MIN;
2140 dst_reg->smax_value = S64_MAX;
2141 } else {
2142 dst_reg->smin_value = dst_reg->umin_value;
2143 dst_reg->smax_value = dst_reg->umax_value;
2144 }
48461135
JB
2145 break;
2146 case BPF_AND:
f1174f77 2147 if (src_known && dst_known) {
b03c9f9f
EC
2148 __mark_reg_known(dst_reg, dst_reg->var_off.value &
2149 src_reg.var_off.value);
f1174f77
EC
2150 break;
2151 }
b03c9f9f
EC
2152 /* We get our minimum from the var_off, since that's inherently
2153 * bitwise. Our maximum is the minimum of the operands' maxima.
f23cc643 2154 */
f1174f77 2155 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
b03c9f9f
EC
2156 dst_reg->umin_value = dst_reg->var_off.value;
2157 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2158 if (dst_reg->smin_value < 0 || smin_val < 0) {
2159 /* Lose signed bounds when ANDing negative numbers,
2160 * ain't nobody got time for that.
2161 */
2162 dst_reg->smin_value = S64_MIN;
2163 dst_reg->smax_value = S64_MAX;
2164 } else {
2165 /* ANDing two positives gives a positive, so safe to
2166 * cast result into s64.
2167 */
2168 dst_reg->smin_value = dst_reg->umin_value;
2169 dst_reg->smax_value = dst_reg->umax_value;
2170 }
2171 /* We may learn something more from the var_off */
2172 __update_reg_bounds(dst_reg);
f1174f77
EC
2173 break;
2174 case BPF_OR:
2175 if (src_known && dst_known) {
b03c9f9f
EC
2176 __mark_reg_known(dst_reg, dst_reg->var_off.value |
2177 src_reg.var_off.value);
f1174f77
EC
2178 break;
2179 }
b03c9f9f
EC
2180 /* We get our maximum from the var_off, and our minimum is the
2181 * maximum of the operands' minima
f1174f77
EC
2182 */
2183 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
b03c9f9f
EC
2184 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2185 dst_reg->umax_value = dst_reg->var_off.value |
2186 dst_reg->var_off.mask;
2187 if (dst_reg->smin_value < 0 || smin_val < 0) {
2188 /* Lose signed bounds when ORing negative numbers,
2189 * ain't nobody got time for that.
2190 */
2191 dst_reg->smin_value = S64_MIN;
2192 dst_reg->smax_value = S64_MAX;
f1174f77 2193 } else {
b03c9f9f
EC
2194 /* ORing two positives gives a positive, so safe to
2195 * cast result into s64.
2196 */
2197 dst_reg->smin_value = dst_reg->umin_value;
2198 dst_reg->smax_value = dst_reg->umax_value;
f1174f77 2199 }
b03c9f9f
EC
2200 /* We may learn something more from the var_off */
2201 __update_reg_bounds(dst_reg);
48461135
JB
2202 break;
2203 case BPF_LSH:
b03c9f9f
EC
2204 if (umax_val > 63) {
2205 /* Shifts greater than 63 are undefined. This includes
2206 * shifts by a negative number.
2207 */
61bd5218 2208 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
2209 break;
2210 }
b03c9f9f
EC
2211 /* We lose all sign bit information (except what we can pick
2212 * up from var_off)
48461135 2213 */
b03c9f9f
EC
2214 dst_reg->smin_value = S64_MIN;
2215 dst_reg->smax_value = S64_MAX;
2216 /* If we might shift our top bit out, then we know nothing */
2217 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2218 dst_reg->umin_value = 0;
2219 dst_reg->umax_value = U64_MAX;
d1174416 2220 } else {
b03c9f9f
EC
2221 dst_reg->umin_value <<= umin_val;
2222 dst_reg->umax_value <<= umax_val;
d1174416 2223 }
b03c9f9f
EC
2224 if (src_known)
2225 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2226 else
2227 dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
2228 /* We may learn something more from the var_off */
2229 __update_reg_bounds(dst_reg);
48461135
JB
2230 break;
2231 case BPF_RSH:
b03c9f9f
EC
2232 if (umax_val > 63) {
2233 /* Shifts greater than 63 are undefined. This includes
2234 * shifts by a negative number.
2235 */
61bd5218 2236 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
2237 break;
2238 }
2239 /* BPF_RSH is an unsigned shift, so make the appropriate casts */
b03c9f9f
EC
2240 if (dst_reg->smin_value < 0) {
2241 if (umin_val) {
f1174f77 2242 /* Sign bit will be cleared */
b03c9f9f
EC
2243 dst_reg->smin_value = 0;
2244 } else {
2245 /* Lost sign bit information */
2246 dst_reg->smin_value = S64_MIN;
2247 dst_reg->smax_value = S64_MAX;
2248 }
d1174416 2249 } else {
b03c9f9f
EC
2250 dst_reg->smin_value =
2251 (u64)(dst_reg->smin_value) >> umax_val;
d1174416 2252 }
f1174f77 2253 if (src_known)
b03c9f9f
EC
2254 dst_reg->var_off = tnum_rshift(dst_reg->var_off,
2255 umin_val);
f1174f77 2256 else
b03c9f9f
EC
2257 dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
2258 dst_reg->umin_value >>= umax_val;
2259 dst_reg->umax_value >>= umin_val;
2260 /* We may learn something more from the var_off */
2261 __update_reg_bounds(dst_reg);
48461135
JB
2262 break;
2263 default:
61bd5218 2264 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
2265 break;
2266 }
2267
b03c9f9f
EC
2268 __reg_deduce_bounds(dst_reg);
2269 __reg_bound_offset(dst_reg);
f1174f77
EC
2270 return 0;
2271}
2272
2273/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2274 * and var_off.
2275 */
2276static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2277 struct bpf_insn *insn)
2278{
2279 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg, *src_reg;
2280 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2281 u8 opcode = BPF_OP(insn->code);
2282 int rc;
2283
2284 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
2285 src_reg = NULL;
2286 if (dst_reg->type != SCALAR_VALUE)
2287 ptr_reg = dst_reg;
2288 if (BPF_SRC(insn->code) == BPF_X) {
2289 src_reg = &regs[insn->src_reg];
f1174f77
EC
2290 if (src_reg->type != SCALAR_VALUE) {
2291 if (dst_reg->type != SCALAR_VALUE) {
2292 /* Combining two pointers by any ALU op yields
2293 * an arbitrary scalar.
2294 */
2295 if (!env->allow_ptr_leaks) {
61bd5218 2296 verbose(env, "R%d pointer %s pointer prohibited\n",
f1174f77
EC
2297 insn->dst_reg,
2298 bpf_alu_string[opcode >> 4]);
2299 return -EACCES;
2300 }
61bd5218 2301 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
2302 return 0;
2303 } else {
2304 /* scalar += pointer
2305 * This is legal, but we have to reverse our
2306 * src/dest handling in computing the range
2307 */
2308 rc = adjust_ptr_min_max_vals(env, insn,
2309 src_reg, dst_reg);
2310 if (rc == -EACCES && env->allow_ptr_leaks) {
2311 /* scalar += unknown scalar */
2312 __mark_reg_unknown(&off_reg);
2313 return adjust_scalar_min_max_vals(
2314 env, insn,
2315 dst_reg, off_reg);
2316 }
2317 return rc;
2318 }
2319 } else if (ptr_reg) {
2320 /* pointer += scalar */
2321 rc = adjust_ptr_min_max_vals(env, insn,
2322 dst_reg, src_reg);
2323 if (rc == -EACCES && env->allow_ptr_leaks) {
2324 /* unknown scalar += scalar */
2325 __mark_reg_unknown(dst_reg);
2326 return adjust_scalar_min_max_vals(
2327 env, insn, dst_reg, *src_reg);
2328 }
2329 return rc;
2330 }
2331 } else {
2332 /* Pretend the src is a reg with a known value, since we only
2333 * need to be able to read from this state.
2334 */
2335 off_reg.type = SCALAR_VALUE;
b03c9f9f 2336 __mark_reg_known(&off_reg, insn->imm);
f1174f77 2337 src_reg = &off_reg;
f1174f77
EC
2338 if (ptr_reg) { /* pointer += K */
2339 rc = adjust_ptr_min_max_vals(env, insn,
2340 ptr_reg, src_reg);
2341 if (rc == -EACCES && env->allow_ptr_leaks) {
2342 /* unknown scalar += K */
2343 __mark_reg_unknown(dst_reg);
2344 return adjust_scalar_min_max_vals(
2345 env, insn, dst_reg, off_reg);
2346 }
2347 return rc;
2348 }
2349 }
2350
2351 /* Got here implies adding two SCALAR_VALUEs */
2352 if (WARN_ON_ONCE(ptr_reg)) {
61bd5218
JK
2353 print_verifier_state(env, &env->cur_state);
2354 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
2355 return -EINVAL;
2356 }
2357 if (WARN_ON(!src_reg)) {
61bd5218
JK
2358 print_verifier_state(env, &env->cur_state);
2359 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
2360 return -EINVAL;
2361 }
2362 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
2363}
2364
17a52670 2365/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 2366static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 2367{
f1174f77 2368 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
2369 u8 opcode = BPF_OP(insn->code);
2370 int err;
2371
2372 if (opcode == BPF_END || opcode == BPF_NEG) {
2373 if (opcode == BPF_NEG) {
2374 if (BPF_SRC(insn->code) != 0 ||
2375 insn->src_reg != BPF_REG_0 ||
2376 insn->off != 0 || insn->imm != 0) {
61bd5218 2377 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
2378 return -EINVAL;
2379 }
2380 } else {
2381 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
2382 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
2383 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 2384 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
2385 return -EINVAL;
2386 }
2387 }
2388
2389 /* check src operand */
dc503a8a 2390 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
2391 if (err)
2392 return err;
2393
1be7f75d 2394 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 2395 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
2396 insn->dst_reg);
2397 return -EACCES;
2398 }
2399
17a52670 2400 /* check dest operand */
dc503a8a 2401 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
2402 if (err)
2403 return err;
2404
2405 } else if (opcode == BPF_MOV) {
2406
2407 if (BPF_SRC(insn->code) == BPF_X) {
2408 if (insn->imm != 0 || insn->off != 0) {
61bd5218 2409 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
2410 return -EINVAL;
2411 }
2412
2413 /* check src operand */
dc503a8a 2414 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
2415 if (err)
2416 return err;
2417 } else {
2418 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 2419 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
2420 return -EINVAL;
2421 }
2422 }
2423
2424 /* check dest operand */
dc503a8a 2425 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
2426 if (err)
2427 return err;
2428
2429 if (BPF_SRC(insn->code) == BPF_X) {
2430 if (BPF_CLASS(insn->code) == BPF_ALU64) {
2431 /* case: R1 = R2
2432 * copy register state to dest reg
2433 */
2434 regs[insn->dst_reg] = regs[insn->src_reg];
8fe2d6cc 2435 regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
17a52670 2436 } else {
f1174f77 2437 /* R1 = (u32) R2 */
1be7f75d 2438 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
2439 verbose(env,
2440 "R%d partial copy of pointer\n",
1be7f75d
AS
2441 insn->src_reg);
2442 return -EACCES;
2443 }
61bd5218 2444 mark_reg_unknown(env, regs, insn->dst_reg);
b03c9f9f 2445 /* high 32 bits are known zero. */
f1174f77
EC
2446 regs[insn->dst_reg].var_off = tnum_cast(
2447 regs[insn->dst_reg].var_off, 4);
b03c9f9f 2448 __update_reg_bounds(&regs[insn->dst_reg]);
17a52670
AS
2449 }
2450 } else {
2451 /* case: R = imm
2452 * remember the value we stored into this reg
2453 */
f1174f77 2454 regs[insn->dst_reg].type = SCALAR_VALUE;
b03c9f9f 2455 __mark_reg_known(regs + insn->dst_reg, insn->imm);
17a52670
AS
2456 }
2457
2458 } else if (opcode > BPF_END) {
61bd5218 2459 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
2460 return -EINVAL;
2461
2462 } else { /* all other ALU ops: and, sub, xor, add, ... */
2463
17a52670
AS
2464 if (BPF_SRC(insn->code) == BPF_X) {
2465 if (insn->imm != 0 || insn->off != 0) {
61bd5218 2466 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
2467 return -EINVAL;
2468 }
2469 /* check src1 operand */
dc503a8a 2470 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
2471 if (err)
2472 return err;
2473 } else {
2474 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 2475 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
2476 return -EINVAL;
2477 }
2478 }
2479
2480 /* check src2 operand */
dc503a8a 2481 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
2482 if (err)
2483 return err;
2484
2485 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
2486 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 2487 verbose(env, "div by zero\n");
17a52670
AS
2488 return -EINVAL;
2489 }
2490
229394e8
RV
2491 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
2492 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
2493 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
2494
2495 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 2496 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
2497 return -EINVAL;
2498 }
2499 }
2500
1a0dc1ac 2501 /* check dest operand */
dc503a8a 2502 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
2503 if (err)
2504 return err;
2505
f1174f77 2506 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
2507 }
2508
2509 return 0;
2510}
2511
58e2af8b 2512static void find_good_pkt_pointers(struct bpf_verifier_state *state,
de8f3a83
DB
2513 struct bpf_reg_state *dst_reg,
2514 enum bpf_reg_type type)
969bf05e 2515{
58e2af8b 2516 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e 2517 int i;
2d2be8ca 2518
f1174f77
EC
2519 if (dst_reg->off < 0)
2520 /* This doesn't give us any range */
2521 return;
2522
b03c9f9f
EC
2523 if (dst_reg->umax_value > MAX_PACKET_OFF ||
2524 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
2525 /* Risk of overflow. For instance, ptr + (1<<63) may be less
2526 * than pkt_end, but that's because it's also less than pkt.
2527 */
2528 return;
2529
b4e432f1 2530 /* LLVM can generate four kind of checks:
2d2be8ca 2531 *
b4e432f1 2532 * Type 1/2:
2d2be8ca
DB
2533 *
2534 * r2 = r3;
2535 * r2 += 8;
2536 * if (r2 > pkt_end) goto <handle exception>
2537 * <access okay>
2538 *
b4e432f1
DB
2539 * r2 = r3;
2540 * r2 += 8;
2541 * if (r2 < pkt_end) goto <access okay>
2542 * <handle exception>
2543 *
2d2be8ca
DB
2544 * Where:
2545 * r2 == dst_reg, pkt_end == src_reg
2546 * r2=pkt(id=n,off=8,r=0)
2547 * r3=pkt(id=n,off=0,r=0)
2548 *
b4e432f1 2549 * Type 3/4:
2d2be8ca
DB
2550 *
2551 * r2 = r3;
2552 * r2 += 8;
2553 * if (pkt_end >= r2) goto <access okay>
2554 * <handle exception>
2555 *
b4e432f1
DB
2556 * r2 = r3;
2557 * r2 += 8;
2558 * if (pkt_end <= r2) goto <handle exception>
2559 * <access okay>
2560 *
2d2be8ca
DB
2561 * Where:
2562 * pkt_end == dst_reg, r2 == src_reg
2563 * r2=pkt(id=n,off=8,r=0)
2564 * r3=pkt(id=n,off=0,r=0)
2565 *
2566 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
2567 * so that range of bytes [r3, r3 + 8) is safe to access.
969bf05e 2568 */
2d2be8ca 2569
f1174f77
EC
2570 /* If our ids match, then we must have the same max_value. And we
2571 * don't care about the other reg's fixed offset, since if it's too big
2572 * the range won't allow anything.
2573 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
2574 */
969bf05e 2575 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 2576 if (regs[i].type == type && regs[i].id == dst_reg->id)
b1977682 2577 /* keep the maximum range already checked */
f1174f77 2578 regs[i].range = max_t(u16, regs[i].range, dst_reg->off);
969bf05e
AS
2579
2580 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2581 if (state->stack_slot_type[i] != STACK_SPILL)
2582 continue;
2583 reg = &state->spilled_regs[i / BPF_REG_SIZE];
de8f3a83 2584 if (reg->type == type && reg->id == dst_reg->id)
f1174f77 2585 reg->range = max_t(u16, reg->range, dst_reg->off);
969bf05e
AS
2586 }
2587}
2588
48461135
JB
2589/* Adjusts the register min/max values in the case that the dst_reg is the
2590 * variable register that we are working on, and src_reg is a constant or we're
2591 * simply doing a BPF_K check.
f1174f77 2592 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
2593 */
2594static void reg_set_min_max(struct bpf_reg_state *true_reg,
2595 struct bpf_reg_state *false_reg, u64 val,
2596 u8 opcode)
2597{
f1174f77
EC
2598 /* If the dst_reg is a pointer, we can't learn anything about its
2599 * variable offset from the compare (unless src_reg were a pointer into
2600 * the same object, but we don't bother with that.
2601 * Since false_reg and true_reg have the same type by construction, we
2602 * only need to check one of them for pointerness.
2603 */
2604 if (__is_pointer_value(false, false_reg))
2605 return;
4cabc5b1 2606
48461135
JB
2607 switch (opcode) {
2608 case BPF_JEQ:
2609 /* If this is false then we know nothing Jon Snow, but if it is
2610 * true then we know for sure.
2611 */
b03c9f9f 2612 __mark_reg_known(true_reg, val);
48461135
JB
2613 break;
2614 case BPF_JNE:
2615 /* If this is true we know nothing Jon Snow, but if it is false
2616 * we know the value for sure;
2617 */
b03c9f9f 2618 __mark_reg_known(false_reg, val);
48461135
JB
2619 break;
2620 case BPF_JGT:
b03c9f9f
EC
2621 false_reg->umax_value = min(false_reg->umax_value, val);
2622 true_reg->umin_value = max(true_reg->umin_value, val + 1);
2623 break;
48461135 2624 case BPF_JSGT:
b03c9f9f
EC
2625 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
2626 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
48461135 2627 break;
b4e432f1
DB
2628 case BPF_JLT:
2629 false_reg->umin_value = max(false_reg->umin_value, val);
2630 true_reg->umax_value = min(true_reg->umax_value, val - 1);
2631 break;
2632 case BPF_JSLT:
2633 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
2634 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
2635 break;
48461135 2636 case BPF_JGE:
b03c9f9f
EC
2637 false_reg->umax_value = min(false_reg->umax_value, val - 1);
2638 true_reg->umin_value = max(true_reg->umin_value, val);
2639 break;
48461135 2640 case BPF_JSGE:
b03c9f9f
EC
2641 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
2642 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
48461135 2643 break;
b4e432f1
DB
2644 case BPF_JLE:
2645 false_reg->umin_value = max(false_reg->umin_value, val + 1);
2646 true_reg->umax_value = min(true_reg->umax_value, val);
2647 break;
2648 case BPF_JSLE:
2649 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
2650 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
2651 break;
48461135
JB
2652 default:
2653 break;
2654 }
2655
b03c9f9f
EC
2656 __reg_deduce_bounds(false_reg);
2657 __reg_deduce_bounds(true_reg);
2658 /* We might have learned some bits from the bounds. */
2659 __reg_bound_offset(false_reg);
2660 __reg_bound_offset(true_reg);
2661 /* Intersecting with the old var_off might have improved our bounds
2662 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2663 * then new var_off is (0; 0x7f...fc) which improves our umax.
2664 */
2665 __update_reg_bounds(false_reg);
2666 __update_reg_bounds(true_reg);
48461135
JB
2667}
2668
f1174f77
EC
2669/* Same as above, but for the case that dst_reg holds a constant and src_reg is
2670 * the variable reg.
48461135
JB
2671 */
2672static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
2673 struct bpf_reg_state *false_reg, u64 val,
2674 u8 opcode)
2675{
f1174f77
EC
2676 if (__is_pointer_value(false, false_reg))
2677 return;
4cabc5b1 2678
48461135
JB
2679 switch (opcode) {
2680 case BPF_JEQ:
2681 /* If this is false then we know nothing Jon Snow, but if it is
2682 * true then we know for sure.
2683 */
b03c9f9f 2684 __mark_reg_known(true_reg, val);
48461135
JB
2685 break;
2686 case BPF_JNE:
2687 /* If this is true we know nothing Jon Snow, but if it is false
2688 * we know the value for sure;
2689 */
b03c9f9f 2690 __mark_reg_known(false_reg, val);
48461135
JB
2691 break;
2692 case BPF_JGT:
b03c9f9f
EC
2693 true_reg->umax_value = min(true_reg->umax_value, val - 1);
2694 false_reg->umin_value = max(false_reg->umin_value, val);
2695 break;
48461135 2696 case BPF_JSGT:
b03c9f9f
EC
2697 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
2698 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
48461135 2699 break;
b4e432f1
DB
2700 case BPF_JLT:
2701 true_reg->umin_value = max(true_reg->umin_value, val + 1);
2702 false_reg->umax_value = min(false_reg->umax_value, val);
2703 break;
2704 case BPF_JSLT:
2705 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
2706 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
2707 break;
48461135 2708 case BPF_JGE:
b03c9f9f
EC
2709 true_reg->umax_value = min(true_reg->umax_value, val);
2710 false_reg->umin_value = max(false_reg->umin_value, val + 1);
2711 break;
48461135 2712 case BPF_JSGE:
b03c9f9f
EC
2713 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
2714 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
48461135 2715 break;
b4e432f1
DB
2716 case BPF_JLE:
2717 true_reg->umin_value = max(true_reg->umin_value, val);
2718 false_reg->umax_value = min(false_reg->umax_value, val - 1);
2719 break;
2720 case BPF_JSLE:
2721 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
2722 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
2723 break;
48461135
JB
2724 default:
2725 break;
2726 }
2727
b03c9f9f
EC
2728 __reg_deduce_bounds(false_reg);
2729 __reg_deduce_bounds(true_reg);
2730 /* We might have learned some bits from the bounds. */
2731 __reg_bound_offset(false_reg);
2732 __reg_bound_offset(true_reg);
2733 /* Intersecting with the old var_off might have improved our bounds
2734 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2735 * then new var_off is (0; 0x7f...fc) which improves our umax.
2736 */
2737 __update_reg_bounds(false_reg);
2738 __update_reg_bounds(true_reg);
f1174f77
EC
2739}
2740
2741/* Regs are known to be equal, so intersect their min/max/var_off */
2742static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
2743 struct bpf_reg_state *dst_reg)
2744{
b03c9f9f
EC
2745 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
2746 dst_reg->umin_value);
2747 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
2748 dst_reg->umax_value);
2749 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
2750 dst_reg->smin_value);
2751 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
2752 dst_reg->smax_value);
f1174f77
EC
2753 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
2754 dst_reg->var_off);
b03c9f9f
EC
2755 /* We might have learned new bounds from the var_off. */
2756 __update_reg_bounds(src_reg);
2757 __update_reg_bounds(dst_reg);
2758 /* We might have learned something about the sign bit. */
2759 __reg_deduce_bounds(src_reg);
2760 __reg_deduce_bounds(dst_reg);
2761 /* We might have learned some bits from the bounds. */
2762 __reg_bound_offset(src_reg);
2763 __reg_bound_offset(dst_reg);
2764 /* Intersecting with the old var_off might have improved our bounds
2765 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2766 * then new var_off is (0; 0x7f...fc) which improves our umax.
2767 */
2768 __update_reg_bounds(src_reg);
2769 __update_reg_bounds(dst_reg);
f1174f77
EC
2770}
2771
2772static void reg_combine_min_max(struct bpf_reg_state *true_src,
2773 struct bpf_reg_state *true_dst,
2774 struct bpf_reg_state *false_src,
2775 struct bpf_reg_state *false_dst,
2776 u8 opcode)
2777{
2778 switch (opcode) {
2779 case BPF_JEQ:
2780 __reg_combine_min_max(true_src, true_dst);
2781 break;
2782 case BPF_JNE:
2783 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 2784 break;
4cabc5b1 2785 }
48461135
JB
2786}
2787
57a09bf0 2788static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
f1174f77 2789 bool is_null)
57a09bf0
TG
2790{
2791 struct bpf_reg_state *reg = &regs[regno];
2792
2793 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
f1174f77
EC
2794 /* Old offset (both fixed and variable parts) should
2795 * have been known-zero, because we don't allow pointer
2796 * arithmetic on pointers that might be NULL.
2797 */
b03c9f9f
EC
2798 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
2799 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 2800 reg->off)) {
b03c9f9f
EC
2801 __mark_reg_known_zero(reg);
2802 reg->off = 0;
f1174f77
EC
2803 }
2804 if (is_null) {
2805 reg->type = SCALAR_VALUE;
56f668df
MKL
2806 } else if (reg->map_ptr->inner_map_meta) {
2807 reg->type = CONST_PTR_TO_MAP;
2808 reg->map_ptr = reg->map_ptr->inner_map_meta;
2809 } else {
f1174f77 2810 reg->type = PTR_TO_MAP_VALUE;
56f668df 2811 }
a08dd0da
DB
2812 /* We don't need id from this point onwards anymore, thus we
2813 * should better reset it, so that state pruning has chances
2814 * to take effect.
2815 */
2816 reg->id = 0;
57a09bf0
TG
2817 }
2818}
2819
2820/* The logic is similar to find_good_pkt_pointers(), both could eventually
2821 * be folded together at some point.
2822 */
2823static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
f1174f77 2824 bool is_null)
57a09bf0
TG
2825{
2826 struct bpf_reg_state *regs = state->regs;
a08dd0da 2827 u32 id = regs[regno].id;
57a09bf0
TG
2828 int i;
2829
2830 for (i = 0; i < MAX_BPF_REG; i++)
f1174f77 2831 mark_map_reg(regs, i, id, is_null);
57a09bf0
TG
2832
2833 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2834 if (state->stack_slot_type[i] != STACK_SPILL)
2835 continue;
f1174f77 2836 mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, is_null);
57a09bf0
TG
2837 }
2838}
2839
58e2af8b 2840static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
2841 struct bpf_insn *insn, int *insn_idx)
2842{
58e2af8b
JK
2843 struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
2844 struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
17a52670
AS
2845 u8 opcode = BPF_OP(insn->code);
2846 int err;
2847
b4e432f1 2848 if (opcode > BPF_JSLE) {
61bd5218 2849 verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
17a52670
AS
2850 return -EINVAL;
2851 }
2852
2853 if (BPF_SRC(insn->code) == BPF_X) {
2854 if (insn->imm != 0) {
61bd5218 2855 verbose(env, "BPF_JMP uses reserved fields\n");
17a52670
AS
2856 return -EINVAL;
2857 }
2858
2859 /* check src1 operand */
dc503a8a 2860 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
2861 if (err)
2862 return err;
1be7f75d
AS
2863
2864 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 2865 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
2866 insn->src_reg);
2867 return -EACCES;
2868 }
17a52670
AS
2869 } else {
2870 if (insn->src_reg != BPF_REG_0) {
61bd5218 2871 verbose(env, "BPF_JMP uses reserved fields\n");
17a52670
AS
2872 return -EINVAL;
2873 }
2874 }
2875
2876 /* check src2 operand */
dc503a8a 2877 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
2878 if (err)
2879 return err;
2880
1a0dc1ac
AS
2881 dst_reg = &regs[insn->dst_reg];
2882
17a52670
AS
2883 /* detect if R == 0 where R was initialized to zero earlier */
2884 if (BPF_SRC(insn->code) == BPF_K &&
2885 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
f1174f77
EC
2886 dst_reg->type == SCALAR_VALUE &&
2887 tnum_equals_const(dst_reg->var_off, insn->imm)) {
17a52670
AS
2888 if (opcode == BPF_JEQ) {
2889 /* if (imm == imm) goto pc+off;
2890 * only follow the goto, ignore fall-through
2891 */
2892 *insn_idx += insn->off;
2893 return 0;
2894 } else {
2895 /* if (imm != imm) goto pc+off;
2896 * only follow fall-through branch, since
2897 * that's where the program will go
2898 */
2899 return 0;
2900 }
2901 }
2902
2903 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
2904 if (!other_branch)
2905 return -EFAULT;
2906
48461135
JB
2907 /* detect if we are comparing against a constant value so we can adjust
2908 * our min/max values for our dst register.
f1174f77
EC
2909 * this is only legit if both are scalars (or pointers to the same
2910 * object, I suppose, but we don't support that right now), because
2911 * otherwise the different base pointers mean the offsets aren't
2912 * comparable.
48461135
JB
2913 */
2914 if (BPF_SRC(insn->code) == BPF_X) {
f1174f77
EC
2915 if (dst_reg->type == SCALAR_VALUE &&
2916 regs[insn->src_reg].type == SCALAR_VALUE) {
2917 if (tnum_is_const(regs[insn->src_reg].var_off))
2918 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2919 dst_reg, regs[insn->src_reg].var_off.value,
2920 opcode);
2921 else if (tnum_is_const(dst_reg->var_off))
2922 reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
2923 &regs[insn->src_reg],
2924 dst_reg->var_off.value, opcode);
2925 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
2926 /* Comparing for equality, we can combine knowledge */
2927 reg_combine_min_max(&other_branch->regs[insn->src_reg],
2928 &other_branch->regs[insn->dst_reg],
2929 &regs[insn->src_reg],
2930 &regs[insn->dst_reg], opcode);
2931 }
2932 } else if (dst_reg->type == SCALAR_VALUE) {
48461135
JB
2933 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2934 dst_reg, insn->imm, opcode);
2935 }
2936
58e2af8b 2937 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
17a52670 2938 if (BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac
AS
2939 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
2940 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
57a09bf0
TG
2941 /* Mark all identical map registers in each branch as either
2942 * safe or unknown depending R == 0 or R != 0 conditional.
2943 */
f1174f77
EC
2944 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
2945 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
969bf05e
AS
2946 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
2947 dst_reg->type == PTR_TO_PACKET &&
2948 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
de8f3a83 2949 find_good_pkt_pointers(this_branch, dst_reg, PTR_TO_PACKET);
b4e432f1
DB
2950 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
2951 dst_reg->type == PTR_TO_PACKET &&
2952 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
de8f3a83 2953 find_good_pkt_pointers(other_branch, dst_reg, PTR_TO_PACKET);
2d2be8ca
DB
2954 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
2955 dst_reg->type == PTR_TO_PACKET_END &&
2956 regs[insn->src_reg].type == PTR_TO_PACKET) {
de8f3a83
DB
2957 find_good_pkt_pointers(other_branch, &regs[insn->src_reg],
2958 PTR_TO_PACKET);
b4e432f1
DB
2959 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
2960 dst_reg->type == PTR_TO_PACKET_END &&
2961 regs[insn->src_reg].type == PTR_TO_PACKET) {
de8f3a83
DB
2962 find_good_pkt_pointers(this_branch, &regs[insn->src_reg],
2963 PTR_TO_PACKET);
2964 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
2965 dst_reg->type == PTR_TO_PACKET_META &&
2966 reg_is_init_pkt_pointer(&regs[insn->src_reg], PTR_TO_PACKET)) {
2967 find_good_pkt_pointers(this_branch, dst_reg, PTR_TO_PACKET_META);
2968 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
2969 dst_reg->type == PTR_TO_PACKET_META &&
2970 reg_is_init_pkt_pointer(&regs[insn->src_reg], PTR_TO_PACKET)) {
2971 find_good_pkt_pointers(other_branch, dst_reg, PTR_TO_PACKET_META);
2972 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
2973 reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
2974 regs[insn->src_reg].type == PTR_TO_PACKET_META) {
2975 find_good_pkt_pointers(other_branch, &regs[insn->src_reg],
2976 PTR_TO_PACKET_META);
2977 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
2978 reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
2979 regs[insn->src_reg].type == PTR_TO_PACKET_META) {
2980 find_good_pkt_pointers(this_branch, &regs[insn->src_reg],
2981 PTR_TO_PACKET_META);
1be7f75d 2982 } else if (is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
2983 verbose(env, "R%d pointer comparison prohibited\n",
2984 insn->dst_reg);
1be7f75d 2985 return -EACCES;
17a52670 2986 }
61bd5218
JK
2987 if (env->log.level)
2988 print_verifier_state(env, this_branch);
17a52670
AS
2989 return 0;
2990}
2991
0246e64d
AS
2992/* return the map pointer stored inside BPF_LD_IMM64 instruction */
2993static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
2994{
2995 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
2996
2997 return (struct bpf_map *) (unsigned long) imm64;
2998}
2999
17a52670 3000/* verify BPF_LD_IMM64 instruction */
58e2af8b 3001static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 3002{
58e2af8b 3003 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
3004 int err;
3005
3006 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 3007 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
3008 return -EINVAL;
3009 }
3010 if (insn->off != 0) {
61bd5218 3011 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
3012 return -EINVAL;
3013 }
3014
dc503a8a 3015 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
3016 if (err)
3017 return err;
3018
6b173873 3019 if (insn->src_reg == 0) {
6b173873
JK
3020 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3021
f1174f77 3022 regs[insn->dst_reg].type = SCALAR_VALUE;
b03c9f9f 3023 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 3024 return 0;
6b173873 3025 }
17a52670
AS
3026
3027 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3028 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3029
3030 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3031 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3032 return 0;
3033}
3034
96be4325
DB
3035static bool may_access_skb(enum bpf_prog_type type)
3036{
3037 switch (type) {
3038 case BPF_PROG_TYPE_SOCKET_FILTER:
3039 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 3040 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
3041 return true;
3042 default:
3043 return false;
3044 }
3045}
3046
ddd872bc
AS
3047/* verify safety of LD_ABS|LD_IND instructions:
3048 * - they can only appear in the programs where ctx == skb
3049 * - since they are wrappers of function calls, they scratch R1-R5 registers,
3050 * preserve R6-R9, and store return value into R0
3051 *
3052 * Implicit input:
3053 * ctx == skb == R6 == CTX
3054 *
3055 * Explicit input:
3056 * SRC == any register
3057 * IMM == 32-bit immediate
3058 *
3059 * Output:
3060 * R0 - 8/16/32-bit skb data converted to cpu endianness
3061 */
58e2af8b 3062static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 3063{
58e2af8b 3064 struct bpf_reg_state *regs = env->cur_state.regs;
ddd872bc 3065 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
3066 int i, err;
3067
24701ece 3068 if (!may_access_skb(env->prog->type)) {
61bd5218 3069 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
3070 return -EINVAL;
3071 }
3072
3073 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 3074 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 3075 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 3076 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
3077 return -EINVAL;
3078 }
3079
3080 /* check whether implicit source operand (register R6) is readable */
dc503a8a 3081 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
ddd872bc
AS
3082 if (err)
3083 return err;
3084
3085 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
61bd5218
JK
3086 verbose(env,
3087 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
3088 return -EINVAL;
3089 }
3090
3091 if (mode == BPF_IND) {
3092 /* check explicit source operand */
dc503a8a 3093 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
3094 if (err)
3095 return err;
3096 }
3097
3098 /* reset caller saved regs to unreadable */
dc503a8a 3099 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 3100 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
3101 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3102 }
ddd872bc
AS
3103
3104 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
3105 * the value fetched from the packet.
3106 * Already marked as written above.
ddd872bc 3107 */
61bd5218 3108 mark_reg_unknown(env, regs, BPF_REG_0);
ddd872bc
AS
3109 return 0;
3110}
3111
390ee7e2
AS
3112static int check_return_code(struct bpf_verifier_env *env)
3113{
3114 struct bpf_reg_state *reg;
3115 struct tnum range = tnum_range(0, 1);
3116
3117 switch (env->prog->type) {
3118 case BPF_PROG_TYPE_CGROUP_SKB:
3119 case BPF_PROG_TYPE_CGROUP_SOCK:
3120 case BPF_PROG_TYPE_SOCK_OPS:
3121 break;
3122 default:
3123 return 0;
3124 }
3125
3126 reg = &env->cur_state.regs[BPF_REG_0];
3127 if (reg->type != SCALAR_VALUE) {
61bd5218 3128 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
3129 reg_type_str[reg->type]);
3130 return -EINVAL;
3131 }
3132
3133 if (!tnum_in(range, reg->var_off)) {
61bd5218 3134 verbose(env, "At program exit the register R0 ");
390ee7e2
AS
3135 if (!tnum_is_unknown(reg->var_off)) {
3136 char tn_buf[48];
3137
3138 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3139 verbose(env, "has value %s", tn_buf);
390ee7e2 3140 } else {
61bd5218 3141 verbose(env, "has unknown scalar value");
390ee7e2 3142 }
61bd5218 3143 verbose(env, " should have been 0 or 1\n");
390ee7e2
AS
3144 return -EINVAL;
3145 }
3146 return 0;
3147}
3148
475fb78f
AS
3149/* non-recursive DFS pseudo code
3150 * 1 procedure DFS-iterative(G,v):
3151 * 2 label v as discovered
3152 * 3 let S be a stack
3153 * 4 S.push(v)
3154 * 5 while S is not empty
3155 * 6 t <- S.pop()
3156 * 7 if t is what we're looking for:
3157 * 8 return t
3158 * 9 for all edges e in G.adjacentEdges(t) do
3159 * 10 if edge e is already labelled
3160 * 11 continue with the next edge
3161 * 12 w <- G.adjacentVertex(t,e)
3162 * 13 if vertex w is not discovered and not explored
3163 * 14 label e as tree-edge
3164 * 15 label w as discovered
3165 * 16 S.push(w)
3166 * 17 continue at 5
3167 * 18 else if vertex w is discovered
3168 * 19 label e as back-edge
3169 * 20 else
3170 * 21 // vertex w is explored
3171 * 22 label e as forward- or cross-edge
3172 * 23 label t as explored
3173 * 24 S.pop()
3174 *
3175 * convention:
3176 * 0x10 - discovered
3177 * 0x11 - discovered and fall-through edge labelled
3178 * 0x12 - discovered and fall-through and branch edges labelled
3179 * 0x20 - explored
3180 */
3181
3182enum {
3183 DISCOVERED = 0x10,
3184 EXPLORED = 0x20,
3185 FALLTHROUGH = 1,
3186 BRANCH = 2,
3187};
3188
58e2af8b 3189#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
f1bca824 3190
475fb78f
AS
3191static int *insn_stack; /* stack of insns to process */
3192static int cur_stack; /* current stack index */
3193static int *insn_state;
3194
3195/* t, w, e - match pseudo-code above:
3196 * t - index of current instruction
3197 * w - next instruction
3198 * e - edge
3199 */
58e2af8b 3200static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
475fb78f
AS
3201{
3202 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
3203 return 0;
3204
3205 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
3206 return 0;
3207
3208 if (w < 0 || w >= env->prog->len) {
61bd5218 3209 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
3210 return -EINVAL;
3211 }
3212
f1bca824
AS
3213 if (e == BRANCH)
3214 /* mark branch target for state pruning */
3215 env->explored_states[w] = STATE_LIST_MARK;
3216
475fb78f
AS
3217 if (insn_state[w] == 0) {
3218 /* tree-edge */
3219 insn_state[t] = DISCOVERED | e;
3220 insn_state[w] = DISCOVERED;
3221 if (cur_stack >= env->prog->len)
3222 return -E2BIG;
3223 insn_stack[cur_stack++] = w;
3224 return 1;
3225 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
61bd5218 3226 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
3227 return -EINVAL;
3228 } else if (insn_state[w] == EXPLORED) {
3229 /* forward- or cross-edge */
3230 insn_state[t] = DISCOVERED | e;
3231 } else {
61bd5218 3232 verbose(env, "insn state internal bug\n");
475fb78f
AS
3233 return -EFAULT;
3234 }
3235 return 0;
3236}
3237
3238/* non-recursive depth-first-search to detect loops in BPF program
3239 * loop == back-edge in directed graph
3240 */
58e2af8b 3241static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
3242{
3243 struct bpf_insn *insns = env->prog->insnsi;
3244 int insn_cnt = env->prog->len;
3245 int ret = 0;
3246 int i, t;
3247
3248 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3249 if (!insn_state)
3250 return -ENOMEM;
3251
3252 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3253 if (!insn_stack) {
3254 kfree(insn_state);
3255 return -ENOMEM;
3256 }
3257
3258 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
3259 insn_stack[0] = 0; /* 0 is the first instruction */
3260 cur_stack = 1;
3261
3262peek_stack:
3263 if (cur_stack == 0)
3264 goto check_state;
3265 t = insn_stack[cur_stack - 1];
3266
3267 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
3268 u8 opcode = BPF_OP(insns[t].code);
3269
3270 if (opcode == BPF_EXIT) {
3271 goto mark_explored;
3272 } else if (opcode == BPF_CALL) {
3273 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3274 if (ret == 1)
3275 goto peek_stack;
3276 else if (ret < 0)
3277 goto err_free;
07016151
DB
3278 if (t + 1 < insn_cnt)
3279 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
3280 } else if (opcode == BPF_JA) {
3281 if (BPF_SRC(insns[t].code) != BPF_K) {
3282 ret = -EINVAL;
3283 goto err_free;
3284 }
3285 /* unconditional jump with single edge */
3286 ret = push_insn(t, t + insns[t].off + 1,
3287 FALLTHROUGH, env);
3288 if (ret == 1)
3289 goto peek_stack;
3290 else if (ret < 0)
3291 goto err_free;
f1bca824
AS
3292 /* tell verifier to check for equivalent states
3293 * after every call and jump
3294 */
c3de6317
AS
3295 if (t + 1 < insn_cnt)
3296 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
3297 } else {
3298 /* conditional jump with two edges */
3c2ce60b 3299 env->explored_states[t] = STATE_LIST_MARK;
475fb78f
AS
3300 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3301 if (ret == 1)
3302 goto peek_stack;
3303 else if (ret < 0)
3304 goto err_free;
3305
3306 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
3307 if (ret == 1)
3308 goto peek_stack;
3309 else if (ret < 0)
3310 goto err_free;
3311 }
3312 } else {
3313 /* all other non-branch instructions with single
3314 * fall-through edge
3315 */
3316 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3317 if (ret == 1)
3318 goto peek_stack;
3319 else if (ret < 0)
3320 goto err_free;
3321 }
3322
3323mark_explored:
3324 insn_state[t] = EXPLORED;
3325 if (cur_stack-- <= 0) {
61bd5218 3326 verbose(env, "pop stack internal bug\n");
475fb78f
AS
3327 ret = -EFAULT;
3328 goto err_free;
3329 }
3330 goto peek_stack;
3331
3332check_state:
3333 for (i = 0; i < insn_cnt; i++) {
3334 if (insn_state[i] != EXPLORED) {
61bd5218 3335 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
3336 ret = -EINVAL;
3337 goto err_free;
3338 }
3339 }
3340 ret = 0; /* cfg looks good */
3341
3342err_free:
3343 kfree(insn_state);
3344 kfree(insn_stack);
3345 return ret;
3346}
3347
f1174f77
EC
3348/* check %cur's range satisfies %old's */
3349static bool range_within(struct bpf_reg_state *old,
3350 struct bpf_reg_state *cur)
3351{
b03c9f9f
EC
3352 return old->umin_value <= cur->umin_value &&
3353 old->umax_value >= cur->umax_value &&
3354 old->smin_value <= cur->smin_value &&
3355 old->smax_value >= cur->smax_value;
f1174f77
EC
3356}
3357
3358/* Maximum number of register states that can exist at once */
3359#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
3360struct idpair {
3361 u32 old;
3362 u32 cur;
3363};
3364
3365/* If in the old state two registers had the same id, then they need to have
3366 * the same id in the new state as well. But that id could be different from
3367 * the old state, so we need to track the mapping from old to new ids.
3368 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
3369 * regs with old id 5 must also have new id 9 for the new state to be safe. But
3370 * regs with a different old id could still have new id 9, we don't care about
3371 * that.
3372 * So we look through our idmap to see if this old id has been seen before. If
3373 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 3374 */
f1174f77 3375static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 3376{
f1174f77 3377 unsigned int i;
969bf05e 3378
f1174f77
EC
3379 for (i = 0; i < ID_MAP_SIZE; i++) {
3380 if (!idmap[i].old) {
3381 /* Reached an empty slot; haven't seen this id before */
3382 idmap[i].old = old_id;
3383 idmap[i].cur = cur_id;
3384 return true;
3385 }
3386 if (idmap[i].old == old_id)
3387 return idmap[i].cur == cur_id;
3388 }
3389 /* We ran out of idmap slots, which should be impossible */
3390 WARN_ON_ONCE(1);
3391 return false;
3392}
3393
3394/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
3395static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
3396 struct idpair *idmap)
f1174f77 3397{
dc503a8a
EC
3398 if (!(rold->live & REG_LIVE_READ))
3399 /* explored state didn't use this */
3400 return true;
3401
3402 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
969bf05e
AS
3403 return true;
3404
f1174f77
EC
3405 if (rold->type == NOT_INIT)
3406 /* explored state can't have used this */
969bf05e 3407 return true;
f1174f77
EC
3408 if (rcur->type == NOT_INIT)
3409 return false;
3410 switch (rold->type) {
3411 case SCALAR_VALUE:
3412 if (rcur->type == SCALAR_VALUE) {
3413 /* new val must satisfy old val knowledge */
3414 return range_within(rold, rcur) &&
3415 tnum_in(rold->var_off, rcur->var_off);
3416 } else {
3417 /* if we knew anything about the old value, we're not
3418 * equal, because we can't know anything about the
3419 * scalar value of the pointer in the new value.
3420 */
b03c9f9f
EC
3421 return rold->umin_value == 0 &&
3422 rold->umax_value == U64_MAX &&
3423 rold->smin_value == S64_MIN &&
3424 rold->smax_value == S64_MAX &&
f1174f77
EC
3425 tnum_is_unknown(rold->var_off);
3426 }
3427 case PTR_TO_MAP_VALUE:
1b688a19
EC
3428 /* If the new min/max/var_off satisfy the old ones and
3429 * everything else matches, we are OK.
3430 * We don't care about the 'id' value, because nothing
3431 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
3432 */
3433 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
3434 range_within(rold, rcur) &&
3435 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
3436 case PTR_TO_MAP_VALUE_OR_NULL:
3437 /* a PTR_TO_MAP_VALUE could be safe to use as a
3438 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
3439 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
3440 * checked, doing so could have affected others with the same
3441 * id, and we can't check for that because we lost the id when
3442 * we converted to a PTR_TO_MAP_VALUE.
3443 */
3444 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
3445 return false;
3446 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
3447 return false;
3448 /* Check our ids match any regs they're supposed to */
3449 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 3450 case PTR_TO_PACKET_META:
f1174f77 3451 case PTR_TO_PACKET:
de8f3a83 3452 if (rcur->type != rold->type)
f1174f77
EC
3453 return false;
3454 /* We must have at least as much range as the old ptr
3455 * did, so that any accesses which were safe before are
3456 * still safe. This is true even if old range < old off,
3457 * since someone could have accessed through (ptr - k), or
3458 * even done ptr -= k in a register, to get a safe access.
3459 */
3460 if (rold->range > rcur->range)
3461 return false;
3462 /* If the offsets don't match, we can't trust our alignment;
3463 * nor can we be sure that we won't fall out of range.
3464 */
3465 if (rold->off != rcur->off)
3466 return false;
3467 /* id relations must be preserved */
3468 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
3469 return false;
3470 /* new val must satisfy old val knowledge */
3471 return range_within(rold, rcur) &&
3472 tnum_in(rold->var_off, rcur->var_off);
3473 case PTR_TO_CTX:
3474 case CONST_PTR_TO_MAP:
3475 case PTR_TO_STACK:
3476 case PTR_TO_PACKET_END:
3477 /* Only valid matches are exact, which memcmp() above
3478 * would have accepted
3479 */
3480 default:
3481 /* Don't know what's going on, just say it's not safe */
3482 return false;
3483 }
969bf05e 3484
f1174f77
EC
3485 /* Shouldn't get here; if we do, say it's not safe */
3486 WARN_ON_ONCE(1);
969bf05e
AS
3487 return false;
3488}
3489
f1bca824
AS
3490/* compare two verifier states
3491 *
3492 * all states stored in state_list are known to be valid, since
3493 * verifier reached 'bpf_exit' instruction through them
3494 *
3495 * this function is called when verifier exploring different branches of
3496 * execution popped from the state stack. If it sees an old state that has
3497 * more strict register state and more strict stack state then this execution
3498 * branch doesn't need to be explored further, since verifier already
3499 * concluded that more strict state leads to valid finish.
3500 *
3501 * Therefore two states are equivalent if register state is more conservative
3502 * and explored stack state is more conservative than the current one.
3503 * Example:
3504 * explored current
3505 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
3506 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
3507 *
3508 * In other words if current stack state (one being explored) has more
3509 * valid slots than old one that already passed validation, it means
3510 * the verifier can stop exploring and conclude that current state is valid too
3511 *
3512 * Similarly with registers. If explored state has register type as invalid
3513 * whereas register type in current state is meaningful, it means that
3514 * the current state will reach 'bpf_exit' instruction safely
3515 */
48461135
JB
3516static bool states_equal(struct bpf_verifier_env *env,
3517 struct bpf_verifier_state *old,
58e2af8b 3518 struct bpf_verifier_state *cur)
f1bca824 3519{
f1174f77
EC
3520 struct idpair *idmap;
3521 bool ret = false;
f1bca824
AS
3522 int i;
3523
f1174f77
EC
3524 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
3525 /* If we failed to allocate the idmap, just say it's not safe */
3526 if (!idmap)
1a0dc1ac 3527 return false;
f1174f77
EC
3528
3529 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 3530 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 3531 goto out_free;
f1bca824
AS
3532 }
3533
3534 for (i = 0; i < MAX_BPF_STACK; i++) {
9c399760
AS
3535 if (old->stack_slot_type[i] == STACK_INVALID)
3536 continue;
3537 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
3538 /* Ex: old explored (safe) state has STACK_SPILL in
3539 * this stack slot, but current has has STACK_MISC ->
3540 * this verifier states are not equivalent,
3541 * return false to continue verification of this path
3542 */
f1174f77 3543 goto out_free;
9c399760
AS
3544 if (i % BPF_REG_SIZE)
3545 continue;
d25da6ca
DB
3546 if (old->stack_slot_type[i] != STACK_SPILL)
3547 continue;
f1174f77
EC
3548 if (!regsafe(&old->spilled_regs[i / BPF_REG_SIZE],
3549 &cur->spilled_regs[i / BPF_REG_SIZE],
1b688a19 3550 idmap))
f1174f77
EC
3551 /* when explored and current stack slot are both storing
3552 * spilled registers, check that stored pointers types
9c399760
AS
3553 * are the same as well.
3554 * Ex: explored safe path could have stored
f1174f77 3555 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9c399760 3556 * but current path has stored:
f1174f77 3557 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9c399760
AS
3558 * such verifier states are not equivalent.
3559 * return false to continue verification of this path
3560 */
f1174f77 3561 goto out_free;
9c399760
AS
3562 else
3563 continue;
f1bca824 3564 }
f1174f77
EC
3565 ret = true;
3566out_free:
3567 kfree(idmap);
3568 return ret;
f1bca824
AS
3569}
3570
8e9cd9ce
EC
3571/* A write screens off any subsequent reads; but write marks come from the
3572 * straight-line code between a state and its parent. When we arrive at a
3573 * jump target (in the first iteration of the propagate_liveness() loop),
3574 * we didn't arrive by the straight-line code, so read marks in state must
3575 * propagate to parent regardless of state's write marks.
3576 */
dc503a8a
EC
3577static bool do_propagate_liveness(const struct bpf_verifier_state *state,
3578 struct bpf_verifier_state *parent)
3579{
63f45f84 3580 bool writes = parent == state->parent; /* Observe write marks */
dc503a8a
EC
3581 bool touched = false; /* any changes made? */
3582 int i;
3583
3584 if (!parent)
3585 return touched;
3586 /* Propagate read liveness of registers... */
3587 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
3588 /* We don't need to worry about FP liveness because it's read-only */
3589 for (i = 0; i < BPF_REG_FP; i++) {
3590 if (parent->regs[i].live & REG_LIVE_READ)
3591 continue;
63f45f84
EC
3592 if (writes && (state->regs[i].live & REG_LIVE_WRITTEN))
3593 continue;
3594 if (state->regs[i].live & REG_LIVE_READ) {
dc503a8a
EC
3595 parent->regs[i].live |= REG_LIVE_READ;
3596 touched = true;
3597 }
3598 }
3599 /* ... and stack slots */
3600 for (i = 0; i < MAX_BPF_STACK / BPF_REG_SIZE; i++) {
3601 if (parent->stack_slot_type[i * BPF_REG_SIZE] != STACK_SPILL)
3602 continue;
3603 if (state->stack_slot_type[i * BPF_REG_SIZE] != STACK_SPILL)
3604 continue;
3605 if (parent->spilled_regs[i].live & REG_LIVE_READ)
3606 continue;
63f45f84
EC
3607 if (writes && (state->spilled_regs[i].live & REG_LIVE_WRITTEN))
3608 continue;
3609 if (state->spilled_regs[i].live & REG_LIVE_READ) {
1ab2de2b 3610 parent->spilled_regs[i].live |= REG_LIVE_READ;
dc503a8a
EC
3611 touched = true;
3612 }
3613 }
3614 return touched;
3615}
3616
8e9cd9ce
EC
3617/* "parent" is "a state from which we reach the current state", but initially
3618 * it is not the state->parent (i.e. "the state whose straight-line code leads
3619 * to the current state"), instead it is the state that happened to arrive at
3620 * a (prunable) equivalent of the current state. See comment above
3621 * do_propagate_liveness() for consequences of this.
3622 * This function is just a more efficient way of calling mark_reg_read() or
3623 * mark_stack_slot_read() on each reg in "parent" that is read in "state",
3624 * though it requires that parent != state->parent in the call arguments.
3625 */
dc503a8a
EC
3626static void propagate_liveness(const struct bpf_verifier_state *state,
3627 struct bpf_verifier_state *parent)
3628{
3629 while (do_propagate_liveness(state, parent)) {
3630 /* Something changed, so we need to feed those changes onward */
3631 state = parent;
3632 parent = state->parent;
3633 }
3634}
3635
58e2af8b 3636static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 3637{
58e2af8b
JK
3638 struct bpf_verifier_state_list *new_sl;
3639 struct bpf_verifier_state_list *sl;
dc503a8a 3640 int i;
f1bca824
AS
3641
3642 sl = env->explored_states[insn_idx];
3643 if (!sl)
3644 /* this 'insn_idx' instruction wasn't marked, so we will not
3645 * be doing state search here
3646 */
3647 return 0;
3648
3649 while (sl != STATE_LIST_MARK) {
dc503a8a 3650 if (states_equal(env, &sl->state, &env->cur_state)) {
f1bca824 3651 /* reached equivalent register/stack state,
dc503a8a
EC
3652 * prune the search.
3653 * Registers read by the continuation are read by us.
8e9cd9ce
EC
3654 * If we have any write marks in env->cur_state, they
3655 * will prevent corresponding reads in the continuation
3656 * from reaching our parent (an explored_state). Our
3657 * own state will get the read marks recorded, but
3658 * they'll be immediately forgotten as we're pruning
3659 * this state and will pop a new one.
f1bca824 3660 */
dc503a8a 3661 propagate_liveness(&sl->state, &env->cur_state);
f1bca824 3662 return 1;
dc503a8a 3663 }
f1bca824
AS
3664 sl = sl->next;
3665 }
3666
3667 /* there were no equivalent states, remember current one.
3668 * technically the current state is not proven to be safe yet,
3669 * but it will either reach bpf_exit (which means it's safe) or
3670 * it will be rejected. Since there are no loops, we won't be
3671 * seeing this 'insn_idx' instruction again on the way to bpf_exit
3672 */
58e2af8b 3673 new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
f1bca824
AS
3674 if (!new_sl)
3675 return -ENOMEM;
3676
3677 /* add new state to the head of linked list */
3678 memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
3679 new_sl->next = env->explored_states[insn_idx];
3680 env->explored_states[insn_idx] = new_sl;
dc503a8a
EC
3681 /* connect new state to parentage chain */
3682 env->cur_state.parent = &new_sl->state;
8e9cd9ce
EC
3683 /* clear write marks in current state: the writes we did are not writes
3684 * our child did, so they don't screen off its reads from us.
3685 * (There are no read marks in current state, because reads always mark
3686 * their parent and current state never has children yet. Only
3687 * explored_states can get read marks.)
3688 */
dc503a8a
EC
3689 for (i = 0; i < BPF_REG_FP; i++)
3690 env->cur_state.regs[i].live = REG_LIVE_NONE;
3691 for (i = 0; i < MAX_BPF_STACK / BPF_REG_SIZE; i++)
3692 if (env->cur_state.stack_slot_type[i * BPF_REG_SIZE] == STACK_SPILL)
3693 env->cur_state.spilled_regs[i].live = REG_LIVE_NONE;
f1bca824
AS
3694 return 0;
3695}
3696
13a27dfc
JK
3697static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
3698 int insn_idx, int prev_insn_idx)
3699{
3700 if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
3701 return 0;
3702
3703 return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
3704}
3705
58e2af8b 3706static int do_check(struct bpf_verifier_env *env)
17a52670 3707{
58e2af8b 3708 struct bpf_verifier_state *state = &env->cur_state;
17a52670 3709 struct bpf_insn *insns = env->prog->insnsi;
58e2af8b 3710 struct bpf_reg_state *regs = state->regs;
17a52670
AS
3711 int insn_cnt = env->prog->len;
3712 int insn_idx, prev_insn_idx = 0;
3713 int insn_processed = 0;
3714 bool do_print_state = false;
3715
61bd5218 3716 init_reg_state(env, regs);
dc503a8a 3717 state->parent = NULL;
17a52670
AS
3718 insn_idx = 0;
3719 for (;;) {
3720 struct bpf_insn *insn;
3721 u8 class;
3722 int err;
3723
3724 if (insn_idx >= insn_cnt) {
61bd5218 3725 verbose(env, "invalid insn idx %d insn_cnt %d\n",
17a52670
AS
3726 insn_idx, insn_cnt);
3727 return -EFAULT;
3728 }
3729
3730 insn = &insns[insn_idx];
3731 class = BPF_CLASS(insn->code);
3732
07016151 3733 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
3734 verbose(env,
3735 "BPF program is too large. Processed %d insn\n",
17a52670
AS
3736 insn_processed);
3737 return -E2BIG;
3738 }
3739
f1bca824
AS
3740 err = is_state_visited(env, insn_idx);
3741 if (err < 0)
3742 return err;
3743 if (err == 1) {
3744 /* found equivalent state, can prune the search */
61bd5218 3745 if (env->log.level) {
f1bca824 3746 if (do_print_state)
61bd5218 3747 verbose(env, "\nfrom %d to %d: safe\n",
f1bca824
AS
3748 prev_insn_idx, insn_idx);
3749 else
61bd5218 3750 verbose(env, "%d: safe\n", insn_idx);
f1bca824
AS
3751 }
3752 goto process_bpf_exit;
3753 }
3754
3c2ce60b
DB
3755 if (need_resched())
3756 cond_resched();
3757
61bd5218
JK
3758 if (env->log.level > 1 || (env->log.level && do_print_state)) {
3759 if (env->log.level > 1)
3760 verbose(env, "%d:", insn_idx);
c5fc9692 3761 else
61bd5218 3762 verbose(env, "\nfrom %d to %d:",
c5fc9692 3763 prev_insn_idx, insn_idx);
61bd5218 3764 print_verifier_state(env, &env->cur_state);
17a52670
AS
3765 do_print_state = false;
3766 }
3767
61bd5218
JK
3768 if (env->log.level) {
3769 verbose(env, "%d: ", insn_idx);
0d0e5769 3770 print_bpf_insn(env, insn);
17a52670
AS
3771 }
3772
13a27dfc
JK
3773 err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
3774 if (err)
3775 return err;
3776
17a52670 3777 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 3778 err = check_alu_op(env, insn);
17a52670
AS
3779 if (err)
3780 return err;
3781
3782 } else if (class == BPF_LDX) {
3df126f3 3783 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
3784
3785 /* check for reserved fields is already done */
3786
17a52670 3787 /* check src operand */
dc503a8a 3788 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
3789 if (err)
3790 return err;
3791
dc503a8a 3792 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
3793 if (err)
3794 return err;
3795
725f9dcd
AS
3796 src_reg_type = regs[insn->src_reg].type;
3797
17a52670
AS
3798 /* check that memory (src_reg + off) is readable,
3799 * the state of dst_reg will be updated by this func
3800 */
31fd8581 3801 err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
17a52670
AS
3802 BPF_SIZE(insn->code), BPF_READ,
3803 insn->dst_reg);
3804 if (err)
3805 return err;
3806
3df126f3
JK
3807 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
3808
3809 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
3810 /* saw a valid insn
3811 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 3812 * save type to validate intersecting paths
9bac3d6d 3813 */
3df126f3 3814 *prev_src_type = src_reg_type;
9bac3d6d 3815
3df126f3 3816 } else if (src_reg_type != *prev_src_type &&
9bac3d6d 3817 (src_reg_type == PTR_TO_CTX ||
3df126f3 3818 *prev_src_type == PTR_TO_CTX)) {
9bac3d6d
AS
3819 /* ABuser program is trying to use the same insn
3820 * dst_reg = *(u32*) (src_reg + off)
3821 * with different pointer types:
3822 * src_reg == ctx in one branch and
3823 * src_reg == stack|map in some other branch.
3824 * Reject it.
3825 */
61bd5218 3826 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
3827 return -EINVAL;
3828 }
3829
17a52670 3830 } else if (class == BPF_STX) {
3df126f3 3831 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 3832
17a52670 3833 if (BPF_MODE(insn->code) == BPF_XADD) {
31fd8581 3834 err = check_xadd(env, insn_idx, insn);
17a52670
AS
3835 if (err)
3836 return err;
3837 insn_idx++;
3838 continue;
3839 }
3840
17a52670 3841 /* check src1 operand */
dc503a8a 3842 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
3843 if (err)
3844 return err;
3845 /* check src2 operand */
dc503a8a 3846 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
3847 if (err)
3848 return err;
3849
d691f9e8
AS
3850 dst_reg_type = regs[insn->dst_reg].type;
3851
17a52670 3852 /* check that memory (dst_reg + off) is writeable */
31fd8581 3853 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
17a52670
AS
3854 BPF_SIZE(insn->code), BPF_WRITE,
3855 insn->src_reg);
3856 if (err)
3857 return err;
3858
3df126f3
JK
3859 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
3860
3861 if (*prev_dst_type == NOT_INIT) {
3862 *prev_dst_type = dst_reg_type;
3863 } else if (dst_reg_type != *prev_dst_type &&
d691f9e8 3864 (dst_reg_type == PTR_TO_CTX ||
3df126f3 3865 *prev_dst_type == PTR_TO_CTX)) {
61bd5218 3866 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
3867 return -EINVAL;
3868 }
3869
17a52670
AS
3870 } else if (class == BPF_ST) {
3871 if (BPF_MODE(insn->code) != BPF_MEM ||
3872 insn->src_reg != BPF_REG_0) {
61bd5218 3873 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
3874 return -EINVAL;
3875 }
3876 /* check src operand */
dc503a8a 3877 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
3878 if (err)
3879 return err;
3880
3881 /* check that memory (dst_reg + off) is writeable */
31fd8581 3882 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
17a52670
AS
3883 BPF_SIZE(insn->code), BPF_WRITE,
3884 -1);
3885 if (err)
3886 return err;
3887
3888 } else if (class == BPF_JMP) {
3889 u8 opcode = BPF_OP(insn->code);
3890
3891 if (opcode == BPF_CALL) {
3892 if (BPF_SRC(insn->code) != BPF_K ||
3893 insn->off != 0 ||
3894 insn->src_reg != BPF_REG_0 ||
3895 insn->dst_reg != BPF_REG_0) {
61bd5218 3896 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
3897 return -EINVAL;
3898 }
3899
81ed18ab 3900 err = check_call(env, insn->imm, insn_idx);
17a52670
AS
3901 if (err)
3902 return err;
3903
3904 } else if (opcode == BPF_JA) {
3905 if (BPF_SRC(insn->code) != BPF_K ||
3906 insn->imm != 0 ||
3907 insn->src_reg != BPF_REG_0 ||
3908 insn->dst_reg != BPF_REG_0) {
61bd5218 3909 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
3910 return -EINVAL;
3911 }
3912
3913 insn_idx += insn->off + 1;
3914 continue;
3915
3916 } else if (opcode == BPF_EXIT) {
3917 if (BPF_SRC(insn->code) != BPF_K ||
3918 insn->imm != 0 ||
3919 insn->src_reg != BPF_REG_0 ||
3920 insn->dst_reg != BPF_REG_0) {
61bd5218 3921 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
3922 return -EINVAL;
3923 }
3924
3925 /* eBPF calling convetion is such that R0 is used
3926 * to return the value from eBPF program.
3927 * Make sure that it's readable at this time
3928 * of bpf_exit, which means that program wrote
3929 * something into it earlier
3930 */
dc503a8a 3931 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
17a52670
AS
3932 if (err)
3933 return err;
3934
1be7f75d 3935 if (is_pointer_value(env, BPF_REG_0)) {
61bd5218 3936 verbose(env, "R0 leaks addr as return value\n");
1be7f75d
AS
3937 return -EACCES;
3938 }
3939
390ee7e2
AS
3940 err = check_return_code(env);
3941 if (err)
3942 return err;
f1bca824 3943process_bpf_exit:
17a52670
AS
3944 insn_idx = pop_stack(env, &prev_insn_idx);
3945 if (insn_idx < 0) {
3946 break;
3947 } else {
3948 do_print_state = true;
3949 continue;
3950 }
3951 } else {
3952 err = check_cond_jmp_op(env, insn, &insn_idx);
3953 if (err)
3954 return err;
3955 }
3956 } else if (class == BPF_LD) {
3957 u8 mode = BPF_MODE(insn->code);
3958
3959 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
3960 err = check_ld_abs(env, insn);
3961 if (err)
3962 return err;
3963
17a52670
AS
3964 } else if (mode == BPF_IMM) {
3965 err = check_ld_imm(env, insn);
3966 if (err)
3967 return err;
3968
3969 insn_idx++;
3970 } else {
61bd5218 3971 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
3972 return -EINVAL;
3973 }
3974 } else {
61bd5218 3975 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
3976 return -EINVAL;
3977 }
3978
3979 insn_idx++;
3980 }
3981
61bd5218
JK
3982 verbose(env, "processed %d insns, stack depth %d\n", insn_processed,
3983 env->prog->aux->stack_depth);
17a52670
AS
3984 return 0;
3985}
3986
56f668df
MKL
3987static int check_map_prealloc(struct bpf_map *map)
3988{
3989 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
3990 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
3991 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
3992 !(map->map_flags & BPF_F_NO_PREALLOC);
3993}
3994
61bd5218
JK
3995static int check_map_prog_compatibility(struct bpf_verifier_env *env,
3996 struct bpf_map *map,
fdc15d38
AS
3997 struct bpf_prog *prog)
3998
3999{
56f668df
MKL
4000 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4001 * preallocated hash maps, since doing memory allocation
4002 * in overflow_handler can crash depending on where nmi got
4003 * triggered.
4004 */
4005 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
4006 if (!check_map_prealloc(map)) {
61bd5218 4007 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
4008 return -EINVAL;
4009 }
4010 if (map->inner_map_meta &&
4011 !check_map_prealloc(map->inner_map_meta)) {
61bd5218 4012 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
56f668df
MKL
4013 return -EINVAL;
4014 }
fdc15d38
AS
4015 }
4016 return 0;
4017}
4018
0246e64d
AS
4019/* look for pseudo eBPF instructions that access map FDs and
4020 * replace them with actual map pointers
4021 */
58e2af8b 4022static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
4023{
4024 struct bpf_insn *insn = env->prog->insnsi;
4025 int insn_cnt = env->prog->len;
fdc15d38 4026 int i, j, err;
0246e64d 4027
f1f7714e 4028 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
4029 if (err)
4030 return err;
4031
0246e64d 4032 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 4033 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 4034 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 4035 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
4036 return -EINVAL;
4037 }
4038
d691f9e8
AS
4039 if (BPF_CLASS(insn->code) == BPF_STX &&
4040 ((BPF_MODE(insn->code) != BPF_MEM &&
4041 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 4042 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
4043 return -EINVAL;
4044 }
4045
0246e64d
AS
4046 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
4047 struct bpf_map *map;
4048 struct fd f;
4049
4050 if (i == insn_cnt - 1 || insn[1].code != 0 ||
4051 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
4052 insn[1].off != 0) {
61bd5218 4053 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
4054 return -EINVAL;
4055 }
4056
4057 if (insn->src_reg == 0)
4058 /* valid generic load 64-bit imm */
4059 goto next_insn;
4060
4061 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
61bd5218
JK
4062 verbose(env,
4063 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
4064 return -EINVAL;
4065 }
4066
4067 f = fdget(insn->imm);
c2101297 4068 map = __bpf_map_get(f);
0246e64d 4069 if (IS_ERR(map)) {
61bd5218 4070 verbose(env, "fd %d is not pointing to valid bpf_map\n",
0246e64d 4071 insn->imm);
0246e64d
AS
4072 return PTR_ERR(map);
4073 }
4074
61bd5218 4075 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
4076 if (err) {
4077 fdput(f);
4078 return err;
4079 }
4080
0246e64d
AS
4081 /* store map pointer inside BPF_LD_IMM64 instruction */
4082 insn[0].imm = (u32) (unsigned long) map;
4083 insn[1].imm = ((u64) (unsigned long) map) >> 32;
4084
4085 /* check whether we recorded this map already */
4086 for (j = 0; j < env->used_map_cnt; j++)
4087 if (env->used_maps[j] == map) {
4088 fdput(f);
4089 goto next_insn;
4090 }
4091
4092 if (env->used_map_cnt >= MAX_USED_MAPS) {
4093 fdput(f);
4094 return -E2BIG;
4095 }
4096
0246e64d
AS
4097 /* hold the map. If the program is rejected by verifier,
4098 * the map will be released by release_maps() or it
4099 * will be used by the valid program until it's unloaded
4100 * and all maps are released in free_bpf_prog_info()
4101 */
92117d84
AS
4102 map = bpf_map_inc(map, false);
4103 if (IS_ERR(map)) {
4104 fdput(f);
4105 return PTR_ERR(map);
4106 }
4107 env->used_maps[env->used_map_cnt++] = map;
4108
0246e64d
AS
4109 fdput(f);
4110next_insn:
4111 insn++;
4112 i++;
4113 }
4114 }
4115
4116 /* now all pseudo BPF_LD_IMM64 instructions load valid
4117 * 'struct bpf_map *' into a register instead of user map_fd.
4118 * These pointers will be used later by verifier to validate map access.
4119 */
4120 return 0;
4121}
4122
4123/* drop refcnt of maps used by the rejected program */
58e2af8b 4124static void release_maps(struct bpf_verifier_env *env)
0246e64d
AS
4125{
4126 int i;
4127
4128 for (i = 0; i < env->used_map_cnt; i++)
4129 bpf_map_put(env->used_maps[i]);
4130}
4131
4132/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 4133static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
4134{
4135 struct bpf_insn *insn = env->prog->insnsi;
4136 int insn_cnt = env->prog->len;
4137 int i;
4138
4139 for (i = 0; i < insn_cnt; i++, insn++)
4140 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
4141 insn->src_reg = 0;
4142}
4143
8041902d
AS
4144/* single env->prog->insni[off] instruction was replaced with the range
4145 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
4146 * [0, off) and [off, end) to new locations, so the patched range stays zero
4147 */
4148static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
4149 u32 off, u32 cnt)
4150{
4151 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
4152
4153 if (cnt == 1)
4154 return 0;
4155 new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
4156 if (!new_data)
4157 return -ENOMEM;
4158 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
4159 memcpy(new_data + off + cnt - 1, old_data + off,
4160 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
4161 env->insn_aux_data = new_data;
4162 vfree(old_data);
4163 return 0;
4164}
4165
4166static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
4167 const struct bpf_insn *patch, u32 len)
4168{
4169 struct bpf_prog *new_prog;
4170
4171 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4172 if (!new_prog)
4173 return NULL;
4174 if (adjust_insn_aux_data(env, new_prog->len, off, len))
4175 return NULL;
4176 return new_prog;
4177}
4178
9bac3d6d
AS
4179/* convert load instructions that access fields of 'struct __sk_buff'
4180 * into sequence of instructions that access fields of 'struct sk_buff'
4181 */
58e2af8b 4182static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 4183{
36bbef52 4184 const struct bpf_verifier_ops *ops = env->prog->aux->ops;
f96da094 4185 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 4186 const int insn_cnt = env->prog->len;
36bbef52 4187 struct bpf_insn insn_buf[16], *insn;
9bac3d6d 4188 struct bpf_prog *new_prog;
d691f9e8 4189 enum bpf_access_type type;
f96da094
DB
4190 bool is_narrower_load;
4191 u32 target_size;
9bac3d6d 4192
36bbef52
DB
4193 if (ops->gen_prologue) {
4194 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
4195 env->prog);
4196 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 4197 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
4198 return -EINVAL;
4199 } else if (cnt) {
8041902d 4200 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
4201 if (!new_prog)
4202 return -ENOMEM;
8041902d 4203
36bbef52 4204 env->prog = new_prog;
3df126f3 4205 delta += cnt - 1;
36bbef52
DB
4206 }
4207 }
4208
4209 if (!ops->convert_ctx_access)
9bac3d6d
AS
4210 return 0;
4211
3df126f3 4212 insn = env->prog->insnsi + delta;
36bbef52 4213
9bac3d6d 4214 for (i = 0; i < insn_cnt; i++, insn++) {
62c7989b
DB
4215 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
4216 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
4217 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 4218 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 4219 type = BPF_READ;
62c7989b
DB
4220 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
4221 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
4222 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 4223 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
4224 type = BPF_WRITE;
4225 else
9bac3d6d
AS
4226 continue;
4227
8041902d 4228 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
9bac3d6d 4229 continue;
9bac3d6d 4230
31fd8581 4231 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 4232 size = BPF_LDST_BYTES(insn);
31fd8581
YS
4233
4234 /* If the read access is a narrower load of the field,
4235 * convert to a 4/8-byte load, to minimum program type specific
4236 * convert_ctx_access changes. If conversion is successful,
4237 * we will apply proper mask to the result.
4238 */
f96da094 4239 is_narrower_load = size < ctx_field_size;
31fd8581 4240 if (is_narrower_load) {
f96da094
DB
4241 u32 off = insn->off;
4242 u8 size_code;
4243
4244 if (type == BPF_WRITE) {
61bd5218 4245 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
4246 return -EINVAL;
4247 }
31fd8581 4248
f96da094 4249 size_code = BPF_H;
31fd8581
YS
4250 if (ctx_field_size == 4)
4251 size_code = BPF_W;
4252 else if (ctx_field_size == 8)
4253 size_code = BPF_DW;
f96da094 4254
31fd8581
YS
4255 insn->off = off & ~(ctx_field_size - 1);
4256 insn->code = BPF_LDX | BPF_MEM | size_code;
4257 }
f96da094
DB
4258
4259 target_size = 0;
4260 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
4261 &target_size);
4262 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
4263 (ctx_field_size && !target_size)) {
61bd5218 4264 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
4265 return -EINVAL;
4266 }
f96da094
DB
4267
4268 if (is_narrower_load && size < target_size) {
31fd8581
YS
4269 if (ctx_field_size <= 4)
4270 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 4271 (1 << size * 8) - 1);
31fd8581
YS
4272 else
4273 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
f96da094 4274 (1 << size * 8) - 1);
31fd8581 4275 }
9bac3d6d 4276
8041902d 4277 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
4278 if (!new_prog)
4279 return -ENOMEM;
4280
3df126f3 4281 delta += cnt - 1;
9bac3d6d
AS
4282
4283 /* keep walking new program and skip insns we just inserted */
4284 env->prog = new_prog;
3df126f3 4285 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
4286 }
4287
4288 return 0;
4289}
4290
79741b3b 4291/* fixup insn->imm field of bpf_call instructions
81ed18ab 4292 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
4293 *
4294 * this function is called after eBPF program passed verification
4295 */
79741b3b 4296static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 4297{
79741b3b
AS
4298 struct bpf_prog *prog = env->prog;
4299 struct bpf_insn *insn = prog->insnsi;
e245c5c6 4300 const struct bpf_func_proto *fn;
79741b3b 4301 const int insn_cnt = prog->len;
81ed18ab
AS
4302 struct bpf_insn insn_buf[16];
4303 struct bpf_prog *new_prog;
4304 struct bpf_map *map_ptr;
4305 int i, cnt, delta = 0;
e245c5c6 4306
79741b3b
AS
4307 for (i = 0; i < insn_cnt; i++, insn++) {
4308 if (insn->code != (BPF_JMP | BPF_CALL))
4309 continue;
e245c5c6 4310
79741b3b
AS
4311 if (insn->imm == BPF_FUNC_get_route_realm)
4312 prog->dst_needed = 1;
4313 if (insn->imm == BPF_FUNC_get_prandom_u32)
4314 bpf_user_rnd_init_once();
79741b3b 4315 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
4316 /* If we tail call into other programs, we
4317 * cannot make any assumptions since they can
4318 * be replaced dynamically during runtime in
4319 * the program array.
4320 */
4321 prog->cb_access = 1;
80a58d02 4322 env->prog->aux->stack_depth = MAX_BPF_STACK;
7b9f6da1 4323
79741b3b
AS
4324 /* mark bpf_tail_call as different opcode to avoid
4325 * conditional branch in the interpeter for every normal
4326 * call and to prevent accidental JITing by JIT compiler
4327 * that doesn't support bpf_tail_call yet
e245c5c6 4328 */
79741b3b 4329 insn->imm = 0;
71189fa9 4330 insn->code = BPF_JMP | BPF_TAIL_CALL;
79741b3b
AS
4331 continue;
4332 }
e245c5c6 4333
89c63074
DB
4334 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
4335 * handlers are currently limited to 64 bit only.
4336 */
4337 if (ebpf_jit_enabled() && BITS_PER_LONG == 64 &&
4338 insn->imm == BPF_FUNC_map_lookup_elem) {
81ed18ab 4339 map_ptr = env->insn_aux_data[i + delta].map_ptr;
fad73a1a
MKL
4340 if (map_ptr == BPF_MAP_PTR_POISON ||
4341 !map_ptr->ops->map_gen_lookup)
81ed18ab
AS
4342 goto patch_call_imm;
4343
4344 cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
4345 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 4346 verbose(env, "bpf verifier is misconfigured\n");
81ed18ab
AS
4347 return -EINVAL;
4348 }
4349
4350 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
4351 cnt);
4352 if (!new_prog)
4353 return -ENOMEM;
4354
4355 delta += cnt - 1;
4356
4357 /* keep walking new program and skip insns we just inserted */
4358 env->prog = prog = new_prog;
4359 insn = new_prog->insnsi + i + delta;
4360 continue;
4361 }
4362
109980b8 4363 if (insn->imm == BPF_FUNC_redirect_map) {
7c300131
DB
4364 /* Note, we cannot use prog directly as imm as subsequent
4365 * rewrites would still change the prog pointer. The only
4366 * stable address we can use is aux, which also works with
4367 * prog clones during blinding.
4368 */
4369 u64 addr = (unsigned long)prog->aux;
109980b8
DB
4370 struct bpf_insn r4_ld[] = {
4371 BPF_LD_IMM64(BPF_REG_4, addr),
4372 *insn,
4373 };
4374 cnt = ARRAY_SIZE(r4_ld);
4375
4376 new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
4377 if (!new_prog)
4378 return -ENOMEM;
4379
4380 delta += cnt - 1;
4381 env->prog = prog = new_prog;
4382 insn = new_prog->insnsi + i + delta;
4383 }
81ed18ab 4384patch_call_imm:
79741b3b
AS
4385 fn = prog->aux->ops->get_func_proto(insn->imm);
4386 /* all functions that have prototype and verifier allowed
4387 * programs to call them, must be real in-kernel functions
4388 */
4389 if (!fn->func) {
61bd5218
JK
4390 verbose(env,
4391 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
4392 func_id_name(insn->imm), insn->imm);
4393 return -EFAULT;
e245c5c6 4394 }
79741b3b 4395 insn->imm = fn->func - __bpf_call_base;
e245c5c6 4396 }
e245c5c6 4397
79741b3b
AS
4398 return 0;
4399}
e245c5c6 4400
58e2af8b 4401static void free_states(struct bpf_verifier_env *env)
f1bca824 4402{
58e2af8b 4403 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
4404 int i;
4405
4406 if (!env->explored_states)
4407 return;
4408
4409 for (i = 0; i < env->prog->len; i++) {
4410 sl = env->explored_states[i];
4411
4412 if (sl)
4413 while (sl != STATE_LIST_MARK) {
4414 sln = sl->next;
4415 kfree(sl);
4416 sl = sln;
4417 }
4418 }
4419
4420 kfree(env->explored_states);
4421}
4422
9bac3d6d 4423int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
51580e79 4424{
58e2af8b 4425 struct bpf_verifier_env *env;
61bd5218 4426 struct bpf_verifer_log *log;
51580e79
AS
4427 int ret = -EINVAL;
4428
58e2af8b 4429 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
4430 * allocate/free it every time bpf_check() is called
4431 */
58e2af8b 4432 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
4433 if (!env)
4434 return -ENOMEM;
61bd5218 4435 log = &env->log;
cbd35700 4436
3df126f3
JK
4437 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
4438 (*prog)->len);
4439 ret = -ENOMEM;
4440 if (!env->insn_aux_data)
4441 goto err_free_env;
9bac3d6d 4442 env->prog = *prog;
0246e64d 4443
cbd35700
AS
4444 /* grab the mutex to protect few globals used by verifier */
4445 mutex_lock(&bpf_verifier_lock);
4446
4447 if (attr->log_level || attr->log_buf || attr->log_size) {
4448 /* user requested verbose verifier output
4449 * and supplied buffer to store the verification trace
4450 */
e7bf8249
JK
4451 log->level = attr->log_level;
4452 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
4453 log->len_total = attr->log_size;
cbd35700
AS
4454
4455 ret = -EINVAL;
e7bf8249
JK
4456 /* log attributes have to be sane */
4457 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
4458 !log->level || !log->ubuf)
3df126f3 4459 goto err_unlock;
cbd35700
AS
4460
4461 ret = -ENOMEM;
e7bf8249
JK
4462 log->kbuf = vmalloc(log->len_total);
4463 if (!log->kbuf)
3df126f3 4464 goto err_unlock;
cbd35700 4465 }
1ad2f583
DB
4466
4467 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
4468 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 4469 env->strict_alignment = true;
cbd35700 4470
0246e64d
AS
4471 ret = replace_map_fd_with_map_ptr(env);
4472 if (ret < 0)
4473 goto skip_full_check;
4474
9bac3d6d 4475 env->explored_states = kcalloc(env->prog->len,
58e2af8b 4476 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
4477 GFP_USER);
4478 ret = -ENOMEM;
4479 if (!env->explored_states)
4480 goto skip_full_check;
4481
475fb78f
AS
4482 ret = check_cfg(env);
4483 if (ret < 0)
4484 goto skip_full_check;
4485
1be7f75d
AS
4486 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
4487
17a52670 4488 ret = do_check(env);
cbd35700 4489
0246e64d 4490skip_full_check:
17a52670 4491 while (pop_stack(env, NULL) >= 0);
f1bca824 4492 free_states(env);
0246e64d 4493
9bac3d6d
AS
4494 if (ret == 0)
4495 /* program is valid, convert *(u32*)(ctx + off) accesses */
4496 ret = convert_ctx_accesses(env);
4497
e245c5c6 4498 if (ret == 0)
79741b3b 4499 ret = fixup_bpf_calls(env);
e245c5c6 4500
e7bf8249
JK
4501 if (log->level && bpf_verifier_log_full(log)) {
4502 BUG_ON(log->len_used >= log->len_total);
cbd35700
AS
4503 /* verifier log exceeded user supplied buffer */
4504 ret = -ENOSPC;
4505 /* fall through to return what was recorded */
4506 }
4507
4508 /* copy verifier log back to user space including trailing zero */
e7bf8249
JK
4509 if (log->level && copy_to_user(log->ubuf, log->kbuf,
4510 log->len_used + 1) != 0) {
cbd35700
AS
4511 ret = -EFAULT;
4512 goto free_log_buf;
4513 }
4514
0246e64d
AS
4515 if (ret == 0 && env->used_map_cnt) {
4516 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
4517 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
4518 sizeof(env->used_maps[0]),
4519 GFP_KERNEL);
0246e64d 4520
9bac3d6d 4521 if (!env->prog->aux->used_maps) {
0246e64d
AS
4522 ret = -ENOMEM;
4523 goto free_log_buf;
4524 }
4525
9bac3d6d 4526 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 4527 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 4528 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
4529
4530 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
4531 * bpf_ld_imm64 instructions
4532 */
4533 convert_pseudo_ld_imm64(env);
4534 }
cbd35700
AS
4535
4536free_log_buf:
e7bf8249
JK
4537 if (log->level)
4538 vfree(log->kbuf);
9bac3d6d 4539 if (!env->prog->aux->used_maps)
0246e64d
AS
4540 /* if we didn't copy map pointers into bpf_prog_info, release
4541 * them now. Otherwise free_bpf_prog_info() will release them.
4542 */
4543 release_maps(env);
9bac3d6d 4544 *prog = env->prog;
3df126f3 4545err_unlock:
cbd35700 4546 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
4547 vfree(env->insn_aux_data);
4548err_free_env:
4549 kfree(env);
51580e79
AS
4550 return ret;
4551}
13a27dfc
JK
4552
4553int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
4554 void *priv)
4555{
4556 struct bpf_verifier_env *env;
4557 int ret;
4558
4559 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
4560 if (!env)
4561 return -ENOMEM;
4562
4563 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
4564 prog->len);
4565 ret = -ENOMEM;
4566 if (!env->insn_aux_data)
4567 goto err_free_env;
4568 env->prog = prog;
4569 env->analyzer_ops = ops;
4570 env->analyzer_priv = priv;
4571
4572 /* grab the mutex to protect few globals used by verifier */
4573 mutex_lock(&bpf_verifier_lock);
4574
e07b98d9 4575 env->strict_alignment = false;
1ad2f583
DB
4576 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
4577 env->strict_alignment = true;
13a27dfc
JK
4578
4579 env->explored_states = kcalloc(env->prog->len,
4580 sizeof(struct bpf_verifier_state_list *),
4581 GFP_KERNEL);
4582 ret = -ENOMEM;
4583 if (!env->explored_states)
4584 goto skip_full_check;
4585
4586 ret = check_cfg(env);
4587 if (ret < 0)
4588 goto skip_full_check;
4589
4590 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
4591
4592 ret = do_check(env);
4593
4594skip_full_check:
4595 while (pop_stack(env, NULL) >= 0);
4596 free_states(env);
4597
4598 mutex_unlock(&bpf_verifier_lock);
4599 vfree(env->insn_aux_data);
4600err_free_env:
4601 kfree(env);
4602 return ret;
4603}
4604EXPORT_SYMBOL_GPL(bpf_analyzer);