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