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