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