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