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