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