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