]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - kernel/bpf/verifier.c
net: dev: Fix non-RCU based lower dev walker
[mirror_ubuntu-bionic-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>
22
23/* bpf_check() is a static code analyzer that walks eBPF program
24 * instruction by instruction and updates register/stack state.
25 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
26 *
27 * The first pass is depth-first-search to check that the program is a DAG.
28 * It rejects the following programs:
29 * - larger than BPF_MAXINSNS insns
30 * - if loop is present (detected via back-edge)
31 * - unreachable insns exist (shouldn't be a forest. program = one function)
32 * - out of bounds or malformed jumps
33 * The second pass is all possible path descent from the 1st insn.
34 * Since it's analyzing all pathes through the program, the length of the
35 * analysis is limited to 32k insn, which may be hit even if total number of
36 * insn is less then 4K, but there are too many branches that change stack/regs.
37 * Number of 'branches to be analyzed' is limited to 1k
38 *
39 * On entry to each instruction, each register has a type, and the instruction
40 * changes the types of the registers depending on instruction semantics.
41 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
42 * copied to R1.
43 *
44 * All registers are 64-bit.
45 * R0 - return register
46 * R1-R5 argument passing registers
47 * R6-R9 callee saved registers
48 * R10 - frame pointer read-only
49 *
50 * At the start of BPF program the register R1 contains a pointer to bpf_context
51 * and has type PTR_TO_CTX.
52 *
53 * Verifier tracks arithmetic operations on pointers in case:
54 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
55 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
56 * 1st insn copies R10 (which has FRAME_PTR) type into R1
57 * and 2nd arithmetic instruction is pattern matched to recognize
58 * that it wants to construct a pointer to some element within stack.
59 * So after 2nd insn, the register R1 has type PTR_TO_STACK
60 * (and -20 constant is saved for further stack bounds checking).
61 * Meaning that this reg is a pointer to stack plus known immediate constant.
62 *
63 * Most of the time the registers have UNKNOWN_VALUE type, which
64 * means the register has some value, but it's not a valid pointer.
65 * (like pointer plus pointer becomes UNKNOWN_VALUE type)
66 *
67 * When verifier sees load or store instructions the type of base register
68 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
69 * types recognized by check_mem_access() function.
70 *
71 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
72 * and the range of [ptr, ptr + map's value_size) is accessible.
73 *
74 * registers used to pass values to function calls are checked against
75 * function argument constraints.
76 *
77 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
78 * It means that the register type passed to this function must be
79 * PTR_TO_STACK and it will be used inside the function as
80 * 'pointer to map element key'
81 *
82 * For example the argument constraints for bpf_map_lookup_elem():
83 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
84 * .arg1_type = ARG_CONST_MAP_PTR,
85 * .arg2_type = ARG_PTR_TO_MAP_KEY,
86 *
87 * ret_type says that this function returns 'pointer to map elem value or null'
88 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
89 * 2nd argument should be a pointer to stack, which will be used inside
90 * the helper function as a pointer to map element key.
91 *
92 * On the kernel side the helper function looks like:
93 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
94 * {
95 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
96 * void *key = (void *) (unsigned long) r2;
97 * void *value;
98 *
99 * here kernel can access 'key' and 'map' pointers safely, knowing that
100 * [key, key + map->key_size) bytes are valid and were initialized on
101 * the stack of eBPF program.
102 * }
103 *
104 * Corresponding eBPF program may look like:
105 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
106 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
107 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
108 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
109 * here verifier looks at prototype of map_lookup_elem() and sees:
110 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
111 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
112 *
113 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
114 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
115 * and were initialized prior to this call.
116 * If it's ok, then verifier allows this BPF_CALL insn and looks at
117 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
118 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
119 * returns ether pointer to map value or NULL.
120 *
121 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
122 * insn, the register holding that pointer in the true branch changes state to
123 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
124 * branch. See check_cond_jmp_op().
125 *
126 * After the call R0 is set to return type of the function and registers R1-R5
127 * are set to NOT_INIT to indicate that they are no longer readable.
128 */
129
17a52670 130/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 131struct bpf_verifier_stack_elem {
17a52670
AS
132 /* verifer state is 'st'
133 * before processing instruction 'insn_idx'
134 * and after processing instruction 'prev_insn_idx'
135 */
58e2af8b 136 struct bpf_verifier_state st;
17a52670
AS
137 int insn_idx;
138 int prev_insn_idx;
58e2af8b 139 struct bpf_verifier_stack_elem *next;
cbd35700
AS
140};
141
07016151
DB
142#define BPF_COMPLEXITY_LIMIT_INSNS 65536
143#define BPF_COMPLEXITY_LIMIT_STACK 1024
144
33ff9823
DB
145struct bpf_call_arg_meta {
146 struct bpf_map *map_ptr;
435faee1 147 bool raw_mode;
36bbef52 148 bool pkt_access;
435faee1
DB
149 int regno;
150 int access_size;
33ff9823
DB
151};
152
cbd35700
AS
153/* verbose verifier prints what it's seeing
154 * bpf_check() is called under lock, so no race to access these global vars
155 */
156static u32 log_level, log_size, log_len;
157static char *log_buf;
158
159static DEFINE_MUTEX(bpf_verifier_lock);
160
161/* log_level controls verbosity level of eBPF verifier.
162 * verbose() is used to dump the verification trace to the log, so the user
163 * can figure out what's wrong with the program
164 */
1d056d9c 165static __printf(1, 2) void verbose(const char *fmt, ...)
cbd35700
AS
166{
167 va_list args;
168
169 if (log_level == 0 || log_len >= log_size - 1)
170 return;
171
172 va_start(args, fmt);
173 log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
174 va_end(args);
175}
176
17a52670
AS
177/* string representation of 'enum bpf_reg_type' */
178static const char * const reg_type_str[] = {
179 [NOT_INIT] = "?",
180 [UNKNOWN_VALUE] = "inv",
181 [PTR_TO_CTX] = "ctx",
182 [CONST_PTR_TO_MAP] = "map_ptr",
183 [PTR_TO_MAP_VALUE] = "map_value",
184 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
48461135 185 [PTR_TO_MAP_VALUE_ADJ] = "map_value_adj",
17a52670
AS
186 [FRAME_PTR] = "fp",
187 [PTR_TO_STACK] = "fp",
188 [CONST_IMM] = "imm",
969bf05e
AS
189 [PTR_TO_PACKET] = "pkt",
190 [PTR_TO_PACKET_END] = "pkt_end",
17a52670
AS
191};
192
58e2af8b 193static void print_verifier_state(struct bpf_verifier_state *state)
17a52670 194{
58e2af8b 195 struct bpf_reg_state *reg;
17a52670
AS
196 enum bpf_reg_type t;
197 int i;
198
199 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
200 reg = &state->regs[i];
201 t = reg->type;
17a52670
AS
202 if (t == NOT_INIT)
203 continue;
204 verbose(" R%d=%s", i, reg_type_str[t]);
205 if (t == CONST_IMM || t == PTR_TO_STACK)
969bf05e
AS
206 verbose("%lld", reg->imm);
207 else if (t == PTR_TO_PACKET)
208 verbose("(id=%d,off=%d,r=%d)",
209 reg->id, reg->off, reg->range);
210 else if (t == UNKNOWN_VALUE && reg->imm)
211 verbose("%lld", reg->imm);
17a52670 212 else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
48461135
JB
213 t == PTR_TO_MAP_VALUE_OR_NULL ||
214 t == PTR_TO_MAP_VALUE_ADJ)
57a09bf0 215 verbose("(ks=%d,vs=%d,id=%u)",
1a0dc1ac 216 reg->map_ptr->key_size,
57a09bf0
TG
217 reg->map_ptr->value_size,
218 reg->id);
48461135
JB
219 if (reg->min_value != BPF_REGISTER_MIN_RANGE)
220 verbose(",min_value=%llu",
221 (unsigned long long)reg->min_value);
222 if (reg->max_value != BPF_REGISTER_MAX_RANGE)
223 verbose(",max_value=%llu",
224 (unsigned long long)reg->max_value);
17a52670 225 }
9c399760 226 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1a0dc1ac 227 if (state->stack_slot_type[i] == STACK_SPILL)
17a52670 228 verbose(" fp%d=%s", -MAX_BPF_STACK + i,
1a0dc1ac 229 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
17a52670
AS
230 }
231 verbose("\n");
232}
233
cbd35700
AS
234static const char *const bpf_class_string[] = {
235 [BPF_LD] = "ld",
236 [BPF_LDX] = "ldx",
237 [BPF_ST] = "st",
238 [BPF_STX] = "stx",
239 [BPF_ALU] = "alu",
240 [BPF_JMP] = "jmp",
241 [BPF_RET] = "BUG",
242 [BPF_ALU64] = "alu64",
243};
244
687f0715 245static const char *const bpf_alu_string[16] = {
cbd35700
AS
246 [BPF_ADD >> 4] = "+=",
247 [BPF_SUB >> 4] = "-=",
248 [BPF_MUL >> 4] = "*=",
249 [BPF_DIV >> 4] = "/=",
250 [BPF_OR >> 4] = "|=",
251 [BPF_AND >> 4] = "&=",
252 [BPF_LSH >> 4] = "<<=",
253 [BPF_RSH >> 4] = ">>=",
254 [BPF_NEG >> 4] = "neg",
255 [BPF_MOD >> 4] = "%=",
256 [BPF_XOR >> 4] = "^=",
257 [BPF_MOV >> 4] = "=",
258 [BPF_ARSH >> 4] = "s>>=",
259 [BPF_END >> 4] = "endian",
260};
261
262static const char *const bpf_ldst_string[] = {
263 [BPF_W >> 3] = "u32",
264 [BPF_H >> 3] = "u16",
265 [BPF_B >> 3] = "u8",
266 [BPF_DW >> 3] = "u64",
267};
268
687f0715 269static const char *const bpf_jmp_string[16] = {
cbd35700
AS
270 [BPF_JA >> 4] = "jmp",
271 [BPF_JEQ >> 4] = "==",
272 [BPF_JGT >> 4] = ">",
273 [BPF_JGE >> 4] = ">=",
274 [BPF_JSET >> 4] = "&",
275 [BPF_JNE >> 4] = "!=",
276 [BPF_JSGT >> 4] = "s>",
277 [BPF_JSGE >> 4] = "s>=",
278 [BPF_CALL >> 4] = "call",
279 [BPF_EXIT >> 4] = "exit",
280};
281
282static void print_bpf_insn(struct bpf_insn *insn)
283{
284 u8 class = BPF_CLASS(insn->code);
285
286 if (class == BPF_ALU || class == BPF_ALU64) {
287 if (BPF_SRC(insn->code) == BPF_X)
288 verbose("(%02x) %sr%d %s %sr%d\n",
289 insn->code, class == BPF_ALU ? "(u32) " : "",
290 insn->dst_reg,
291 bpf_alu_string[BPF_OP(insn->code) >> 4],
292 class == BPF_ALU ? "(u32) " : "",
293 insn->src_reg);
294 else
295 verbose("(%02x) %sr%d %s %s%d\n",
296 insn->code, class == BPF_ALU ? "(u32) " : "",
297 insn->dst_reg,
298 bpf_alu_string[BPF_OP(insn->code) >> 4],
299 class == BPF_ALU ? "(u32) " : "",
300 insn->imm);
301 } else if (class == BPF_STX) {
302 if (BPF_MODE(insn->code) == BPF_MEM)
303 verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
304 insn->code,
305 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
306 insn->dst_reg,
307 insn->off, insn->src_reg);
308 else if (BPF_MODE(insn->code) == BPF_XADD)
309 verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
310 insn->code,
311 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
312 insn->dst_reg, insn->off,
313 insn->src_reg);
314 else
315 verbose("BUG_%02x\n", insn->code);
316 } else if (class == BPF_ST) {
317 if (BPF_MODE(insn->code) != BPF_MEM) {
318 verbose("BUG_st_%02x\n", insn->code);
319 return;
320 }
321 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
322 insn->code,
323 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
324 insn->dst_reg,
325 insn->off, insn->imm);
326 } else if (class == BPF_LDX) {
327 if (BPF_MODE(insn->code) != BPF_MEM) {
328 verbose("BUG_ldx_%02x\n", insn->code);
329 return;
330 }
331 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
332 insn->code, insn->dst_reg,
333 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
334 insn->src_reg, insn->off);
335 } else if (class == BPF_LD) {
336 if (BPF_MODE(insn->code) == BPF_ABS) {
337 verbose("(%02x) r0 = *(%s *)skb[%d]\n",
338 insn->code,
339 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
340 insn->imm);
341 } else if (BPF_MODE(insn->code) == BPF_IND) {
342 verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
343 insn->code,
344 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
345 insn->src_reg, insn->imm);
346 } else if (BPF_MODE(insn->code) == BPF_IMM) {
347 verbose("(%02x) r%d = 0x%x\n",
348 insn->code, insn->dst_reg, insn->imm);
349 } else {
350 verbose("BUG_ld_%02x\n", insn->code);
351 return;
352 }
353 } else if (class == BPF_JMP) {
354 u8 opcode = BPF_OP(insn->code);
355
356 if (opcode == BPF_CALL) {
357 verbose("(%02x) call %d\n", insn->code, insn->imm);
358 } else if (insn->code == (BPF_JMP | BPF_JA)) {
359 verbose("(%02x) goto pc%+d\n",
360 insn->code, insn->off);
361 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
362 verbose("(%02x) exit\n", insn->code);
363 } else if (BPF_SRC(insn->code) == BPF_X) {
364 verbose("(%02x) if r%d %s r%d goto pc%+d\n",
365 insn->code, insn->dst_reg,
366 bpf_jmp_string[BPF_OP(insn->code) >> 4],
367 insn->src_reg, insn->off);
368 } else {
369 verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
370 insn->code, insn->dst_reg,
371 bpf_jmp_string[BPF_OP(insn->code) >> 4],
372 insn->imm, insn->off);
373 }
374 } else {
375 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
376 }
377}
378
58e2af8b 379static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
17a52670 380{
58e2af8b 381 struct bpf_verifier_stack_elem *elem;
17a52670
AS
382 int insn_idx;
383
384 if (env->head == NULL)
385 return -1;
386
387 memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
388 insn_idx = env->head->insn_idx;
389 if (prev_insn_idx)
390 *prev_insn_idx = env->head->prev_insn_idx;
391 elem = env->head->next;
392 kfree(env->head);
393 env->head = elem;
394 env->stack_size--;
395 return insn_idx;
396}
397
58e2af8b
JK
398static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
399 int insn_idx, int prev_insn_idx)
17a52670 400{
58e2af8b 401 struct bpf_verifier_stack_elem *elem;
17a52670 402
58e2af8b 403 elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
404 if (!elem)
405 goto err;
406
407 memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
408 elem->insn_idx = insn_idx;
409 elem->prev_insn_idx = prev_insn_idx;
410 elem->next = env->head;
411 env->head = elem;
412 env->stack_size++;
07016151 413 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
17a52670
AS
414 verbose("BPF program is too complex\n");
415 goto err;
416 }
417 return &elem->st;
418err:
419 /* pop all elements and return */
420 while (pop_stack(env, NULL) >= 0);
421 return NULL;
422}
423
424#define CALLER_SAVED_REGS 6
425static const int caller_saved[CALLER_SAVED_REGS] = {
426 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
427};
428
58e2af8b 429static void init_reg_state(struct bpf_reg_state *regs)
17a52670
AS
430{
431 int i;
432
433 for (i = 0; i < MAX_BPF_REG; i++) {
434 regs[i].type = NOT_INIT;
435 regs[i].imm = 0;
48461135
JB
436 regs[i].min_value = BPF_REGISTER_MIN_RANGE;
437 regs[i].max_value = BPF_REGISTER_MAX_RANGE;
17a52670
AS
438 }
439
440 /* frame pointer */
441 regs[BPF_REG_FP].type = FRAME_PTR;
442
443 /* 1st arg to a function */
444 regs[BPF_REG_1].type = PTR_TO_CTX;
445}
446
58e2af8b 447static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
17a52670
AS
448{
449 BUG_ON(regno >= MAX_BPF_REG);
450 regs[regno].type = UNKNOWN_VALUE;
57a09bf0 451 regs[regno].id = 0;
17a52670 452 regs[regno].imm = 0;
17a52670
AS
453}
454
48461135
JB
455static void reset_reg_range_values(struct bpf_reg_state *regs, u32 regno)
456{
457 regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
458 regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
459}
460
17a52670
AS
461enum reg_arg_type {
462 SRC_OP, /* register is used as source operand */
463 DST_OP, /* register is used as destination operand */
464 DST_OP_NO_MARK /* same as above, check only, don't mark */
465};
466
58e2af8b 467static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
17a52670
AS
468 enum reg_arg_type t)
469{
470 if (regno >= MAX_BPF_REG) {
471 verbose("R%d is invalid\n", regno);
472 return -EINVAL;
473 }
474
475 if (t == SRC_OP) {
476 /* check whether register used as source operand can be read */
477 if (regs[regno].type == NOT_INIT) {
478 verbose("R%d !read_ok\n", regno);
479 return -EACCES;
480 }
481 } else {
482 /* check whether register used as dest operand can be written to */
483 if (regno == BPF_REG_FP) {
484 verbose("frame pointer is read only\n");
485 return -EACCES;
486 }
487 if (t == DST_OP)
488 mark_reg_unknown_value(regs, regno);
489 }
490 return 0;
491}
492
493static int bpf_size_to_bytes(int bpf_size)
494{
495 if (bpf_size == BPF_W)
496 return 4;
497 else if (bpf_size == BPF_H)
498 return 2;
499 else if (bpf_size == BPF_B)
500 return 1;
501 else if (bpf_size == BPF_DW)
502 return 8;
503 else
504 return -EINVAL;
505}
506
1be7f75d
AS
507static bool is_spillable_regtype(enum bpf_reg_type type)
508{
509 switch (type) {
510 case PTR_TO_MAP_VALUE:
511 case PTR_TO_MAP_VALUE_OR_NULL:
512 case PTR_TO_STACK:
513 case PTR_TO_CTX:
969bf05e
AS
514 case PTR_TO_PACKET:
515 case PTR_TO_PACKET_END:
1be7f75d
AS
516 case FRAME_PTR:
517 case CONST_PTR_TO_MAP:
518 return true;
519 default:
520 return false;
521 }
522}
523
17a52670
AS
524/* check_stack_read/write functions track spill/fill of registers,
525 * stack boundary and alignment are checked in check_mem_access()
526 */
58e2af8b
JK
527static int check_stack_write(struct bpf_verifier_state *state, int off,
528 int size, int value_regno)
17a52670 529{
17a52670 530 int i;
9c399760
AS
531 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
532 * so it's aligned access and [off, off + size) are within stack limits
533 */
17a52670
AS
534
535 if (value_regno >= 0 &&
1be7f75d 536 is_spillable_regtype(state->regs[value_regno].type)) {
17a52670
AS
537
538 /* register containing pointer is being spilled into stack */
9c399760 539 if (size != BPF_REG_SIZE) {
17a52670
AS
540 verbose("invalid size of register spill\n");
541 return -EACCES;
542 }
543
17a52670 544 /* save register state */
9c399760
AS
545 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
546 state->regs[value_regno];
17a52670 547
9c399760
AS
548 for (i = 0; i < BPF_REG_SIZE; i++)
549 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
550 } else {
17a52670 551 /* regular write of data into stack */
9c399760 552 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
58e2af8b 553 (struct bpf_reg_state) {};
9c399760
AS
554
555 for (i = 0; i < size; i++)
556 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
17a52670
AS
557 }
558 return 0;
559}
560
58e2af8b 561static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
17a52670
AS
562 int value_regno)
563{
9c399760 564 u8 *slot_type;
17a52670 565 int i;
17a52670 566
9c399760 567 slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
17a52670 568
9c399760
AS
569 if (slot_type[0] == STACK_SPILL) {
570 if (size != BPF_REG_SIZE) {
17a52670
AS
571 verbose("invalid size of register spill\n");
572 return -EACCES;
573 }
9c399760
AS
574 for (i = 1; i < BPF_REG_SIZE; i++) {
575 if (slot_type[i] != STACK_SPILL) {
17a52670
AS
576 verbose("corrupted spill memory\n");
577 return -EACCES;
578 }
579 }
580
581 if (value_regno >= 0)
582 /* restore register state from stack */
9c399760
AS
583 state->regs[value_regno] =
584 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
17a52670
AS
585 return 0;
586 } else {
587 for (i = 0; i < size; i++) {
9c399760 588 if (slot_type[i] != STACK_MISC) {
17a52670
AS
589 verbose("invalid read from stack off %d+%d size %d\n",
590 off, i, size);
591 return -EACCES;
592 }
593 }
594 if (value_regno >= 0)
595 /* have read misc data from the stack */
596 mark_reg_unknown_value(state->regs, value_regno);
597 return 0;
598 }
599}
600
601/* check read/write into map element returned by bpf_map_lookup_elem() */
58e2af8b 602static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
17a52670
AS
603 int size)
604{
605 struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
606
607 if (off < 0 || off + size > map->value_size) {
608 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
609 map->value_size, off, size);
610 return -EACCES;
611 }
612 return 0;
613}
614
969bf05e
AS
615#define MAX_PACKET_OFF 0xffff
616
58e2af8b 617static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
36bbef52 618 const struct bpf_call_arg_meta *meta)
4acf6c0b 619{
36bbef52
DB
620 switch (env->prog->type) {
621 case BPF_PROG_TYPE_SCHED_CLS:
622 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 623 case BPF_PROG_TYPE_XDP:
36bbef52
DB
624 if (meta)
625 return meta->pkt_access;
626
627 env->seen_direct_write = true;
4acf6c0b
BB
628 return true;
629 default:
630 return false;
631 }
632}
633
58e2af8b 634static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
969bf05e
AS
635 int size)
636{
58e2af8b
JK
637 struct bpf_reg_state *regs = env->cur_state.regs;
638 struct bpf_reg_state *reg = &regs[regno];
969bf05e 639
d91b28ed 640 off += reg->off;
b399cf64 641 if (off < 0 || size <= 0 || off + size > reg->range) {
d91b28ed
AS
642 verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
643 off, size, regno, reg->id, reg->off, reg->range);
969bf05e
AS
644 return -EACCES;
645 }
646 return 0;
647}
648
17a52670 649/* check access to 'struct bpf_context' fields */
58e2af8b 650static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
19de99f7 651 enum bpf_access_type t, enum bpf_reg_type *reg_type)
17a52670 652{
13a27dfc
JK
653 /* for analyzer ctx accesses are already validated and converted */
654 if (env->analyzer_ops)
655 return 0;
656
17a52670 657 if (env->prog->aux->ops->is_valid_access &&
19de99f7 658 env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
32bbe007
AS
659 /* remember the offset of last byte accessed in ctx */
660 if (env->prog->aux->max_ctx_offset < off + size)
661 env->prog->aux->max_ctx_offset = off + size;
17a52670 662 return 0;
32bbe007 663 }
17a52670
AS
664
665 verbose("invalid bpf_context access off=%d size=%d\n", off, size);
666 return -EACCES;
667}
668
58e2af8b 669static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1be7f75d
AS
670{
671 if (env->allow_ptr_leaks)
672 return false;
673
674 switch (env->cur_state.regs[regno].type) {
675 case UNKNOWN_VALUE:
676 case CONST_IMM:
677 return false;
678 default:
679 return true;
680 }
681}
682
58e2af8b
JK
683static int check_ptr_alignment(struct bpf_verifier_env *env,
684 struct bpf_reg_state *reg, int off, int size)
969bf05e 685{
48461135 686 if (reg->type != PTR_TO_PACKET && reg->type != PTR_TO_MAP_VALUE_ADJ) {
969bf05e 687 if (off % size != 0) {
58e2af8b
JK
688 verbose("misaligned access off %d size %d\n",
689 off, size);
969bf05e
AS
690 return -EACCES;
691 } else {
692 return 0;
693 }
694 }
695
969bf05e
AS
696 if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
697 /* misaligned access to packet is ok on x86,arm,arm64 */
698 return 0;
699
700 if (reg->id && size != 1) {
701 verbose("Unknown packet alignment. Only byte-sized access allowed\n");
702 return -EACCES;
703 }
704
705 /* skb->data is NET_IP_ALIGN-ed */
48461135
JB
706 if (reg->type == PTR_TO_PACKET &&
707 (NET_IP_ALIGN + reg->off + off) % size != 0) {
969bf05e
AS
708 verbose("misaligned packet access off %d+%d+%d size %d\n",
709 NET_IP_ALIGN, reg->off, off, size);
710 return -EACCES;
711 }
712 return 0;
713}
714
17a52670
AS
715/* check whether memory at (regno + off) is accessible for t = (read | write)
716 * if t==write, value_regno is a register which value is stored into memory
717 * if t==read, value_regno is a register which will receive the value from memory
718 * if t==write && value_regno==-1, some unknown value is stored into memory
719 * if t==read && value_regno==-1, don't care what we read from memory
720 */
58e2af8b 721static int check_mem_access(struct bpf_verifier_env *env, u32 regno, int off,
17a52670
AS
722 int bpf_size, enum bpf_access_type t,
723 int value_regno)
724{
58e2af8b
JK
725 struct bpf_verifier_state *state = &env->cur_state;
726 struct bpf_reg_state *reg = &state->regs[regno];
17a52670
AS
727 int size, err = 0;
728
1a0dc1ac
AS
729 if (reg->type == PTR_TO_STACK)
730 off += reg->imm;
24b4d2ab 731
17a52670
AS
732 size = bpf_size_to_bytes(bpf_size);
733 if (size < 0)
734 return size;
735
969bf05e
AS
736 err = check_ptr_alignment(env, reg, off, size);
737 if (err)
738 return err;
17a52670 739
48461135
JB
740 if (reg->type == PTR_TO_MAP_VALUE ||
741 reg->type == PTR_TO_MAP_VALUE_ADJ) {
1be7f75d
AS
742 if (t == BPF_WRITE && value_regno >= 0 &&
743 is_pointer_value(env, value_regno)) {
744 verbose("R%d leaks addr into map\n", value_regno);
745 return -EACCES;
746 }
48461135
JB
747
748 /* If we adjusted the register to this map value at all then we
749 * need to change off and size to min_value and max_value
750 * respectively to make sure our theoretical access will be
751 * safe.
752 */
753 if (reg->type == PTR_TO_MAP_VALUE_ADJ) {
754 if (log_level)
755 print_verifier_state(state);
756 env->varlen_map_value_access = true;
757 /* The minimum value is only important with signed
758 * comparisons where we can't assume the floor of a
759 * value is 0. If we are using signed variables for our
760 * index'es we need to make sure that whatever we use
761 * will have a set floor within our range.
762 */
763 if ((s64)reg->min_value < 0) {
764 verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
765 regno);
766 return -EACCES;
767 }
768 err = check_map_access(env, regno, reg->min_value + off,
769 size);
770 if (err) {
771 verbose("R%d min value is outside of the array range\n",
772 regno);
773 return err;
774 }
775
776 /* If we haven't set a max value then we need to bail
777 * since we can't be sure we won't do bad things.
778 */
779 if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
780 verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
781 regno);
782 return -EACCES;
783 }
784 off += reg->max_value;
785 }
17a52670
AS
786 err = check_map_access(env, regno, off, size);
787 if (!err && t == BPF_READ && value_regno >= 0)
788 mark_reg_unknown_value(state->regs, value_regno);
789
1a0dc1ac 790 } else if (reg->type == PTR_TO_CTX) {
19de99f7
AS
791 enum bpf_reg_type reg_type = UNKNOWN_VALUE;
792
1be7f75d
AS
793 if (t == BPF_WRITE && value_regno >= 0 &&
794 is_pointer_value(env, value_regno)) {
795 verbose("R%d leaks addr into ctx\n", value_regno);
796 return -EACCES;
797 }
19de99f7 798 err = check_ctx_access(env, off, size, t, &reg_type);
969bf05e 799 if (!err && t == BPF_READ && value_regno >= 0) {
17a52670 800 mark_reg_unknown_value(state->regs, value_regno);
1955351d
MS
801 /* note that reg.[id|off|range] == 0 */
802 state->regs[value_regno].type = reg_type;
969bf05e 803 }
17a52670 804
1a0dc1ac 805 } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
17a52670
AS
806 if (off >= 0 || off < -MAX_BPF_STACK) {
807 verbose("invalid stack off=%d size=%d\n", off, size);
808 return -EACCES;
809 }
1be7f75d
AS
810 if (t == BPF_WRITE) {
811 if (!env->allow_ptr_leaks &&
812 state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
813 size != BPF_REG_SIZE) {
814 verbose("attempt to corrupt spilled pointer on stack\n");
815 return -EACCES;
816 }
17a52670 817 err = check_stack_write(state, off, size, value_regno);
1be7f75d 818 } else {
17a52670 819 err = check_stack_read(state, off, size, value_regno);
1be7f75d 820 }
969bf05e 821 } else if (state->regs[regno].type == PTR_TO_PACKET) {
36bbef52 822 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL)) {
969bf05e
AS
823 verbose("cannot write into packet\n");
824 return -EACCES;
825 }
4acf6c0b
BB
826 if (t == BPF_WRITE && value_regno >= 0 &&
827 is_pointer_value(env, value_regno)) {
828 verbose("R%d leaks addr into packet\n", value_regno);
829 return -EACCES;
830 }
969bf05e
AS
831 err = check_packet_access(env, regno, off, size);
832 if (!err && t == BPF_READ && value_regno >= 0)
833 mark_reg_unknown_value(state->regs, value_regno);
17a52670
AS
834 } else {
835 verbose("R%d invalid mem access '%s'\n",
1a0dc1ac 836 regno, reg_type_str[reg->type]);
17a52670
AS
837 return -EACCES;
838 }
969bf05e
AS
839
840 if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
841 state->regs[value_regno].type == UNKNOWN_VALUE) {
842 /* 1 or 2 byte load zero-extends, determine the number of
843 * zero upper bits. Not doing it fo 4 byte load, since
844 * such values cannot be added to ptr_to_packet anyway.
845 */
846 state->regs[value_regno].imm = 64 - size * 8;
847 }
17a52670
AS
848 return err;
849}
850
58e2af8b 851static int check_xadd(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 852{
58e2af8b 853 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
854 int err;
855
856 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
857 insn->imm != 0) {
858 verbose("BPF_XADD uses reserved fields\n");
859 return -EINVAL;
860 }
861
862 /* check src1 operand */
863 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
864 if (err)
865 return err;
866
867 /* check src2 operand */
868 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
869 if (err)
870 return err;
871
872 /* check whether atomic_add can read the memory */
873 err = check_mem_access(env, insn->dst_reg, insn->off,
874 BPF_SIZE(insn->code), BPF_READ, -1);
875 if (err)
876 return err;
877
878 /* check whether atomic_add can write into the same memory */
879 return check_mem_access(env, insn->dst_reg, insn->off,
880 BPF_SIZE(insn->code), BPF_WRITE, -1);
881}
882
883/* when register 'regno' is passed into function that will read 'access_size'
884 * bytes from that pointer, make sure that it's within stack boundary
885 * and all elements of stack are initialized
886 */
58e2af8b 887static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
888 int access_size, bool zero_size_allowed,
889 struct bpf_call_arg_meta *meta)
17a52670 890{
58e2af8b
JK
891 struct bpf_verifier_state *state = &env->cur_state;
892 struct bpf_reg_state *regs = state->regs;
17a52670
AS
893 int off, i;
894
8e2fe1d9
DB
895 if (regs[regno].type != PTR_TO_STACK) {
896 if (zero_size_allowed && access_size == 0 &&
897 regs[regno].type == CONST_IMM &&
898 regs[regno].imm == 0)
899 return 0;
900
901 verbose("R%d type=%s expected=%s\n", regno,
902 reg_type_str[regs[regno].type],
903 reg_type_str[PTR_TO_STACK]);
17a52670 904 return -EACCES;
8e2fe1d9 905 }
17a52670
AS
906
907 off = regs[regno].imm;
908 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
909 access_size <= 0) {
910 verbose("invalid stack type R%d off=%d access_size=%d\n",
911 regno, off, access_size);
912 return -EACCES;
913 }
914
435faee1
DB
915 if (meta && meta->raw_mode) {
916 meta->access_size = access_size;
917 meta->regno = regno;
918 return 0;
919 }
920
17a52670 921 for (i = 0; i < access_size; i++) {
9c399760 922 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
17a52670
AS
923 verbose("invalid indirect read from stack off %d+%d size %d\n",
924 off, i, access_size);
925 return -EACCES;
926 }
927 }
928 return 0;
929}
930
58e2af8b 931static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
33ff9823
DB
932 enum bpf_arg_type arg_type,
933 struct bpf_call_arg_meta *meta)
17a52670 934{
58e2af8b 935 struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
6841de8b 936 enum bpf_reg_type expected_type, type = reg->type;
17a52670
AS
937 int err = 0;
938
80f1d68c 939 if (arg_type == ARG_DONTCARE)
17a52670
AS
940 return 0;
941
6841de8b 942 if (type == NOT_INIT) {
17a52670
AS
943 verbose("R%d !read_ok\n", regno);
944 return -EACCES;
945 }
946
1be7f75d
AS
947 if (arg_type == ARG_ANYTHING) {
948 if (is_pointer_value(env, regno)) {
949 verbose("R%d leaks addr into helper function\n", regno);
950 return -EACCES;
951 }
80f1d68c 952 return 0;
1be7f75d 953 }
80f1d68c 954
36bbef52
DB
955 if (type == PTR_TO_PACKET && !may_access_direct_pkt_data(env, meta)) {
956 verbose("helper access to the packet is not allowed\n");
6841de8b
AS
957 return -EACCES;
958 }
959
8e2fe1d9 960 if (arg_type == ARG_PTR_TO_MAP_KEY ||
17a52670
AS
961 arg_type == ARG_PTR_TO_MAP_VALUE) {
962 expected_type = PTR_TO_STACK;
6841de8b
AS
963 if (type != PTR_TO_PACKET && type != expected_type)
964 goto err_type;
8e2fe1d9
DB
965 } else if (arg_type == ARG_CONST_STACK_SIZE ||
966 arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
17a52670 967 expected_type = CONST_IMM;
6841de8b
AS
968 if (type != expected_type)
969 goto err_type;
17a52670
AS
970 } else if (arg_type == ARG_CONST_MAP_PTR) {
971 expected_type = CONST_PTR_TO_MAP;
6841de8b
AS
972 if (type != expected_type)
973 goto err_type;
608cd71a
AS
974 } else if (arg_type == ARG_PTR_TO_CTX) {
975 expected_type = PTR_TO_CTX;
6841de8b
AS
976 if (type != expected_type)
977 goto err_type;
435faee1
DB
978 } else if (arg_type == ARG_PTR_TO_STACK ||
979 arg_type == ARG_PTR_TO_RAW_STACK) {
8e2fe1d9
DB
980 expected_type = PTR_TO_STACK;
981 /* One exception here. In case function allows for NULL to be
982 * passed in as argument, it's a CONST_IMM type. Final test
983 * happens during stack boundary checking.
984 */
6841de8b
AS
985 if (type == CONST_IMM && reg->imm == 0)
986 /* final test in check_stack_boundary() */;
987 else if (type != PTR_TO_PACKET && type != expected_type)
988 goto err_type;
435faee1 989 meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
17a52670
AS
990 } else {
991 verbose("unsupported arg_type %d\n", arg_type);
992 return -EFAULT;
993 }
994
17a52670
AS
995 if (arg_type == ARG_CONST_MAP_PTR) {
996 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 997 meta->map_ptr = reg->map_ptr;
17a52670
AS
998 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
999 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1000 * check that [key, key + map->key_size) are within
1001 * stack limits and initialized
1002 */
33ff9823 1003 if (!meta->map_ptr) {
17a52670
AS
1004 /* in function declaration map_ptr must come before
1005 * map_key, so that it's verified and known before
1006 * we have to check map_key here. Otherwise it means
1007 * that kernel subsystem misconfigured verifier
1008 */
1009 verbose("invalid map_ptr to access map->key\n");
1010 return -EACCES;
1011 }
6841de8b
AS
1012 if (type == PTR_TO_PACKET)
1013 err = check_packet_access(env, regno, 0,
1014 meta->map_ptr->key_size);
1015 else
1016 err = check_stack_boundary(env, regno,
1017 meta->map_ptr->key_size,
1018 false, NULL);
17a52670
AS
1019 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1020 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1021 * check [value, value + map->value_size) validity
1022 */
33ff9823 1023 if (!meta->map_ptr) {
17a52670
AS
1024 /* kernel subsystem misconfigured verifier */
1025 verbose("invalid map_ptr to access map->value\n");
1026 return -EACCES;
1027 }
6841de8b
AS
1028 if (type == PTR_TO_PACKET)
1029 err = check_packet_access(env, regno, 0,
1030 meta->map_ptr->value_size);
1031 else
1032 err = check_stack_boundary(env, regno,
1033 meta->map_ptr->value_size,
1034 false, NULL);
8e2fe1d9
DB
1035 } else if (arg_type == ARG_CONST_STACK_SIZE ||
1036 arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
1037 bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
17a52670 1038
17a52670
AS
1039 /* bpf_xxx(..., buf, len) call will access 'len' bytes
1040 * from stack pointer 'buf'. Check it
1041 * note: regno == len, regno - 1 == buf
1042 */
1043 if (regno == 0) {
1044 /* kernel subsystem misconfigured verifier */
1045 verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
1046 return -EACCES;
1047 }
6841de8b
AS
1048 if (regs[regno - 1].type == PTR_TO_PACKET)
1049 err = check_packet_access(env, regno - 1, 0, reg->imm);
1050 else
1051 err = check_stack_boundary(env, regno - 1, reg->imm,
1052 zero_size_allowed, meta);
17a52670
AS
1053 }
1054
1055 return err;
6841de8b
AS
1056err_type:
1057 verbose("R%d type=%s expected=%s\n", regno,
1058 reg_type_str[type], reg_type_str[expected_type]);
1059 return -EACCES;
17a52670
AS
1060}
1061
35578d79
KX
1062static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1063{
35578d79
KX
1064 if (!map)
1065 return 0;
1066
6aff67c8
AS
1067 /* We need a two way check, first is from map perspective ... */
1068 switch (map->map_type) {
1069 case BPF_MAP_TYPE_PROG_ARRAY:
1070 if (func_id != BPF_FUNC_tail_call)
1071 goto error;
1072 break;
1073 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1074 if (func_id != BPF_FUNC_perf_event_read &&
1075 func_id != BPF_FUNC_perf_event_output)
1076 goto error;
1077 break;
1078 case BPF_MAP_TYPE_STACK_TRACE:
1079 if (func_id != BPF_FUNC_get_stackid)
1080 goto error;
1081 break;
4ed8ec52 1082 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 1083 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 1084 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
1085 goto error;
1086 break;
6aff67c8
AS
1087 default:
1088 break;
1089 }
1090
1091 /* ... and second from the function itself. */
1092 switch (func_id) {
1093 case BPF_FUNC_tail_call:
1094 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1095 goto error;
1096 break;
1097 case BPF_FUNC_perf_event_read:
1098 case BPF_FUNC_perf_event_output:
1099 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1100 goto error;
1101 break;
1102 case BPF_FUNC_get_stackid:
1103 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1104 goto error;
1105 break;
60d20f91 1106 case BPF_FUNC_current_task_under_cgroup:
747ea55e 1107 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
1108 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1109 goto error;
1110 break;
6aff67c8
AS
1111 default:
1112 break;
35578d79
KX
1113 }
1114
1115 return 0;
6aff67c8
AS
1116error:
1117 verbose("cannot pass map_type %d into func %d\n",
1118 map->map_type, func_id);
1119 return -EINVAL;
35578d79
KX
1120}
1121
435faee1
DB
1122static int check_raw_mode(const struct bpf_func_proto *fn)
1123{
1124 int count = 0;
1125
1126 if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
1127 count++;
1128 if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
1129 count++;
1130 if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
1131 count++;
1132 if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
1133 count++;
1134 if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
1135 count++;
1136
1137 return count > 1 ? -EINVAL : 0;
1138}
1139
58e2af8b 1140static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
969bf05e 1141{
58e2af8b
JK
1142 struct bpf_verifier_state *state = &env->cur_state;
1143 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
1144 int i;
1145
1146 for (i = 0; i < MAX_BPF_REG; i++)
1147 if (regs[i].type == PTR_TO_PACKET ||
1148 regs[i].type == PTR_TO_PACKET_END)
1149 mark_reg_unknown_value(regs, i);
1150
1151 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1152 if (state->stack_slot_type[i] != STACK_SPILL)
1153 continue;
1154 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1155 if (reg->type != PTR_TO_PACKET &&
1156 reg->type != PTR_TO_PACKET_END)
1157 continue;
1158 reg->type = UNKNOWN_VALUE;
1159 reg->imm = 0;
1160 }
1161}
1162
58e2af8b 1163static int check_call(struct bpf_verifier_env *env, int func_id)
17a52670 1164{
58e2af8b 1165 struct bpf_verifier_state *state = &env->cur_state;
17a52670 1166 const struct bpf_func_proto *fn = NULL;
58e2af8b
JK
1167 struct bpf_reg_state *regs = state->regs;
1168 struct bpf_reg_state *reg;
33ff9823 1169 struct bpf_call_arg_meta meta;
969bf05e 1170 bool changes_data;
17a52670
AS
1171 int i, err;
1172
1173 /* find function prototype */
1174 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1175 verbose("invalid func %d\n", func_id);
1176 return -EINVAL;
1177 }
1178
1179 if (env->prog->aux->ops->get_func_proto)
1180 fn = env->prog->aux->ops->get_func_proto(func_id);
1181
1182 if (!fn) {
1183 verbose("unknown func %d\n", func_id);
1184 return -EINVAL;
1185 }
1186
1187 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 1188 if (!env->prog->gpl_compatible && fn->gpl_only) {
17a52670
AS
1189 verbose("cannot call GPL only function from proprietary program\n");
1190 return -EINVAL;
1191 }
1192
969bf05e
AS
1193 changes_data = bpf_helper_changes_skb_data(fn->func);
1194
33ff9823 1195 memset(&meta, 0, sizeof(meta));
36bbef52 1196 meta.pkt_access = fn->pkt_access;
33ff9823 1197
435faee1
DB
1198 /* We only support one arg being in raw mode at the moment, which
1199 * is sufficient for the helper functions we have right now.
1200 */
1201 err = check_raw_mode(fn);
1202 if (err) {
1203 verbose("kernel subsystem misconfigured func %d\n", func_id);
1204 return err;
1205 }
1206
17a52670 1207 /* check args */
33ff9823 1208 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
17a52670
AS
1209 if (err)
1210 return err;
33ff9823 1211 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
17a52670
AS
1212 if (err)
1213 return err;
33ff9823 1214 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
17a52670
AS
1215 if (err)
1216 return err;
33ff9823 1217 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
17a52670
AS
1218 if (err)
1219 return err;
33ff9823 1220 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
17a52670
AS
1221 if (err)
1222 return err;
1223
435faee1
DB
1224 /* Mark slots with STACK_MISC in case of raw mode, stack offset
1225 * is inferred from register state.
1226 */
1227 for (i = 0; i < meta.access_size; i++) {
1228 err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1229 if (err)
1230 return err;
1231 }
1232
17a52670
AS
1233 /* reset caller saved regs */
1234 for (i = 0; i < CALLER_SAVED_REGS; i++) {
1235 reg = regs + caller_saved[i];
1236 reg->type = NOT_INIT;
1237 reg->imm = 0;
1238 }
1239
1240 /* update return register */
1241 if (fn->ret_type == RET_INTEGER) {
1242 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1243 } else if (fn->ret_type == RET_VOID) {
1244 regs[BPF_REG_0].type = NOT_INIT;
1245 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1246 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
48461135 1247 regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0;
17a52670
AS
1248 /* remember map_ptr, so that check_map_access()
1249 * can check 'value_size' boundary of memory access
1250 * to map element returned from bpf_map_lookup_elem()
1251 */
33ff9823 1252 if (meta.map_ptr == NULL) {
17a52670
AS
1253 verbose("kernel subsystem misconfigured verifier\n");
1254 return -EINVAL;
1255 }
33ff9823 1256 regs[BPF_REG_0].map_ptr = meta.map_ptr;
57a09bf0 1257 regs[BPF_REG_0].id = ++env->id_gen;
17a52670
AS
1258 } else {
1259 verbose("unknown return type %d of func %d\n",
1260 fn->ret_type, func_id);
1261 return -EINVAL;
1262 }
04fd61ab 1263
33ff9823 1264 err = check_map_func_compatibility(meta.map_ptr, func_id);
35578d79
KX
1265 if (err)
1266 return err;
04fd61ab 1267
969bf05e
AS
1268 if (changes_data)
1269 clear_all_pkt_pointers(env);
1270 return 0;
1271}
1272
58e2af8b
JK
1273static int check_packet_ptr_add(struct bpf_verifier_env *env,
1274 struct bpf_insn *insn)
969bf05e 1275{
58e2af8b
JK
1276 struct bpf_reg_state *regs = env->cur_state.regs;
1277 struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1278 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1279 struct bpf_reg_state tmp_reg;
969bf05e
AS
1280 s32 imm;
1281
1282 if (BPF_SRC(insn->code) == BPF_K) {
1283 /* pkt_ptr += imm */
1284 imm = insn->imm;
1285
1286add_imm:
1287 if (imm <= 0) {
1288 verbose("addition of negative constant to packet pointer is not allowed\n");
1289 return -EACCES;
1290 }
1291 if (imm >= MAX_PACKET_OFF ||
1292 imm + dst_reg->off >= MAX_PACKET_OFF) {
1293 verbose("constant %d is too large to add to packet pointer\n",
1294 imm);
1295 return -EACCES;
1296 }
1297 /* a constant was added to pkt_ptr.
1298 * Remember it while keeping the same 'id'
1299 */
1300 dst_reg->off += imm;
1301 } else {
1b9b69ec
AS
1302 if (src_reg->type == PTR_TO_PACKET) {
1303 /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
1304 tmp_reg = *dst_reg; /* save r7 state */
1305 *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
1306 src_reg = &tmp_reg; /* pretend it's src_reg state */
1307 /* if the checks below reject it, the copy won't matter,
1308 * since we're rejecting the whole program. If all ok,
1309 * then imm22 state will be added to r7
1310 * and r7 will be pkt(id=0,off=22,r=62) while
1311 * r6 will stay as pkt(id=0,off=0,r=62)
1312 */
1313 }
1314
969bf05e
AS
1315 if (src_reg->type == CONST_IMM) {
1316 /* pkt_ptr += reg where reg is known constant */
1317 imm = src_reg->imm;
1318 goto add_imm;
1319 }
1320 /* disallow pkt_ptr += reg
1321 * if reg is not uknown_value with guaranteed zero upper bits
1322 * otherwise pkt_ptr may overflow and addition will become
1323 * subtraction which is not allowed
1324 */
1325 if (src_reg->type != UNKNOWN_VALUE) {
1326 verbose("cannot add '%s' to ptr_to_packet\n",
1327 reg_type_str[src_reg->type]);
1328 return -EACCES;
1329 }
1330 if (src_reg->imm < 48) {
1331 verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1332 src_reg->imm);
1333 return -EACCES;
1334 }
1335 /* dst_reg stays as pkt_ptr type and since some positive
1336 * integer value was added to the pointer, increment its 'id'
1337 */
1f415a74 1338 dst_reg->id = ++env->id_gen;
969bf05e
AS
1339
1340 /* something was added to pkt_ptr, set range and off to zero */
1341 dst_reg->off = 0;
1342 dst_reg->range = 0;
1343 }
1344 return 0;
1345}
1346
58e2af8b 1347static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
969bf05e 1348{
58e2af8b
JK
1349 struct bpf_reg_state *regs = env->cur_state.regs;
1350 struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
969bf05e
AS
1351 u8 opcode = BPF_OP(insn->code);
1352 s64 imm_log2;
1353
1354 /* for type == UNKNOWN_VALUE:
1355 * imm > 0 -> number of zero upper bits
1356 * imm == 0 -> don't track which is the same as all bits can be non-zero
1357 */
1358
1359 if (BPF_SRC(insn->code) == BPF_X) {
58e2af8b 1360 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
969bf05e
AS
1361
1362 if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1363 dst_reg->imm && opcode == BPF_ADD) {
1364 /* dreg += sreg
1365 * where both have zero upper bits. Adding them
1366 * can only result making one more bit non-zero
1367 * in the larger value.
1368 * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1369 * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1370 */
1371 dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1372 dst_reg->imm--;
1373 return 0;
1374 }
1375 if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1376 dst_reg->imm && opcode == BPF_ADD) {
1377 /* dreg += sreg
1378 * where dreg has zero upper bits and sreg is const.
1379 * Adding them can only result making one more bit
1380 * non-zero in the larger value.
1381 */
1382 imm_log2 = __ilog2_u64((long long)src_reg->imm);
1383 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1384 dst_reg->imm--;
1385 return 0;
1386 }
1387 /* all other cases non supported yet, just mark dst_reg */
1388 dst_reg->imm = 0;
1389 return 0;
1390 }
1391
1392 /* sign extend 32-bit imm into 64-bit to make sure that
1393 * negative values occupy bit 63. Note ilog2() would have
1394 * been incorrect, since sizeof(insn->imm) == 4
1395 */
1396 imm_log2 = __ilog2_u64((long long)insn->imm);
1397
1398 if (dst_reg->imm && opcode == BPF_LSH) {
1399 /* reg <<= imm
1400 * if reg was a result of 2 byte load, then its imm == 48
1401 * which means that upper 48 bits are zero and shifting this reg
1402 * left by 4 would mean that upper 44 bits are still zero
1403 */
1404 dst_reg->imm -= insn->imm;
1405 } else if (dst_reg->imm && opcode == BPF_MUL) {
1406 /* reg *= imm
1407 * if multiplying by 14 subtract 4
1408 * This is conservative calculation of upper zero bits.
1409 * It's not trying to special case insn->imm == 1 or 0 cases
1410 */
1411 dst_reg->imm -= imm_log2 + 1;
1412 } else if (opcode == BPF_AND) {
1413 /* reg &= imm */
1414 dst_reg->imm = 63 - imm_log2;
1415 } else if (dst_reg->imm && opcode == BPF_ADD) {
1416 /* reg += imm */
1417 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1418 dst_reg->imm--;
1419 } else if (opcode == BPF_RSH) {
1420 /* reg >>= imm
1421 * which means that after right shift, upper bits will be zero
1422 * note that verifier already checked that
1423 * 0 <= imm < 64 for shift insn
1424 */
1425 dst_reg->imm += insn->imm;
1426 if (unlikely(dst_reg->imm > 64))
1427 /* some dumb code did:
1428 * r2 = *(u32 *)mem;
1429 * r2 >>= 32;
1430 * and all bits are zero now */
1431 dst_reg->imm = 64;
1432 } else {
1433 /* all other alu ops, means that we don't know what will
1434 * happen to the value, mark it with unknown number of zero bits
1435 */
1436 dst_reg->imm = 0;
1437 }
1438
1439 if (dst_reg->imm < 0) {
1440 /* all 64 bits of the register can contain non-zero bits
1441 * and such value cannot be added to ptr_to_packet, since it
1442 * may overflow, mark it as unknown to avoid further eval
1443 */
1444 dst_reg->imm = 0;
1445 }
1446 return 0;
1447}
1448
58e2af8b
JK
1449static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
1450 struct bpf_insn *insn)
969bf05e 1451{
58e2af8b
JK
1452 struct bpf_reg_state *regs = env->cur_state.regs;
1453 struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1454 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
969bf05e
AS
1455 u8 opcode = BPF_OP(insn->code);
1456
1457 /* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
1458 * Don't care about overflow or negative values, just add them
1459 */
1460 if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
1461 dst_reg->imm += insn->imm;
1462 else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1463 src_reg->type == CONST_IMM)
1464 dst_reg->imm += src_reg->imm;
1465 else
1466 mark_reg_unknown_value(regs, insn->dst_reg);
17a52670
AS
1467 return 0;
1468}
1469
48461135
JB
1470static void check_reg_overflow(struct bpf_reg_state *reg)
1471{
1472 if (reg->max_value > BPF_REGISTER_MAX_RANGE)
1473 reg->max_value = BPF_REGISTER_MAX_RANGE;
1474 if ((s64)reg->min_value < BPF_REGISTER_MIN_RANGE)
1475 reg->min_value = BPF_REGISTER_MIN_RANGE;
1476}
1477
1478static void adjust_reg_min_max_vals(struct bpf_verifier_env *env,
1479 struct bpf_insn *insn)
1480{
1481 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1482 u64 min_val = BPF_REGISTER_MIN_RANGE, max_val = BPF_REGISTER_MAX_RANGE;
1483 bool min_set = false, max_set = false;
1484 u8 opcode = BPF_OP(insn->code);
1485
1486 dst_reg = &regs[insn->dst_reg];
1487 if (BPF_SRC(insn->code) == BPF_X) {
1488 check_reg_overflow(&regs[insn->src_reg]);
1489 min_val = regs[insn->src_reg].min_value;
1490 max_val = regs[insn->src_reg].max_value;
1491
1492 /* If the source register is a random pointer then the
1493 * min_value/max_value values represent the range of the known
1494 * accesses into that value, not the actual min/max value of the
1495 * register itself. In this case we have to reset the reg range
1496 * values so we know it is not safe to look at.
1497 */
1498 if (regs[insn->src_reg].type != CONST_IMM &&
1499 regs[insn->src_reg].type != UNKNOWN_VALUE) {
1500 min_val = BPF_REGISTER_MIN_RANGE;
1501 max_val = BPF_REGISTER_MAX_RANGE;
1502 }
1503 } else if (insn->imm < BPF_REGISTER_MAX_RANGE &&
1504 (s64)insn->imm > BPF_REGISTER_MIN_RANGE) {
1505 min_val = max_val = insn->imm;
1506 min_set = max_set = true;
1507 }
1508
1509 /* We don't know anything about what was done to this register, mark it
1510 * as unknown.
1511 */
1512 if (min_val == BPF_REGISTER_MIN_RANGE &&
1513 max_val == BPF_REGISTER_MAX_RANGE) {
1514 reset_reg_range_values(regs, insn->dst_reg);
1515 return;
1516 }
1517
1518 switch (opcode) {
1519 case BPF_ADD:
1520 dst_reg->min_value += min_val;
1521 dst_reg->max_value += max_val;
1522 break;
1523 case BPF_SUB:
1524 dst_reg->min_value -= min_val;
1525 dst_reg->max_value -= max_val;
1526 break;
1527 case BPF_MUL:
1528 dst_reg->min_value *= min_val;
1529 dst_reg->max_value *= max_val;
1530 break;
1531 case BPF_AND:
1532 /* & is special since it could end up with 0 bits set. */
1533 dst_reg->min_value &= min_val;
1534 dst_reg->max_value = max_val;
1535 break;
1536 case BPF_LSH:
1537 /* Gotta have special overflow logic here, if we're shifting
1538 * more than MAX_RANGE then just assume we have an invalid
1539 * range.
1540 */
1541 if (min_val > ilog2(BPF_REGISTER_MAX_RANGE))
1542 dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1543 else
1544 dst_reg->min_value <<= min_val;
1545
1546 if (max_val > ilog2(BPF_REGISTER_MAX_RANGE))
1547 dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
1548 else
1549 dst_reg->max_value <<= max_val;
1550 break;
1551 case BPF_RSH:
1552 dst_reg->min_value >>= min_val;
1553 dst_reg->max_value >>= max_val;
1554 break;
1555 case BPF_MOD:
1556 /* % is special since it is an unsigned modulus, so the floor
1557 * will always be 0.
1558 */
1559 dst_reg->min_value = 0;
1560 dst_reg->max_value = max_val - 1;
1561 break;
1562 default:
1563 reset_reg_range_values(regs, insn->dst_reg);
1564 break;
1565 }
1566
1567 check_reg_overflow(dst_reg);
1568}
1569
17a52670 1570/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 1571static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 1572{
58e2af8b 1573 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
17a52670
AS
1574 u8 opcode = BPF_OP(insn->code);
1575 int err;
1576
1577 if (opcode == BPF_END || opcode == BPF_NEG) {
1578 if (opcode == BPF_NEG) {
1579 if (BPF_SRC(insn->code) != 0 ||
1580 insn->src_reg != BPF_REG_0 ||
1581 insn->off != 0 || insn->imm != 0) {
1582 verbose("BPF_NEG uses reserved fields\n");
1583 return -EINVAL;
1584 }
1585 } else {
1586 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1587 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1588 verbose("BPF_END uses reserved fields\n");
1589 return -EINVAL;
1590 }
1591 }
1592
1593 /* check src operand */
1594 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1595 if (err)
1596 return err;
1597
1be7f75d
AS
1598 if (is_pointer_value(env, insn->dst_reg)) {
1599 verbose("R%d pointer arithmetic prohibited\n",
1600 insn->dst_reg);
1601 return -EACCES;
1602 }
1603
17a52670
AS
1604 /* check dest operand */
1605 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1606 if (err)
1607 return err;
1608
1609 } else if (opcode == BPF_MOV) {
1610
1611 if (BPF_SRC(insn->code) == BPF_X) {
1612 if (insn->imm != 0 || insn->off != 0) {
1613 verbose("BPF_MOV uses reserved fields\n");
1614 return -EINVAL;
1615 }
1616
1617 /* check src operand */
1618 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1619 if (err)
1620 return err;
1621 } else {
1622 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1623 verbose("BPF_MOV uses reserved fields\n");
1624 return -EINVAL;
1625 }
1626 }
1627
1628 /* check dest operand */
1629 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1630 if (err)
1631 return err;
1632
48461135
JB
1633 /* we are setting our register to something new, we need to
1634 * reset its range values.
1635 */
1636 reset_reg_range_values(regs, insn->dst_reg);
1637
17a52670
AS
1638 if (BPF_SRC(insn->code) == BPF_X) {
1639 if (BPF_CLASS(insn->code) == BPF_ALU64) {
1640 /* case: R1 = R2
1641 * copy register state to dest reg
1642 */
1643 regs[insn->dst_reg] = regs[insn->src_reg];
1644 } else {
1be7f75d
AS
1645 if (is_pointer_value(env, insn->src_reg)) {
1646 verbose("R%d partial copy of pointer\n",
1647 insn->src_reg);
1648 return -EACCES;
1649 }
57a09bf0 1650 mark_reg_unknown_value(regs, insn->dst_reg);
17a52670
AS
1651 }
1652 } else {
1653 /* case: R = imm
1654 * remember the value we stored into this reg
1655 */
1656 regs[insn->dst_reg].type = CONST_IMM;
1657 regs[insn->dst_reg].imm = insn->imm;
48461135
JB
1658 regs[insn->dst_reg].max_value = insn->imm;
1659 regs[insn->dst_reg].min_value = insn->imm;
17a52670
AS
1660 }
1661
1662 } else if (opcode > BPF_END) {
1663 verbose("invalid BPF_ALU opcode %x\n", opcode);
1664 return -EINVAL;
1665
1666 } else { /* all other ALU ops: and, sub, xor, add, ... */
1667
17a52670
AS
1668 if (BPF_SRC(insn->code) == BPF_X) {
1669 if (insn->imm != 0 || insn->off != 0) {
1670 verbose("BPF_ALU uses reserved fields\n");
1671 return -EINVAL;
1672 }
1673 /* check src1 operand */
1674 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1675 if (err)
1676 return err;
1677 } else {
1678 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1679 verbose("BPF_ALU uses reserved fields\n");
1680 return -EINVAL;
1681 }
1682 }
1683
1684 /* check src2 operand */
1685 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1686 if (err)
1687 return err;
1688
1689 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1690 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1691 verbose("div by zero\n");
1692 return -EINVAL;
1693 }
1694
229394e8
RV
1695 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1696 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1697 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1698
1699 if (insn->imm < 0 || insn->imm >= size) {
1700 verbose("invalid shift %d\n", insn->imm);
1701 return -EINVAL;
1702 }
1703 }
1704
1a0dc1ac
AS
1705 /* check dest operand */
1706 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1707 if (err)
1708 return err;
1709
1710 dst_reg = &regs[insn->dst_reg];
1711
48461135
JB
1712 /* first we want to adjust our ranges. */
1713 adjust_reg_min_max_vals(env, insn);
1714
17a52670
AS
1715 /* pattern match 'bpf_add Rx, imm' instruction */
1716 if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1a0dc1ac
AS
1717 dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
1718 dst_reg->type = PTR_TO_STACK;
1719 dst_reg->imm = insn->imm;
1720 return 0;
969bf05e
AS
1721 } else if (opcode == BPF_ADD &&
1722 BPF_CLASS(insn->code) == BPF_ALU64 &&
1b9b69ec
AS
1723 (dst_reg->type == PTR_TO_PACKET ||
1724 (BPF_SRC(insn->code) == BPF_X &&
1725 regs[insn->src_reg].type == PTR_TO_PACKET))) {
969bf05e
AS
1726 /* ptr_to_packet += K|X */
1727 return check_packet_ptr_add(env, insn);
1728 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1729 dst_reg->type == UNKNOWN_VALUE &&
1730 env->allow_ptr_leaks) {
1731 /* unknown += K|X */
1732 return evaluate_reg_alu(env, insn);
1733 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1734 dst_reg->type == CONST_IMM &&
1735 env->allow_ptr_leaks) {
1736 /* reg_imm += K|X */
1737 return evaluate_reg_imm_alu(env, insn);
1be7f75d
AS
1738 } else if (is_pointer_value(env, insn->dst_reg)) {
1739 verbose("R%d pointer arithmetic prohibited\n",
1740 insn->dst_reg);
1741 return -EACCES;
1742 } else if (BPF_SRC(insn->code) == BPF_X &&
1743 is_pointer_value(env, insn->src_reg)) {
1744 verbose("R%d pointer arithmetic prohibited\n",
1745 insn->src_reg);
1746 return -EACCES;
1747 }
17a52670 1748
48461135
JB
1749 /* If we did pointer math on a map value then just set it to our
1750 * PTR_TO_MAP_VALUE_ADJ type so we can deal with any stores or
1751 * loads to this register appropriately, otherwise just mark the
1752 * register as unknown.
1753 */
1754 if (env->allow_ptr_leaks &&
1755 (dst_reg->type == PTR_TO_MAP_VALUE ||
1756 dst_reg->type == PTR_TO_MAP_VALUE_ADJ))
1757 dst_reg->type = PTR_TO_MAP_VALUE_ADJ;
1758 else
1759 mark_reg_unknown_value(regs, insn->dst_reg);
17a52670
AS
1760 }
1761
1762 return 0;
1763}
1764
58e2af8b
JK
1765static void find_good_pkt_pointers(struct bpf_verifier_state *state,
1766 struct bpf_reg_state *dst_reg)
969bf05e 1767{
58e2af8b 1768 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e 1769 int i;
2d2be8ca
DB
1770
1771 /* LLVM can generate two kind of checks:
1772 *
1773 * Type 1:
1774 *
1775 * r2 = r3;
1776 * r2 += 8;
1777 * if (r2 > pkt_end) goto <handle exception>
1778 * <access okay>
1779 *
1780 * Where:
1781 * r2 == dst_reg, pkt_end == src_reg
1782 * r2=pkt(id=n,off=8,r=0)
1783 * r3=pkt(id=n,off=0,r=0)
1784 *
1785 * Type 2:
1786 *
1787 * r2 = r3;
1788 * r2 += 8;
1789 * if (pkt_end >= r2) goto <access okay>
1790 * <handle exception>
1791 *
1792 * Where:
1793 * pkt_end == dst_reg, r2 == src_reg
1794 * r2=pkt(id=n,off=8,r=0)
1795 * r3=pkt(id=n,off=0,r=0)
1796 *
1797 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
1798 * so that range of bytes [r3, r3 + 8) is safe to access.
969bf05e 1799 */
2d2be8ca 1800
969bf05e
AS
1801 for (i = 0; i < MAX_BPF_REG; i++)
1802 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
1803 regs[i].range = dst_reg->off;
1804
1805 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1806 if (state->stack_slot_type[i] != STACK_SPILL)
1807 continue;
1808 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1809 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
1810 reg->range = dst_reg->off;
1811 }
1812}
1813
48461135
JB
1814/* Adjusts the register min/max values in the case that the dst_reg is the
1815 * variable register that we are working on, and src_reg is a constant or we're
1816 * simply doing a BPF_K check.
1817 */
1818static void reg_set_min_max(struct bpf_reg_state *true_reg,
1819 struct bpf_reg_state *false_reg, u64 val,
1820 u8 opcode)
1821{
1822 switch (opcode) {
1823 case BPF_JEQ:
1824 /* If this is false then we know nothing Jon Snow, but if it is
1825 * true then we know for sure.
1826 */
1827 true_reg->max_value = true_reg->min_value = val;
1828 break;
1829 case BPF_JNE:
1830 /* If this is true we know nothing Jon Snow, but if it is false
1831 * we know the value for sure;
1832 */
1833 false_reg->max_value = false_reg->min_value = val;
1834 break;
1835 case BPF_JGT:
1836 /* Unsigned comparison, the minimum value is 0. */
1837 false_reg->min_value = 0;
1838 case BPF_JSGT:
1839 /* If this is false then we know the maximum val is val,
1840 * otherwise we know the min val is val+1.
1841 */
1842 false_reg->max_value = val;
1843 true_reg->min_value = val + 1;
1844 break;
1845 case BPF_JGE:
1846 /* Unsigned comparison, the minimum value is 0. */
1847 false_reg->min_value = 0;
1848 case BPF_JSGE:
1849 /* If this is false then we know the maximum value is val - 1,
1850 * otherwise we know the mimimum value is val.
1851 */
1852 false_reg->max_value = val - 1;
1853 true_reg->min_value = val;
1854 break;
1855 default:
1856 break;
1857 }
1858
1859 check_reg_overflow(false_reg);
1860 check_reg_overflow(true_reg);
1861}
1862
1863/* Same as above, but for the case that dst_reg is a CONST_IMM reg and src_reg
1864 * is the variable reg.
1865 */
1866static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
1867 struct bpf_reg_state *false_reg, u64 val,
1868 u8 opcode)
1869{
1870 switch (opcode) {
1871 case BPF_JEQ:
1872 /* If this is false then we know nothing Jon Snow, but if it is
1873 * true then we know for sure.
1874 */
1875 true_reg->max_value = true_reg->min_value = val;
1876 break;
1877 case BPF_JNE:
1878 /* If this is true we know nothing Jon Snow, but if it is false
1879 * we know the value for sure;
1880 */
1881 false_reg->max_value = false_reg->min_value = val;
1882 break;
1883 case BPF_JGT:
1884 /* Unsigned comparison, the minimum value is 0. */
1885 true_reg->min_value = 0;
1886 case BPF_JSGT:
1887 /*
1888 * If this is false, then the val is <= the register, if it is
1889 * true the register <= to the val.
1890 */
1891 false_reg->min_value = val;
1892 true_reg->max_value = val - 1;
1893 break;
1894 case BPF_JGE:
1895 /* Unsigned comparison, the minimum value is 0. */
1896 true_reg->min_value = 0;
1897 case BPF_JSGE:
1898 /* If this is false then constant < register, if it is true then
1899 * the register < constant.
1900 */
1901 false_reg->min_value = val + 1;
1902 true_reg->max_value = val;
1903 break;
1904 default:
1905 break;
1906 }
1907
1908 check_reg_overflow(false_reg);
1909 check_reg_overflow(true_reg);
1910}
1911
57a09bf0
TG
1912static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
1913 enum bpf_reg_type type)
1914{
1915 struct bpf_reg_state *reg = &regs[regno];
1916
1917 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
1918 reg->type = type;
1919 if (type == UNKNOWN_VALUE)
1920 mark_reg_unknown_value(regs, regno);
1921 }
1922}
1923
1924/* The logic is similar to find_good_pkt_pointers(), both could eventually
1925 * be folded together at some point.
1926 */
1927static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
1928 enum bpf_reg_type type)
1929{
1930 struct bpf_reg_state *regs = state->regs;
1931 int i;
1932
1933 for (i = 0; i < MAX_BPF_REG; i++)
1934 mark_map_reg(regs, i, regs[regno].id, type);
1935
1936 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1937 if (state->stack_slot_type[i] != STACK_SPILL)
1938 continue;
1939 mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE,
1940 regs[regno].id, type);
1941 }
1942}
1943
58e2af8b 1944static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
1945 struct bpf_insn *insn, int *insn_idx)
1946{
58e2af8b
JK
1947 struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
1948 struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
17a52670
AS
1949 u8 opcode = BPF_OP(insn->code);
1950 int err;
1951
1952 if (opcode > BPF_EXIT) {
1953 verbose("invalid BPF_JMP opcode %x\n", opcode);
1954 return -EINVAL;
1955 }
1956
1957 if (BPF_SRC(insn->code) == BPF_X) {
1958 if (insn->imm != 0) {
1959 verbose("BPF_JMP uses reserved fields\n");
1960 return -EINVAL;
1961 }
1962
1963 /* check src1 operand */
1964 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1965 if (err)
1966 return err;
1be7f75d
AS
1967
1968 if (is_pointer_value(env, insn->src_reg)) {
1969 verbose("R%d pointer comparison prohibited\n",
1970 insn->src_reg);
1971 return -EACCES;
1972 }
17a52670
AS
1973 } else {
1974 if (insn->src_reg != BPF_REG_0) {
1975 verbose("BPF_JMP uses reserved fields\n");
1976 return -EINVAL;
1977 }
1978 }
1979
1980 /* check src2 operand */
1981 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1982 if (err)
1983 return err;
1984
1a0dc1ac
AS
1985 dst_reg = &regs[insn->dst_reg];
1986
17a52670
AS
1987 /* detect if R == 0 where R was initialized to zero earlier */
1988 if (BPF_SRC(insn->code) == BPF_K &&
1989 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1a0dc1ac 1990 dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
17a52670
AS
1991 if (opcode == BPF_JEQ) {
1992 /* if (imm == imm) goto pc+off;
1993 * only follow the goto, ignore fall-through
1994 */
1995 *insn_idx += insn->off;
1996 return 0;
1997 } else {
1998 /* if (imm != imm) goto pc+off;
1999 * only follow fall-through branch, since
2000 * that's where the program will go
2001 */
2002 return 0;
2003 }
2004 }
2005
2006 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
2007 if (!other_branch)
2008 return -EFAULT;
2009
48461135
JB
2010 /* detect if we are comparing against a constant value so we can adjust
2011 * our min/max values for our dst register.
2012 */
2013 if (BPF_SRC(insn->code) == BPF_X) {
2014 if (regs[insn->src_reg].type == CONST_IMM)
2015 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2016 dst_reg, regs[insn->src_reg].imm,
2017 opcode);
2018 else if (dst_reg->type == CONST_IMM)
2019 reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
2020 &regs[insn->src_reg], dst_reg->imm,
2021 opcode);
2022 } else {
2023 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2024 dst_reg, insn->imm, opcode);
2025 }
2026
58e2af8b 2027 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
17a52670 2028 if (BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac
AS
2029 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
2030 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
57a09bf0
TG
2031 /* Mark all identical map registers in each branch as either
2032 * safe or unknown depending R == 0 or R != 0 conditional.
2033 */
2034 mark_map_regs(this_branch, insn->dst_reg,
2035 opcode == BPF_JEQ ? PTR_TO_MAP_VALUE : UNKNOWN_VALUE);
2036 mark_map_regs(other_branch, insn->dst_reg,
2037 opcode == BPF_JEQ ? UNKNOWN_VALUE : PTR_TO_MAP_VALUE);
969bf05e
AS
2038 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
2039 dst_reg->type == PTR_TO_PACKET &&
2040 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
2d2be8ca
DB
2041 find_good_pkt_pointers(this_branch, dst_reg);
2042 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
2043 dst_reg->type == PTR_TO_PACKET_END &&
2044 regs[insn->src_reg].type == PTR_TO_PACKET) {
2045 find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
1be7f75d
AS
2046 } else if (is_pointer_value(env, insn->dst_reg)) {
2047 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
2048 return -EACCES;
17a52670
AS
2049 }
2050 if (log_level)
2d2be8ca 2051 print_verifier_state(this_branch);
17a52670
AS
2052 return 0;
2053}
2054
0246e64d
AS
2055/* return the map pointer stored inside BPF_LD_IMM64 instruction */
2056static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
2057{
2058 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
2059
2060 return (struct bpf_map *) (unsigned long) imm64;
2061}
2062
17a52670 2063/* verify BPF_LD_IMM64 instruction */
58e2af8b 2064static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 2065{
58e2af8b 2066 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
2067 int err;
2068
2069 if (BPF_SIZE(insn->code) != BPF_DW) {
2070 verbose("invalid BPF_LD_IMM insn\n");
2071 return -EINVAL;
2072 }
2073 if (insn->off != 0) {
2074 verbose("BPF_LD_IMM64 uses reserved fields\n");
2075 return -EINVAL;
2076 }
2077
2078 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
2079 if (err)
2080 return err;
2081
6b173873
JK
2082 if (insn->src_reg == 0) {
2083 /* generic move 64-bit immediate into a register,
2084 * only analyzer needs to collect the ld_imm value.
2085 */
2086 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
2087
2088 if (!env->analyzer_ops)
2089 return 0;
2090
2091 regs[insn->dst_reg].type = CONST_IMM;
2092 regs[insn->dst_reg].imm = imm;
17a52670 2093 return 0;
6b173873 2094 }
17a52670
AS
2095
2096 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
2097 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
2098
2099 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
2100 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
2101 return 0;
2102}
2103
96be4325
DB
2104static bool may_access_skb(enum bpf_prog_type type)
2105{
2106 switch (type) {
2107 case BPF_PROG_TYPE_SOCKET_FILTER:
2108 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 2109 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
2110 return true;
2111 default:
2112 return false;
2113 }
2114}
2115
ddd872bc
AS
2116/* verify safety of LD_ABS|LD_IND instructions:
2117 * - they can only appear in the programs where ctx == skb
2118 * - since they are wrappers of function calls, they scratch R1-R5 registers,
2119 * preserve R6-R9, and store return value into R0
2120 *
2121 * Implicit input:
2122 * ctx == skb == R6 == CTX
2123 *
2124 * Explicit input:
2125 * SRC == any register
2126 * IMM == 32-bit immediate
2127 *
2128 * Output:
2129 * R0 - 8/16/32-bit skb data converted to cpu endianness
2130 */
58e2af8b 2131static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 2132{
58e2af8b 2133 struct bpf_reg_state *regs = env->cur_state.regs;
ddd872bc 2134 u8 mode = BPF_MODE(insn->code);
58e2af8b 2135 struct bpf_reg_state *reg;
ddd872bc
AS
2136 int i, err;
2137
24701ece 2138 if (!may_access_skb(env->prog->type)) {
1a0dc1ac 2139 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
2140 return -EINVAL;
2141 }
2142
2143 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 2144 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 2145 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
1a0dc1ac 2146 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
2147 return -EINVAL;
2148 }
2149
2150 /* check whether implicit source operand (register R6) is readable */
2151 err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
2152 if (err)
2153 return err;
2154
2155 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
2156 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
2157 return -EINVAL;
2158 }
2159
2160 if (mode == BPF_IND) {
2161 /* check explicit source operand */
2162 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2163 if (err)
2164 return err;
2165 }
2166
2167 /* reset caller saved regs to unreadable */
2168 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2169 reg = regs + caller_saved[i];
2170 reg->type = NOT_INIT;
2171 reg->imm = 0;
2172 }
2173
2174 /* mark destination R0 register as readable, since it contains
2175 * the value fetched from the packet
2176 */
2177 regs[BPF_REG_0].type = UNKNOWN_VALUE;
2178 return 0;
2179}
2180
475fb78f
AS
2181/* non-recursive DFS pseudo code
2182 * 1 procedure DFS-iterative(G,v):
2183 * 2 label v as discovered
2184 * 3 let S be a stack
2185 * 4 S.push(v)
2186 * 5 while S is not empty
2187 * 6 t <- S.pop()
2188 * 7 if t is what we're looking for:
2189 * 8 return t
2190 * 9 for all edges e in G.adjacentEdges(t) do
2191 * 10 if edge e is already labelled
2192 * 11 continue with the next edge
2193 * 12 w <- G.adjacentVertex(t,e)
2194 * 13 if vertex w is not discovered and not explored
2195 * 14 label e as tree-edge
2196 * 15 label w as discovered
2197 * 16 S.push(w)
2198 * 17 continue at 5
2199 * 18 else if vertex w is discovered
2200 * 19 label e as back-edge
2201 * 20 else
2202 * 21 // vertex w is explored
2203 * 22 label e as forward- or cross-edge
2204 * 23 label t as explored
2205 * 24 S.pop()
2206 *
2207 * convention:
2208 * 0x10 - discovered
2209 * 0x11 - discovered and fall-through edge labelled
2210 * 0x12 - discovered and fall-through and branch edges labelled
2211 * 0x20 - explored
2212 */
2213
2214enum {
2215 DISCOVERED = 0x10,
2216 EXPLORED = 0x20,
2217 FALLTHROUGH = 1,
2218 BRANCH = 2,
2219};
2220
58e2af8b 2221#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
f1bca824 2222
475fb78f
AS
2223static int *insn_stack; /* stack of insns to process */
2224static int cur_stack; /* current stack index */
2225static int *insn_state;
2226
2227/* t, w, e - match pseudo-code above:
2228 * t - index of current instruction
2229 * w - next instruction
2230 * e - edge
2231 */
58e2af8b 2232static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
475fb78f
AS
2233{
2234 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
2235 return 0;
2236
2237 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
2238 return 0;
2239
2240 if (w < 0 || w >= env->prog->len) {
2241 verbose("jump out of range from insn %d to %d\n", t, w);
2242 return -EINVAL;
2243 }
2244
f1bca824
AS
2245 if (e == BRANCH)
2246 /* mark branch target for state pruning */
2247 env->explored_states[w] = STATE_LIST_MARK;
2248
475fb78f
AS
2249 if (insn_state[w] == 0) {
2250 /* tree-edge */
2251 insn_state[t] = DISCOVERED | e;
2252 insn_state[w] = DISCOVERED;
2253 if (cur_stack >= env->prog->len)
2254 return -E2BIG;
2255 insn_stack[cur_stack++] = w;
2256 return 1;
2257 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2258 verbose("back-edge from insn %d to %d\n", t, w);
2259 return -EINVAL;
2260 } else if (insn_state[w] == EXPLORED) {
2261 /* forward- or cross-edge */
2262 insn_state[t] = DISCOVERED | e;
2263 } else {
2264 verbose("insn state internal bug\n");
2265 return -EFAULT;
2266 }
2267 return 0;
2268}
2269
2270/* non-recursive depth-first-search to detect loops in BPF program
2271 * loop == back-edge in directed graph
2272 */
58e2af8b 2273static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
2274{
2275 struct bpf_insn *insns = env->prog->insnsi;
2276 int insn_cnt = env->prog->len;
2277 int ret = 0;
2278 int i, t;
2279
2280 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2281 if (!insn_state)
2282 return -ENOMEM;
2283
2284 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2285 if (!insn_stack) {
2286 kfree(insn_state);
2287 return -ENOMEM;
2288 }
2289
2290 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
2291 insn_stack[0] = 0; /* 0 is the first instruction */
2292 cur_stack = 1;
2293
2294peek_stack:
2295 if (cur_stack == 0)
2296 goto check_state;
2297 t = insn_stack[cur_stack - 1];
2298
2299 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
2300 u8 opcode = BPF_OP(insns[t].code);
2301
2302 if (opcode == BPF_EXIT) {
2303 goto mark_explored;
2304 } else if (opcode == BPF_CALL) {
2305 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2306 if (ret == 1)
2307 goto peek_stack;
2308 else if (ret < 0)
2309 goto err_free;
07016151
DB
2310 if (t + 1 < insn_cnt)
2311 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
2312 } else if (opcode == BPF_JA) {
2313 if (BPF_SRC(insns[t].code) != BPF_K) {
2314 ret = -EINVAL;
2315 goto err_free;
2316 }
2317 /* unconditional jump with single edge */
2318 ret = push_insn(t, t + insns[t].off + 1,
2319 FALLTHROUGH, env);
2320 if (ret == 1)
2321 goto peek_stack;
2322 else if (ret < 0)
2323 goto err_free;
f1bca824
AS
2324 /* tell verifier to check for equivalent states
2325 * after every call and jump
2326 */
c3de6317
AS
2327 if (t + 1 < insn_cnt)
2328 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
2329 } else {
2330 /* conditional jump with two edges */
2331 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2332 if (ret == 1)
2333 goto peek_stack;
2334 else if (ret < 0)
2335 goto err_free;
2336
2337 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2338 if (ret == 1)
2339 goto peek_stack;
2340 else if (ret < 0)
2341 goto err_free;
2342 }
2343 } else {
2344 /* all other non-branch instructions with single
2345 * fall-through edge
2346 */
2347 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2348 if (ret == 1)
2349 goto peek_stack;
2350 else if (ret < 0)
2351 goto err_free;
2352 }
2353
2354mark_explored:
2355 insn_state[t] = EXPLORED;
2356 if (cur_stack-- <= 0) {
2357 verbose("pop stack internal bug\n");
2358 ret = -EFAULT;
2359 goto err_free;
2360 }
2361 goto peek_stack;
2362
2363check_state:
2364 for (i = 0; i < insn_cnt; i++) {
2365 if (insn_state[i] != EXPLORED) {
2366 verbose("unreachable insn %d\n", i);
2367 ret = -EINVAL;
2368 goto err_free;
2369 }
2370 }
2371 ret = 0; /* cfg looks good */
2372
2373err_free:
2374 kfree(insn_state);
2375 kfree(insn_stack);
2376 return ret;
2377}
2378
969bf05e
AS
2379/* the following conditions reduce the number of explored insns
2380 * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2381 */
58e2af8b
JK
2382static bool compare_ptrs_to_packet(struct bpf_reg_state *old,
2383 struct bpf_reg_state *cur)
969bf05e
AS
2384{
2385 if (old->id != cur->id)
2386 return false;
2387
2388 /* old ptr_to_packet is more conservative, since it allows smaller
2389 * range. Ex:
2390 * old(off=0,r=10) is equal to cur(off=0,r=20), because
2391 * old(off=0,r=10) means that with range=10 the verifier proceeded
2392 * further and found no issues with the program. Now we're in the same
2393 * spot with cur(off=0,r=20), so we're safe too, since anything further
2394 * will only be looking at most 10 bytes after this pointer.
2395 */
2396 if (old->off == cur->off && old->range < cur->range)
2397 return true;
2398
2399 /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2400 * since both cannot be used for packet access and safe(old)
2401 * pointer has smaller off that could be used for further
2402 * 'if (ptr > data_end)' check
2403 * Ex:
2404 * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2405 * that we cannot access the packet.
2406 * The safe range is:
2407 * [ptr, ptr + range - off)
2408 * so whenever off >=range, it means no safe bytes from this pointer.
2409 * When comparing old->off <= cur->off, it means that older code
2410 * went with smaller offset and that offset was later
2411 * used to figure out the safe range after 'if (ptr > data_end)' check
2412 * Say, 'old' state was explored like:
2413 * ... R3(off=0, r=0)
2414 * R4 = R3 + 20
2415 * ... now R4(off=20,r=0) <-- here
2416 * if (R4 > data_end)
2417 * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2418 * ... the code further went all the way to bpf_exit.
2419 * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2420 * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2421 * goes further, such cur_R4 will give larger safe packet range after
2422 * 'if (R4 > data_end)' and all further insn were already good with r=20,
2423 * so they will be good with r=30 and we can prune the search.
2424 */
2425 if (old->off <= cur->off &&
2426 old->off >= old->range && cur->off >= cur->range)
2427 return true;
2428
2429 return false;
2430}
2431
f1bca824
AS
2432/* compare two verifier states
2433 *
2434 * all states stored in state_list are known to be valid, since
2435 * verifier reached 'bpf_exit' instruction through them
2436 *
2437 * this function is called when verifier exploring different branches of
2438 * execution popped from the state stack. If it sees an old state that has
2439 * more strict register state and more strict stack state then this execution
2440 * branch doesn't need to be explored further, since verifier already
2441 * concluded that more strict state leads to valid finish.
2442 *
2443 * Therefore two states are equivalent if register state is more conservative
2444 * and explored stack state is more conservative than the current one.
2445 * Example:
2446 * explored current
2447 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2448 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2449 *
2450 * In other words if current stack state (one being explored) has more
2451 * valid slots than old one that already passed validation, it means
2452 * the verifier can stop exploring and conclude that current state is valid too
2453 *
2454 * Similarly with registers. If explored state has register type as invalid
2455 * whereas register type in current state is meaningful, it means that
2456 * the current state will reach 'bpf_exit' instruction safely
2457 */
48461135
JB
2458static bool states_equal(struct bpf_verifier_env *env,
2459 struct bpf_verifier_state *old,
58e2af8b 2460 struct bpf_verifier_state *cur)
f1bca824 2461{
58e2af8b 2462 struct bpf_reg_state *rold, *rcur;
f1bca824
AS
2463 int i;
2464
2465 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
2466 rold = &old->regs[i];
2467 rcur = &cur->regs[i];
2468
2469 if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2470 continue;
2471
48461135
JB
2472 /* If the ranges were not the same, but everything else was and
2473 * we didn't do a variable access into a map then we are a-ok.
2474 */
2475 if (!env->varlen_map_value_access &&
2476 rold->type == rcur->type && rold->imm == rcur->imm)
2477 continue;
2478
1a0dc1ac
AS
2479 if (rold->type == NOT_INIT ||
2480 (rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT))
2481 continue;
2482
969bf05e
AS
2483 if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
2484 compare_ptrs_to_packet(rold, rcur))
2485 continue;
2486
1a0dc1ac 2487 return false;
f1bca824
AS
2488 }
2489
2490 for (i = 0; i < MAX_BPF_STACK; i++) {
9c399760
AS
2491 if (old->stack_slot_type[i] == STACK_INVALID)
2492 continue;
2493 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2494 /* Ex: old explored (safe) state has STACK_SPILL in
2495 * this stack slot, but current has has STACK_MISC ->
2496 * this verifier states are not equivalent,
2497 * return false to continue verification of this path
2498 */
f1bca824 2499 return false;
9c399760
AS
2500 if (i % BPF_REG_SIZE)
2501 continue;
2502 if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2503 &cur->spilled_regs[i / BPF_REG_SIZE],
2504 sizeof(old->spilled_regs[0])))
2505 /* when explored and current stack slot types are
2506 * the same, check that stored pointers types
2507 * are the same as well.
2508 * Ex: explored safe path could have stored
58e2af8b 2509 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
9c399760 2510 * but current path has stored:
58e2af8b 2511 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
9c399760
AS
2512 * such verifier states are not equivalent.
2513 * return false to continue verification of this path
2514 */
2515 return false;
2516 else
2517 continue;
f1bca824
AS
2518 }
2519 return true;
2520}
2521
58e2af8b 2522static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 2523{
58e2af8b
JK
2524 struct bpf_verifier_state_list *new_sl;
2525 struct bpf_verifier_state_list *sl;
f1bca824
AS
2526
2527 sl = env->explored_states[insn_idx];
2528 if (!sl)
2529 /* this 'insn_idx' instruction wasn't marked, so we will not
2530 * be doing state search here
2531 */
2532 return 0;
2533
2534 while (sl != STATE_LIST_MARK) {
48461135 2535 if (states_equal(env, &sl->state, &env->cur_state))
f1bca824
AS
2536 /* reached equivalent register/stack state,
2537 * prune the search
2538 */
2539 return 1;
2540 sl = sl->next;
2541 }
2542
2543 /* there were no equivalent states, remember current one.
2544 * technically the current state is not proven to be safe yet,
2545 * but it will either reach bpf_exit (which means it's safe) or
2546 * it will be rejected. Since there are no loops, we won't be
2547 * seeing this 'insn_idx' instruction again on the way to bpf_exit
2548 */
58e2af8b 2549 new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
f1bca824
AS
2550 if (!new_sl)
2551 return -ENOMEM;
2552
2553 /* add new state to the head of linked list */
2554 memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2555 new_sl->next = env->explored_states[insn_idx];
2556 env->explored_states[insn_idx] = new_sl;
2557 return 0;
2558}
2559
13a27dfc
JK
2560static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
2561 int insn_idx, int prev_insn_idx)
2562{
2563 if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
2564 return 0;
2565
2566 return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
2567}
2568
58e2af8b 2569static int do_check(struct bpf_verifier_env *env)
17a52670 2570{
58e2af8b 2571 struct bpf_verifier_state *state = &env->cur_state;
17a52670 2572 struct bpf_insn *insns = env->prog->insnsi;
58e2af8b 2573 struct bpf_reg_state *regs = state->regs;
17a52670
AS
2574 int insn_cnt = env->prog->len;
2575 int insn_idx, prev_insn_idx = 0;
2576 int insn_processed = 0;
2577 bool do_print_state = false;
2578
2579 init_reg_state(regs);
2580 insn_idx = 0;
48461135 2581 env->varlen_map_value_access = false;
17a52670
AS
2582 for (;;) {
2583 struct bpf_insn *insn;
2584 u8 class;
2585 int err;
2586
2587 if (insn_idx >= insn_cnt) {
2588 verbose("invalid insn idx %d insn_cnt %d\n",
2589 insn_idx, insn_cnt);
2590 return -EFAULT;
2591 }
2592
2593 insn = &insns[insn_idx];
2594 class = BPF_CLASS(insn->code);
2595
07016151 2596 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17a52670
AS
2597 verbose("BPF program is too large. Proccessed %d insn\n",
2598 insn_processed);
2599 return -E2BIG;
2600 }
2601
f1bca824
AS
2602 err = is_state_visited(env, insn_idx);
2603 if (err < 0)
2604 return err;
2605 if (err == 1) {
2606 /* found equivalent state, can prune the search */
2607 if (log_level) {
2608 if (do_print_state)
2609 verbose("\nfrom %d to %d: safe\n",
2610 prev_insn_idx, insn_idx);
2611 else
2612 verbose("%d: safe\n", insn_idx);
2613 }
2614 goto process_bpf_exit;
2615 }
2616
17a52670
AS
2617 if (log_level && do_print_state) {
2618 verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
1a0dc1ac 2619 print_verifier_state(&env->cur_state);
17a52670
AS
2620 do_print_state = false;
2621 }
2622
2623 if (log_level) {
2624 verbose("%d: ", insn_idx);
2625 print_bpf_insn(insn);
2626 }
2627
13a27dfc
JK
2628 err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
2629 if (err)
2630 return err;
2631
17a52670 2632 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 2633 err = check_alu_op(env, insn);
17a52670
AS
2634 if (err)
2635 return err;
2636
2637 } else if (class == BPF_LDX) {
3df126f3 2638 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
2639
2640 /* check for reserved fields is already done */
2641
17a52670
AS
2642 /* check src operand */
2643 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2644 if (err)
2645 return err;
2646
2647 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2648 if (err)
2649 return err;
2650
725f9dcd
AS
2651 src_reg_type = regs[insn->src_reg].type;
2652
17a52670
AS
2653 /* check that memory (src_reg + off) is readable,
2654 * the state of dst_reg will be updated by this func
2655 */
2656 err = check_mem_access(env, insn->src_reg, insn->off,
2657 BPF_SIZE(insn->code), BPF_READ,
2658 insn->dst_reg);
2659 if (err)
2660 return err;
2661
48461135 2662 reset_reg_range_values(regs, insn->dst_reg);
ea2e7ce5
AS
2663 if (BPF_SIZE(insn->code) != BPF_W &&
2664 BPF_SIZE(insn->code) != BPF_DW) {
725f9dcd
AS
2665 insn_idx++;
2666 continue;
2667 }
9bac3d6d 2668
3df126f3
JK
2669 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
2670
2671 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
2672 /* saw a valid insn
2673 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 2674 * save type to validate intersecting paths
9bac3d6d 2675 */
3df126f3 2676 *prev_src_type = src_reg_type;
9bac3d6d 2677
3df126f3 2678 } else if (src_reg_type != *prev_src_type &&
9bac3d6d 2679 (src_reg_type == PTR_TO_CTX ||
3df126f3 2680 *prev_src_type == PTR_TO_CTX)) {
9bac3d6d
AS
2681 /* ABuser program is trying to use the same insn
2682 * dst_reg = *(u32*) (src_reg + off)
2683 * with different pointer types:
2684 * src_reg == ctx in one branch and
2685 * src_reg == stack|map in some other branch.
2686 * Reject it.
2687 */
2688 verbose("same insn cannot be used with different pointers\n");
2689 return -EINVAL;
2690 }
2691
17a52670 2692 } else if (class == BPF_STX) {
3df126f3 2693 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 2694
17a52670
AS
2695 if (BPF_MODE(insn->code) == BPF_XADD) {
2696 err = check_xadd(env, insn);
2697 if (err)
2698 return err;
2699 insn_idx++;
2700 continue;
2701 }
2702
17a52670
AS
2703 /* check src1 operand */
2704 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2705 if (err)
2706 return err;
2707 /* check src2 operand */
2708 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2709 if (err)
2710 return err;
2711
d691f9e8
AS
2712 dst_reg_type = regs[insn->dst_reg].type;
2713
17a52670
AS
2714 /* check that memory (dst_reg + off) is writeable */
2715 err = check_mem_access(env, insn->dst_reg, insn->off,
2716 BPF_SIZE(insn->code), BPF_WRITE,
2717 insn->src_reg);
2718 if (err)
2719 return err;
2720
3df126f3
JK
2721 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
2722
2723 if (*prev_dst_type == NOT_INIT) {
2724 *prev_dst_type = dst_reg_type;
2725 } else if (dst_reg_type != *prev_dst_type &&
d691f9e8 2726 (dst_reg_type == PTR_TO_CTX ||
3df126f3 2727 *prev_dst_type == PTR_TO_CTX)) {
d691f9e8
AS
2728 verbose("same insn cannot be used with different pointers\n");
2729 return -EINVAL;
2730 }
2731
17a52670
AS
2732 } else if (class == BPF_ST) {
2733 if (BPF_MODE(insn->code) != BPF_MEM ||
2734 insn->src_reg != BPF_REG_0) {
2735 verbose("BPF_ST uses reserved fields\n");
2736 return -EINVAL;
2737 }
2738 /* check src operand */
2739 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2740 if (err)
2741 return err;
2742
2743 /* check that memory (dst_reg + off) is writeable */
2744 err = check_mem_access(env, insn->dst_reg, insn->off,
2745 BPF_SIZE(insn->code), BPF_WRITE,
2746 -1);
2747 if (err)
2748 return err;
2749
2750 } else if (class == BPF_JMP) {
2751 u8 opcode = BPF_OP(insn->code);
2752
2753 if (opcode == BPF_CALL) {
2754 if (BPF_SRC(insn->code) != BPF_K ||
2755 insn->off != 0 ||
2756 insn->src_reg != BPF_REG_0 ||
2757 insn->dst_reg != BPF_REG_0) {
2758 verbose("BPF_CALL uses reserved fields\n");
2759 return -EINVAL;
2760 }
2761
2762 err = check_call(env, insn->imm);
2763 if (err)
2764 return err;
2765
2766 } else if (opcode == BPF_JA) {
2767 if (BPF_SRC(insn->code) != BPF_K ||
2768 insn->imm != 0 ||
2769 insn->src_reg != BPF_REG_0 ||
2770 insn->dst_reg != BPF_REG_0) {
2771 verbose("BPF_JA uses reserved fields\n");
2772 return -EINVAL;
2773 }
2774
2775 insn_idx += insn->off + 1;
2776 continue;
2777
2778 } else if (opcode == BPF_EXIT) {
2779 if (BPF_SRC(insn->code) != BPF_K ||
2780 insn->imm != 0 ||
2781 insn->src_reg != BPF_REG_0 ||
2782 insn->dst_reg != BPF_REG_0) {
2783 verbose("BPF_EXIT uses reserved fields\n");
2784 return -EINVAL;
2785 }
2786
2787 /* eBPF calling convetion is such that R0 is used
2788 * to return the value from eBPF program.
2789 * Make sure that it's readable at this time
2790 * of bpf_exit, which means that program wrote
2791 * something into it earlier
2792 */
2793 err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
2794 if (err)
2795 return err;
2796
1be7f75d
AS
2797 if (is_pointer_value(env, BPF_REG_0)) {
2798 verbose("R0 leaks addr as return value\n");
2799 return -EACCES;
2800 }
2801
f1bca824 2802process_bpf_exit:
17a52670
AS
2803 insn_idx = pop_stack(env, &prev_insn_idx);
2804 if (insn_idx < 0) {
2805 break;
2806 } else {
2807 do_print_state = true;
2808 continue;
2809 }
2810 } else {
2811 err = check_cond_jmp_op(env, insn, &insn_idx);
2812 if (err)
2813 return err;
2814 }
2815 } else if (class == BPF_LD) {
2816 u8 mode = BPF_MODE(insn->code);
2817
2818 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
2819 err = check_ld_abs(env, insn);
2820 if (err)
2821 return err;
2822
17a52670
AS
2823 } else if (mode == BPF_IMM) {
2824 err = check_ld_imm(env, insn);
2825 if (err)
2826 return err;
2827
2828 insn_idx++;
2829 } else {
2830 verbose("invalid BPF_LD mode\n");
2831 return -EINVAL;
2832 }
48461135 2833 reset_reg_range_values(regs, insn->dst_reg);
17a52670
AS
2834 } else {
2835 verbose("unknown insn class %d\n", class);
2836 return -EINVAL;
2837 }
2838
2839 insn_idx++;
2840 }
2841
1a0dc1ac 2842 verbose("processed %d insns\n", insn_processed);
17a52670
AS
2843 return 0;
2844}
2845
fdc15d38
AS
2846static int check_map_prog_compatibility(struct bpf_map *map,
2847 struct bpf_prog *prog)
2848
2849{
2850 if (prog->type == BPF_PROG_TYPE_PERF_EVENT &&
2851 (map->map_type == BPF_MAP_TYPE_HASH ||
2852 map->map_type == BPF_MAP_TYPE_PERCPU_HASH) &&
2853 (map->map_flags & BPF_F_NO_PREALLOC)) {
2854 verbose("perf_event programs can only use preallocated hash map\n");
2855 return -EINVAL;
2856 }
2857 return 0;
2858}
2859
0246e64d
AS
2860/* look for pseudo eBPF instructions that access map FDs and
2861 * replace them with actual map pointers
2862 */
58e2af8b 2863static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
2864{
2865 struct bpf_insn *insn = env->prog->insnsi;
2866 int insn_cnt = env->prog->len;
fdc15d38 2867 int i, j, err;
0246e64d
AS
2868
2869 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 2870 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 2871 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
9bac3d6d
AS
2872 verbose("BPF_LDX uses reserved fields\n");
2873 return -EINVAL;
2874 }
2875
d691f9e8
AS
2876 if (BPF_CLASS(insn->code) == BPF_STX &&
2877 ((BPF_MODE(insn->code) != BPF_MEM &&
2878 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
2879 verbose("BPF_STX uses reserved fields\n");
2880 return -EINVAL;
2881 }
2882
0246e64d
AS
2883 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
2884 struct bpf_map *map;
2885 struct fd f;
2886
2887 if (i == insn_cnt - 1 || insn[1].code != 0 ||
2888 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
2889 insn[1].off != 0) {
2890 verbose("invalid bpf_ld_imm64 insn\n");
2891 return -EINVAL;
2892 }
2893
2894 if (insn->src_reg == 0)
2895 /* valid generic load 64-bit imm */
2896 goto next_insn;
2897
2898 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
2899 verbose("unrecognized bpf_ld_imm64 insn\n");
2900 return -EINVAL;
2901 }
2902
2903 f = fdget(insn->imm);
c2101297 2904 map = __bpf_map_get(f);
0246e64d
AS
2905 if (IS_ERR(map)) {
2906 verbose("fd %d is not pointing to valid bpf_map\n",
2907 insn->imm);
0246e64d
AS
2908 return PTR_ERR(map);
2909 }
2910
fdc15d38
AS
2911 err = check_map_prog_compatibility(map, env->prog);
2912 if (err) {
2913 fdput(f);
2914 return err;
2915 }
2916
0246e64d
AS
2917 /* store map pointer inside BPF_LD_IMM64 instruction */
2918 insn[0].imm = (u32) (unsigned long) map;
2919 insn[1].imm = ((u64) (unsigned long) map) >> 32;
2920
2921 /* check whether we recorded this map already */
2922 for (j = 0; j < env->used_map_cnt; j++)
2923 if (env->used_maps[j] == map) {
2924 fdput(f);
2925 goto next_insn;
2926 }
2927
2928 if (env->used_map_cnt >= MAX_USED_MAPS) {
2929 fdput(f);
2930 return -E2BIG;
2931 }
2932
0246e64d
AS
2933 /* hold the map. If the program is rejected by verifier,
2934 * the map will be released by release_maps() or it
2935 * will be used by the valid program until it's unloaded
2936 * and all maps are released in free_bpf_prog_info()
2937 */
92117d84
AS
2938 map = bpf_map_inc(map, false);
2939 if (IS_ERR(map)) {
2940 fdput(f);
2941 return PTR_ERR(map);
2942 }
2943 env->used_maps[env->used_map_cnt++] = map;
2944
0246e64d
AS
2945 fdput(f);
2946next_insn:
2947 insn++;
2948 i++;
2949 }
2950 }
2951
2952 /* now all pseudo BPF_LD_IMM64 instructions load valid
2953 * 'struct bpf_map *' into a register instead of user map_fd.
2954 * These pointers will be used later by verifier to validate map access.
2955 */
2956 return 0;
2957}
2958
2959/* drop refcnt of maps used by the rejected program */
58e2af8b 2960static void release_maps(struct bpf_verifier_env *env)
0246e64d
AS
2961{
2962 int i;
2963
2964 for (i = 0; i < env->used_map_cnt; i++)
2965 bpf_map_put(env->used_maps[i]);
2966}
2967
2968/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 2969static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
2970{
2971 struct bpf_insn *insn = env->prog->insnsi;
2972 int insn_cnt = env->prog->len;
2973 int i;
2974
2975 for (i = 0; i < insn_cnt; i++, insn++)
2976 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
2977 insn->src_reg = 0;
2978}
2979
9bac3d6d
AS
2980/* convert load instructions that access fields of 'struct __sk_buff'
2981 * into sequence of instructions that access fields of 'struct sk_buff'
2982 */
58e2af8b 2983static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 2984{
36bbef52 2985 const struct bpf_verifier_ops *ops = env->prog->aux->ops;
3df126f3 2986 const int insn_cnt = env->prog->len;
36bbef52 2987 struct bpf_insn insn_buf[16], *insn;
9bac3d6d 2988 struct bpf_prog *new_prog;
d691f9e8 2989 enum bpf_access_type type;
3df126f3 2990 int i, cnt, delta = 0;
9bac3d6d 2991
36bbef52
DB
2992 if (ops->gen_prologue) {
2993 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
2994 env->prog);
2995 if (cnt >= ARRAY_SIZE(insn_buf)) {
2996 verbose("bpf verifier is misconfigured\n");
2997 return -EINVAL;
2998 } else if (cnt) {
2999 new_prog = bpf_patch_insn_single(env->prog, 0,
3000 insn_buf, cnt);
3001 if (!new_prog)
3002 return -ENOMEM;
3003 env->prog = new_prog;
3df126f3 3004 delta += cnt - 1;
36bbef52
DB
3005 }
3006 }
3007
3008 if (!ops->convert_ctx_access)
9bac3d6d
AS
3009 return 0;
3010
3df126f3 3011 insn = env->prog->insnsi + delta;
36bbef52 3012
9bac3d6d 3013 for (i = 0; i < insn_cnt; i++, insn++) {
ea2e7ce5
AS
3014 if (insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
3015 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 3016 type = BPF_READ;
ea2e7ce5
AS
3017 else if (insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
3018 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
3019 type = BPF_WRITE;
3020 else
9bac3d6d
AS
3021 continue;
3022
3df126f3 3023 if (env->insn_aux_data[i].ptr_type != PTR_TO_CTX)
9bac3d6d 3024 continue;
9bac3d6d 3025
36bbef52
DB
3026 cnt = ops->convert_ctx_access(type, insn->dst_reg, insn->src_reg,
3027 insn->off, insn_buf, env->prog);
9bac3d6d
AS
3028 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
3029 verbose("bpf verifier is misconfigured\n");
3030 return -EINVAL;
3031 }
3032
3df126f3
JK
3033 new_prog = bpf_patch_insn_single(env->prog, i + delta, insn_buf,
3034 cnt);
9bac3d6d
AS
3035 if (!new_prog)
3036 return -ENOMEM;
3037
3df126f3 3038 delta += cnt - 1;
9bac3d6d
AS
3039
3040 /* keep walking new program and skip insns we just inserted */
3041 env->prog = new_prog;
3df126f3 3042 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
3043 }
3044
3045 return 0;
3046}
3047
58e2af8b 3048static void free_states(struct bpf_verifier_env *env)
f1bca824 3049{
58e2af8b 3050 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
3051 int i;
3052
3053 if (!env->explored_states)
3054 return;
3055
3056 for (i = 0; i < env->prog->len; i++) {
3057 sl = env->explored_states[i];
3058
3059 if (sl)
3060 while (sl != STATE_LIST_MARK) {
3061 sln = sl->next;
3062 kfree(sl);
3063 sl = sln;
3064 }
3065 }
3066
3067 kfree(env->explored_states);
3068}
3069
9bac3d6d 3070int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
51580e79 3071{
cbd35700 3072 char __user *log_ubuf = NULL;
58e2af8b 3073 struct bpf_verifier_env *env;
51580e79
AS
3074 int ret = -EINVAL;
3075
9bac3d6d 3076 if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
cbd35700
AS
3077 return -E2BIG;
3078
58e2af8b 3079 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
3080 * allocate/free it every time bpf_check() is called
3081 */
58e2af8b 3082 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
3083 if (!env)
3084 return -ENOMEM;
3085
3df126f3
JK
3086 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3087 (*prog)->len);
3088 ret = -ENOMEM;
3089 if (!env->insn_aux_data)
3090 goto err_free_env;
9bac3d6d 3091 env->prog = *prog;
0246e64d 3092
cbd35700
AS
3093 /* grab the mutex to protect few globals used by verifier */
3094 mutex_lock(&bpf_verifier_lock);
3095
3096 if (attr->log_level || attr->log_buf || attr->log_size) {
3097 /* user requested verbose verifier output
3098 * and supplied buffer to store the verification trace
3099 */
3100 log_level = attr->log_level;
3101 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
3102 log_size = attr->log_size;
3103 log_len = 0;
3104
3105 ret = -EINVAL;
3106 /* log_* values have to be sane */
3107 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
3108 log_level == 0 || log_ubuf == NULL)
3df126f3 3109 goto err_unlock;
cbd35700
AS
3110
3111 ret = -ENOMEM;
3112 log_buf = vmalloc(log_size);
3113 if (!log_buf)
3df126f3 3114 goto err_unlock;
cbd35700
AS
3115 } else {
3116 log_level = 0;
3117 }
3118
0246e64d
AS
3119 ret = replace_map_fd_with_map_ptr(env);
3120 if (ret < 0)
3121 goto skip_full_check;
3122
9bac3d6d 3123 env->explored_states = kcalloc(env->prog->len,
58e2af8b 3124 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
3125 GFP_USER);
3126 ret = -ENOMEM;
3127 if (!env->explored_states)
3128 goto skip_full_check;
3129
475fb78f
AS
3130 ret = check_cfg(env);
3131 if (ret < 0)
3132 goto skip_full_check;
3133
1be7f75d
AS
3134 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3135
17a52670 3136 ret = do_check(env);
cbd35700 3137
0246e64d 3138skip_full_check:
17a52670 3139 while (pop_stack(env, NULL) >= 0);
f1bca824 3140 free_states(env);
0246e64d 3141
9bac3d6d
AS
3142 if (ret == 0)
3143 /* program is valid, convert *(u32*)(ctx + off) accesses */
3144 ret = convert_ctx_accesses(env);
3145
cbd35700
AS
3146 if (log_level && log_len >= log_size - 1) {
3147 BUG_ON(log_len >= log_size);
3148 /* verifier log exceeded user supplied buffer */
3149 ret = -ENOSPC;
3150 /* fall through to return what was recorded */
3151 }
3152
3153 /* copy verifier log back to user space including trailing zero */
3154 if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
3155 ret = -EFAULT;
3156 goto free_log_buf;
3157 }
3158
0246e64d
AS
3159 if (ret == 0 && env->used_map_cnt) {
3160 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
3161 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
3162 sizeof(env->used_maps[0]),
3163 GFP_KERNEL);
0246e64d 3164
9bac3d6d 3165 if (!env->prog->aux->used_maps) {
0246e64d
AS
3166 ret = -ENOMEM;
3167 goto free_log_buf;
3168 }
3169
9bac3d6d 3170 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 3171 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 3172 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
3173
3174 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
3175 * bpf_ld_imm64 instructions
3176 */
3177 convert_pseudo_ld_imm64(env);
3178 }
cbd35700
AS
3179
3180free_log_buf:
3181 if (log_level)
3182 vfree(log_buf);
9bac3d6d 3183 if (!env->prog->aux->used_maps)
0246e64d
AS
3184 /* if we didn't copy map pointers into bpf_prog_info, release
3185 * them now. Otherwise free_bpf_prog_info() will release them.
3186 */
3187 release_maps(env);
9bac3d6d 3188 *prog = env->prog;
3df126f3 3189err_unlock:
cbd35700 3190 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
3191 vfree(env->insn_aux_data);
3192err_free_env:
3193 kfree(env);
51580e79
AS
3194 return ret;
3195}
13a27dfc
JK
3196
3197int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
3198 void *priv)
3199{
3200 struct bpf_verifier_env *env;
3201 int ret;
3202
3203 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
3204 if (!env)
3205 return -ENOMEM;
3206
3207 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3208 prog->len);
3209 ret = -ENOMEM;
3210 if (!env->insn_aux_data)
3211 goto err_free_env;
3212 env->prog = prog;
3213 env->analyzer_ops = ops;
3214 env->analyzer_priv = priv;
3215
3216 /* grab the mutex to protect few globals used by verifier */
3217 mutex_lock(&bpf_verifier_lock);
3218
3219 log_level = 0;
3220
3221 env->explored_states = kcalloc(env->prog->len,
3222 sizeof(struct bpf_verifier_state_list *),
3223 GFP_KERNEL);
3224 ret = -ENOMEM;
3225 if (!env->explored_states)
3226 goto skip_full_check;
3227
3228 ret = check_cfg(env);
3229 if (ret < 0)
3230 goto skip_full_check;
3231
3232 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3233
3234 ret = do_check(env);
3235
3236skip_full_check:
3237 while (pop_stack(env, NULL) >= 0);
3238 free_states(env);
3239
3240 mutex_unlock(&bpf_verifier_lock);
3241 vfree(env->insn_aux_data);
3242err_free_env:
3243 kfree(env);
3244 return ret;
3245}
3246EXPORT_SYMBOL_GPL(bpf_analyzer);