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