]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - kernel/bpf/verifier.c
bpf, nfp: implement jiting of BPF_J{LT,LE}
[mirror_ubuntu-bionic-kernel.git] / kernel / bpf / verifier.c
CommitLineData
51580e79 1/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 2 * Copyright (c) 2016 Facebook
51580e79
AS
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13#include <linux/kernel.h>
14#include <linux/types.h>
15#include <linux/slab.h>
16#include <linux/bpf.h>
58e2af8b 17#include <linux/bpf_verifier.h>
51580e79
AS
18#include <linux/filter.h>
19#include <net/netlink.h>
20#include <linux/file.h>
21#include <linux/vmalloc.h>
ebb676da 22#include <linux/stringify.h>
51580e79
AS
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
eba38a96 36 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
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 *
f1174f77 64 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 65 * means the register has some value, but it's not a valid pointer.
f1174f77 66 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
67 *
68 * When verifier sees load or store instructions the type of base register
f1174f77 69 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
51580e79
AS
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
17a52670 131/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 132struct bpf_verifier_stack_elem {
17a52670
AS
133 /* verifer state is 'st'
134 * before processing instruction 'insn_idx'
135 * and after processing instruction 'prev_insn_idx'
136 */
58e2af8b 137 struct bpf_verifier_state st;
17a52670
AS
138 int insn_idx;
139 int prev_insn_idx;
58e2af8b 140 struct bpf_verifier_stack_elem *next;
cbd35700
AS
141};
142
8e17c1b1 143#define BPF_COMPLEXITY_LIMIT_INSNS 131072
07016151
DB
144#define BPF_COMPLEXITY_LIMIT_STACK 1024
145
fad73a1a
MKL
146#define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
147
33ff9823
DB
148struct bpf_call_arg_meta {
149 struct bpf_map *map_ptr;
435faee1 150 bool raw_mode;
36bbef52 151 bool pkt_access;
435faee1
DB
152 int regno;
153 int access_size;
33ff9823
DB
154};
155
cbd35700
AS
156/* verbose verifier prints what it's seeing
157 * bpf_check() is called under lock, so no race to access these global vars
158 */
159static u32 log_level, log_size, log_len;
160static char *log_buf;
161
162static 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 */
1d056d9c 168static __printf(1, 2) void verbose(const char *fmt, ...)
cbd35700
AS
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
17a52670
AS
180/* string representation of 'enum bpf_reg_type' */
181static const char * const reg_type_str[] = {
182 [NOT_INIT] = "?",
f1174f77 183 [SCALAR_VALUE] = "inv",
17a52670
AS
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",
17a52670 188 [PTR_TO_STACK] = "fp",
969bf05e
AS
189 [PTR_TO_PACKET] = "pkt",
190 [PTR_TO_PACKET_END] = "pkt_end",
17a52670
AS
191};
192
ebb676da
TG
193#define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
194static const char * const func_id_str[] = {
195 __BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
196};
197#undef __BPF_FUNC_STR_FN
198
199static const char *func_id_name(int id)
200{
201 BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID);
202
203 if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id])
204 return func_id_str[id];
205 else
206 return "unknown";
207}
208
58e2af8b 209static void print_verifier_state(struct bpf_verifier_state *state)
17a52670 210{
58e2af8b 211 struct bpf_reg_state *reg;
17a52670
AS
212 enum bpf_reg_type t;
213 int i;
214
215 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
216 reg = &state->regs[i];
217 t = reg->type;
17a52670
AS
218 if (t == NOT_INIT)
219 continue;
220 verbose(" R%d=%s", i, reg_type_str[t]);
f1174f77
EC
221 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
222 tnum_is_const(reg->var_off)) {
223 /* reg->off should be 0 for SCALAR_VALUE */
224 verbose("%lld", reg->var_off.value + reg->off);
225 } else {
226 verbose("(id=%d", reg->id);
227 if (t != SCALAR_VALUE)
228 verbose(",off=%d", reg->off);
229 if (t == PTR_TO_PACKET)
230 verbose(",r=%d", reg->range);
231 else if (t == CONST_PTR_TO_MAP ||
232 t == PTR_TO_MAP_VALUE ||
233 t == PTR_TO_MAP_VALUE_OR_NULL)
234 verbose(",ks=%d,vs=%d",
235 reg->map_ptr->key_size,
236 reg->map_ptr->value_size);
7d1238f2
EC
237 if (tnum_is_const(reg->var_off)) {
238 /* Typically an immediate SCALAR_VALUE, but
239 * could be a pointer whose offset is too big
240 * for reg->off
241 */
242 verbose(",imm=%llx", reg->var_off.value);
243 } else {
244 if (reg->smin_value != reg->umin_value &&
245 reg->smin_value != S64_MIN)
246 verbose(",smin_value=%lld",
247 (long long)reg->smin_value);
248 if (reg->smax_value != reg->umax_value &&
249 reg->smax_value != S64_MAX)
250 verbose(",smax_value=%lld",
251 (long long)reg->smax_value);
252 if (reg->umin_value != 0)
253 verbose(",umin_value=%llu",
254 (unsigned long long)reg->umin_value);
255 if (reg->umax_value != U64_MAX)
256 verbose(",umax_value=%llu",
257 (unsigned long long)reg->umax_value);
258 if (!tnum_is_unknown(reg->var_off)) {
259 char tn_buf[48];
f1174f77 260
7d1238f2
EC
261 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
262 verbose(",var_off=%s", tn_buf);
263 }
f1174f77
EC
264 }
265 verbose(")");
266 }
17a52670 267 }
9c399760 268 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1a0dc1ac 269 if (state->stack_slot_type[i] == STACK_SPILL)
17a52670 270 verbose(" fp%d=%s", -MAX_BPF_STACK + i,
1a0dc1ac 271 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
17a52670
AS
272 }
273 verbose("\n");
274}
275
cbd35700
AS
276static const char *const bpf_class_string[] = {
277 [BPF_LD] = "ld",
278 [BPF_LDX] = "ldx",
279 [BPF_ST] = "st",
280 [BPF_STX] = "stx",
281 [BPF_ALU] = "alu",
282 [BPF_JMP] = "jmp",
283 [BPF_RET] = "BUG",
284 [BPF_ALU64] = "alu64",
285};
286
687f0715 287static const char *const bpf_alu_string[16] = {
cbd35700
AS
288 [BPF_ADD >> 4] = "+=",
289 [BPF_SUB >> 4] = "-=",
290 [BPF_MUL >> 4] = "*=",
291 [BPF_DIV >> 4] = "/=",
292 [BPF_OR >> 4] = "|=",
293 [BPF_AND >> 4] = "&=",
294 [BPF_LSH >> 4] = "<<=",
295 [BPF_RSH >> 4] = ">>=",
296 [BPF_NEG >> 4] = "neg",
297 [BPF_MOD >> 4] = "%=",
298 [BPF_XOR >> 4] = "^=",
299 [BPF_MOV >> 4] = "=",
300 [BPF_ARSH >> 4] = "s>>=",
301 [BPF_END >> 4] = "endian",
302};
303
304static const char *const bpf_ldst_string[] = {
305 [BPF_W >> 3] = "u32",
306 [BPF_H >> 3] = "u16",
307 [BPF_B >> 3] = "u8",
308 [BPF_DW >> 3] = "u64",
309};
310
687f0715 311static const char *const bpf_jmp_string[16] = {
cbd35700
AS
312 [BPF_JA >> 4] = "jmp",
313 [BPF_JEQ >> 4] = "==",
314 [BPF_JGT >> 4] = ">",
315 [BPF_JGE >> 4] = ">=",
316 [BPF_JSET >> 4] = "&",
317 [BPF_JNE >> 4] = "!=",
318 [BPF_JSGT >> 4] = "s>",
319 [BPF_JSGE >> 4] = "s>=",
320 [BPF_CALL >> 4] = "call",
321 [BPF_EXIT >> 4] = "exit",
322};
323
0d0e5769
DB
324static void print_bpf_insn(const struct bpf_verifier_env *env,
325 const struct bpf_insn *insn)
cbd35700
AS
326{
327 u8 class = BPF_CLASS(insn->code);
328
329 if (class == BPF_ALU || class == BPF_ALU64) {
330 if (BPF_SRC(insn->code) == BPF_X)
331 verbose("(%02x) %sr%d %s %sr%d\n",
332 insn->code, class == BPF_ALU ? "(u32) " : "",
333 insn->dst_reg,
334 bpf_alu_string[BPF_OP(insn->code) >> 4],
335 class == BPF_ALU ? "(u32) " : "",
336 insn->src_reg);
337 else
338 verbose("(%02x) %sr%d %s %s%d\n",
339 insn->code, class == BPF_ALU ? "(u32) " : "",
340 insn->dst_reg,
341 bpf_alu_string[BPF_OP(insn->code) >> 4],
342 class == BPF_ALU ? "(u32) " : "",
343 insn->imm);
344 } else if (class == BPF_STX) {
345 if (BPF_MODE(insn->code) == BPF_MEM)
346 verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
347 insn->code,
348 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
349 insn->dst_reg,
350 insn->off, insn->src_reg);
351 else if (BPF_MODE(insn->code) == BPF_XADD)
352 verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
353 insn->code,
354 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
355 insn->dst_reg, insn->off,
356 insn->src_reg);
357 else
358 verbose("BUG_%02x\n", insn->code);
359 } else if (class == BPF_ST) {
360 if (BPF_MODE(insn->code) != BPF_MEM) {
361 verbose("BUG_st_%02x\n", insn->code);
362 return;
363 }
364 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
365 insn->code,
366 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
367 insn->dst_reg,
368 insn->off, insn->imm);
369 } else if (class == BPF_LDX) {
370 if (BPF_MODE(insn->code) != BPF_MEM) {
371 verbose("BUG_ldx_%02x\n", insn->code);
372 return;
373 }
374 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
375 insn->code, insn->dst_reg,
376 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
377 insn->src_reg, insn->off);
378 } else if (class == BPF_LD) {
379 if (BPF_MODE(insn->code) == BPF_ABS) {
380 verbose("(%02x) r0 = *(%s *)skb[%d]\n",
381 insn->code,
382 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
383 insn->imm);
384 } else if (BPF_MODE(insn->code) == BPF_IND) {
385 verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
386 insn->code,
387 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
388 insn->src_reg, insn->imm);
0d0e5769
DB
389 } else if (BPF_MODE(insn->code) == BPF_IMM &&
390 BPF_SIZE(insn->code) == BPF_DW) {
391 /* At this point, we already made sure that the second
392 * part of the ldimm64 insn is accessible.
393 */
394 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
395 bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
396
397 if (map_ptr && !env->allow_ptr_leaks)
398 imm = 0;
399
400 verbose("(%02x) r%d = 0x%llx\n", insn->code,
401 insn->dst_reg, (unsigned long long)imm);
cbd35700
AS
402 } else {
403 verbose("BUG_ld_%02x\n", insn->code);
404 return;
405 }
406 } else if (class == BPF_JMP) {
407 u8 opcode = BPF_OP(insn->code);
408
409 if (opcode == BPF_CALL) {
ebb676da
TG
410 verbose("(%02x) call %s#%d\n", insn->code,
411 func_id_name(insn->imm), insn->imm);
cbd35700
AS
412 } else if (insn->code == (BPF_JMP | BPF_JA)) {
413 verbose("(%02x) goto pc%+d\n",
414 insn->code, insn->off);
415 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
416 verbose("(%02x) exit\n", insn->code);
417 } else if (BPF_SRC(insn->code) == BPF_X) {
418 verbose("(%02x) if r%d %s r%d goto pc%+d\n",
419 insn->code, insn->dst_reg,
420 bpf_jmp_string[BPF_OP(insn->code) >> 4],
421 insn->src_reg, insn->off);
422 } else {
423 verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
424 insn->code, insn->dst_reg,
425 bpf_jmp_string[BPF_OP(insn->code) >> 4],
426 insn->imm, insn->off);
427 }
428 } else {
429 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
430 }
431}
432
58e2af8b 433static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
17a52670 434{
58e2af8b 435 struct bpf_verifier_stack_elem *elem;
17a52670
AS
436 int insn_idx;
437
438 if (env->head == NULL)
439 return -1;
440
441 memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
442 insn_idx = env->head->insn_idx;
443 if (prev_insn_idx)
444 *prev_insn_idx = env->head->prev_insn_idx;
445 elem = env->head->next;
446 kfree(env->head);
447 env->head = elem;
448 env->stack_size--;
449 return insn_idx;
450}
451
58e2af8b
JK
452static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
453 int insn_idx, int prev_insn_idx)
17a52670 454{
58e2af8b 455 struct bpf_verifier_stack_elem *elem;
17a52670 456
58e2af8b 457 elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
458 if (!elem)
459 goto err;
460
461 memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
462 elem->insn_idx = insn_idx;
463 elem->prev_insn_idx = prev_insn_idx;
464 elem->next = env->head;
465 env->head = elem;
466 env->stack_size++;
07016151 467 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
17a52670
AS
468 verbose("BPF program is too complex\n");
469 goto err;
470 }
471 return &elem->st;
472err:
473 /* pop all elements and return */
474 while (pop_stack(env, NULL) >= 0);
475 return NULL;
476}
477
478#define CALLER_SAVED_REGS 6
479static const int caller_saved[CALLER_SAVED_REGS] = {
480 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
481};
482
f1174f77
EC
483static void __mark_reg_not_init(struct bpf_reg_state *reg);
484
b03c9f9f
EC
485/* Mark the unknown part of a register (variable offset or scalar value) as
486 * known to have the value @imm.
487 */
488static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
489{
490 reg->id = 0;
491 reg->var_off = tnum_const(imm);
492 reg->smin_value = (s64)imm;
493 reg->smax_value = (s64)imm;
494 reg->umin_value = imm;
495 reg->umax_value = imm;
496}
497
f1174f77
EC
498/* Mark the 'variable offset' part of a register as zero. This should be
499 * used only on registers holding a pointer type.
500 */
501static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 502{
b03c9f9f 503 __mark_reg_known(reg, 0);
f1174f77 504}
a9789ef9 505
f1174f77
EC
506static void mark_reg_known_zero(struct bpf_reg_state *regs, u32 regno)
507{
508 if (WARN_ON(regno >= MAX_BPF_REG)) {
509 verbose("mark_reg_known_zero(regs, %u)\n", regno);
510 /* Something bad happened, let's kill all regs */
511 for (regno = 0; regno < MAX_BPF_REG; regno++)
512 __mark_reg_not_init(regs + regno);
513 return;
514 }
515 __mark_reg_known_zero(regs + regno);
516}
517
b03c9f9f
EC
518/* Attempts to improve min/max values based on var_off information */
519static void __update_reg_bounds(struct bpf_reg_state *reg)
520{
521 /* min signed is max(sign bit) | min(other bits) */
522 reg->smin_value = max_t(s64, reg->smin_value,
523 reg->var_off.value | (reg->var_off.mask & S64_MIN));
524 /* max signed is min(sign bit) | max(other bits) */
525 reg->smax_value = min_t(s64, reg->smax_value,
526 reg->var_off.value | (reg->var_off.mask & S64_MAX));
527 reg->umin_value = max(reg->umin_value, reg->var_off.value);
528 reg->umax_value = min(reg->umax_value,
529 reg->var_off.value | reg->var_off.mask);
530}
531
532/* Uses signed min/max values to inform unsigned, and vice-versa */
533static void __reg_deduce_bounds(struct bpf_reg_state *reg)
534{
535 /* Learn sign from signed bounds.
536 * If we cannot cross the sign boundary, then signed and unsigned bounds
537 * are the same, so combine. This works even in the negative case, e.g.
538 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
539 */
540 if (reg->smin_value >= 0 || reg->smax_value < 0) {
541 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
542 reg->umin_value);
543 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
544 reg->umax_value);
545 return;
546 }
547 /* Learn sign from unsigned bounds. Signed bounds cross the sign
548 * boundary, so we must be careful.
549 */
550 if ((s64)reg->umax_value >= 0) {
551 /* Positive. We can't learn anything from the smin, but smax
552 * is positive, hence safe.
553 */
554 reg->smin_value = reg->umin_value;
555 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
556 reg->umax_value);
557 } else if ((s64)reg->umin_value < 0) {
558 /* Negative. We can't learn anything from the smax, but smin
559 * is negative, hence safe.
560 */
561 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
562 reg->umin_value);
563 reg->smax_value = reg->umax_value;
564 }
565}
566
567/* Attempts to improve var_off based on unsigned min/max information */
568static void __reg_bound_offset(struct bpf_reg_state *reg)
569{
570 reg->var_off = tnum_intersect(reg->var_off,
571 tnum_range(reg->umin_value,
572 reg->umax_value));
573}
574
575/* Reset the min/max bounds of a register */
576static void __mark_reg_unbounded(struct bpf_reg_state *reg)
577{
578 reg->smin_value = S64_MIN;
579 reg->smax_value = S64_MAX;
580 reg->umin_value = 0;
581 reg->umax_value = U64_MAX;
582}
583
f1174f77
EC
584/* Mark a register as having a completely unknown (scalar) value. */
585static void __mark_reg_unknown(struct bpf_reg_state *reg)
586{
587 reg->type = SCALAR_VALUE;
588 reg->id = 0;
589 reg->off = 0;
590 reg->var_off = tnum_unknown;
b03c9f9f 591 __mark_reg_unbounded(reg);
f1174f77
EC
592}
593
594static void mark_reg_unknown(struct bpf_reg_state *regs, u32 regno)
595{
596 if (WARN_ON(regno >= MAX_BPF_REG)) {
597 verbose("mark_reg_unknown(regs, %u)\n", regno);
598 /* Something bad happened, let's kill all regs */
599 for (regno = 0; regno < MAX_BPF_REG; regno++)
600 __mark_reg_not_init(regs + regno);
601 return;
602 }
603 __mark_reg_unknown(regs + regno);
604}
605
606static void __mark_reg_not_init(struct bpf_reg_state *reg)
607{
608 __mark_reg_unknown(reg);
609 reg->type = NOT_INIT;
610}
611
612static void mark_reg_not_init(struct bpf_reg_state *regs, u32 regno)
613{
614 if (WARN_ON(regno >= MAX_BPF_REG)) {
615 verbose("mark_reg_not_init(regs, %u)\n", regno);
616 /* Something bad happened, let's kill all regs */
617 for (regno = 0; regno < MAX_BPF_REG; regno++)
618 __mark_reg_not_init(regs + regno);
619 return;
620 }
621 __mark_reg_not_init(regs + regno);
a9789ef9
DB
622}
623
58e2af8b 624static void init_reg_state(struct bpf_reg_state *regs)
17a52670
AS
625{
626 int i;
627
a9789ef9
DB
628 for (i = 0; i < MAX_BPF_REG; i++)
629 mark_reg_not_init(regs, i);
17a52670
AS
630
631 /* frame pointer */
f1174f77
EC
632 regs[BPF_REG_FP].type = PTR_TO_STACK;
633 mark_reg_known_zero(regs, BPF_REG_FP);
17a52670
AS
634
635 /* 1st arg to a function */
636 regs[BPF_REG_1].type = PTR_TO_CTX;
f1174f77 637 mark_reg_known_zero(regs, BPF_REG_1);
6760bf2d
DB
638}
639
17a52670
AS
640enum reg_arg_type {
641 SRC_OP, /* register is used as source operand */
642 DST_OP, /* register is used as destination operand */
643 DST_OP_NO_MARK /* same as above, check only, don't mark */
644};
645
58e2af8b 646static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
17a52670
AS
647 enum reg_arg_type t)
648{
649 if (regno >= MAX_BPF_REG) {
650 verbose("R%d is invalid\n", regno);
651 return -EINVAL;
652 }
653
654 if (t == SRC_OP) {
655 /* check whether register used as source operand can be read */
656 if (regs[regno].type == NOT_INIT) {
657 verbose("R%d !read_ok\n", regno);
658 return -EACCES;
659 }
660 } else {
661 /* check whether register used as dest operand can be written to */
662 if (regno == BPF_REG_FP) {
663 verbose("frame pointer is read only\n");
664 return -EACCES;
665 }
666 if (t == DST_OP)
f1174f77 667 mark_reg_unknown(regs, regno);
17a52670
AS
668 }
669 return 0;
670}
671
1be7f75d
AS
672static bool is_spillable_regtype(enum bpf_reg_type type)
673{
674 switch (type) {
675 case PTR_TO_MAP_VALUE:
676 case PTR_TO_MAP_VALUE_OR_NULL:
677 case PTR_TO_STACK:
678 case PTR_TO_CTX:
969bf05e
AS
679 case PTR_TO_PACKET:
680 case PTR_TO_PACKET_END:
1be7f75d
AS
681 case CONST_PTR_TO_MAP:
682 return true;
683 default:
684 return false;
685 }
686}
687
17a52670
AS
688/* check_stack_read/write functions track spill/fill of registers,
689 * stack boundary and alignment are checked in check_mem_access()
690 */
58e2af8b
JK
691static int check_stack_write(struct bpf_verifier_state *state, int off,
692 int size, int value_regno)
17a52670 693{
17a52670 694 int i;
9c399760
AS
695 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
696 * so it's aligned access and [off, off + size) are within stack limits
697 */
17a52670
AS
698
699 if (value_regno >= 0 &&
1be7f75d 700 is_spillable_regtype(state->regs[value_regno].type)) {
17a52670
AS
701
702 /* register containing pointer is being spilled into stack */
9c399760 703 if (size != BPF_REG_SIZE) {
17a52670
AS
704 verbose("invalid size of register spill\n");
705 return -EACCES;
706 }
707
17a52670 708 /* save register state */
9c399760
AS
709 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
710 state->regs[value_regno];
17a52670 711
9c399760
AS
712 for (i = 0; i < BPF_REG_SIZE; i++)
713 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
714 } else {
17a52670 715 /* regular write of data into stack */
9c399760 716 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
58e2af8b 717 (struct bpf_reg_state) {};
9c399760
AS
718
719 for (i = 0; i < size; i++)
720 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
17a52670
AS
721 }
722 return 0;
723}
724
58e2af8b 725static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
17a52670
AS
726 int value_regno)
727{
9c399760 728 u8 *slot_type;
17a52670 729 int i;
17a52670 730
9c399760 731 slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
17a52670 732
9c399760
AS
733 if (slot_type[0] == STACK_SPILL) {
734 if (size != BPF_REG_SIZE) {
17a52670
AS
735 verbose("invalid size of register spill\n");
736 return -EACCES;
737 }
9c399760
AS
738 for (i = 1; i < BPF_REG_SIZE; i++) {
739 if (slot_type[i] != STACK_SPILL) {
17a52670
AS
740 verbose("corrupted spill memory\n");
741 return -EACCES;
742 }
743 }
744
745 if (value_regno >= 0)
746 /* restore register state from stack */
9c399760
AS
747 state->regs[value_regno] =
748 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
17a52670
AS
749 return 0;
750 } else {
751 for (i = 0; i < size; i++) {
9c399760 752 if (slot_type[i] != STACK_MISC) {
17a52670
AS
753 verbose("invalid read from stack off %d+%d size %d\n",
754 off, i, size);
755 return -EACCES;
756 }
757 }
758 if (value_regno >= 0)
759 /* have read misc data from the stack */
f1174f77 760 mark_reg_unknown(state->regs, value_regno);
17a52670
AS
761 return 0;
762 }
763}
764
765/* check read/write into map element returned by bpf_map_lookup_elem() */
f1174f77 766static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
17a52670
AS
767 int size)
768{
769 struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
770
5722569b 771 if (off < 0 || size <= 0 || off + size > map->value_size) {
17a52670
AS
772 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
773 map->value_size, off, size);
774 return -EACCES;
775 }
776 return 0;
777}
778
f1174f77
EC
779/* check read/write into a map element with possible variable offset */
780static int check_map_access(struct bpf_verifier_env *env, u32 regno,
dbcfe5f7
GB
781 int off, int size)
782{
783 struct bpf_verifier_state *state = &env->cur_state;
784 struct bpf_reg_state *reg = &state->regs[regno];
785 int err;
786
f1174f77
EC
787 /* We may have adjusted the register to this map value, so we
788 * need to try adding each of min_value and max_value to off
789 * to make sure our theoretical access will be safe.
dbcfe5f7
GB
790 */
791 if (log_level)
792 print_verifier_state(state);
f1174f77
EC
793 /* If the offset is variable, we will need to be stricter in state
794 * pruning from now on.
795 */
796 if (!tnum_is_const(reg->var_off))
797 env->varlen_map_value_access = true;
dbcfe5f7
GB
798 /* The minimum value is only important with signed
799 * comparisons where we can't assume the floor of a
800 * value is 0. If we are using signed variables for our
801 * index'es we need to make sure that whatever we use
802 * will have a set floor within our range.
803 */
b03c9f9f 804 if (reg->smin_value < 0) {
dbcfe5f7
GB
805 verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
806 regno);
807 return -EACCES;
808 }
b03c9f9f 809 err = __check_map_access(env, regno, reg->smin_value + off, size);
dbcfe5f7 810 if (err) {
f1174f77 811 verbose("R%d min value is outside of the array range\n", regno);
dbcfe5f7
GB
812 return err;
813 }
814
b03c9f9f
EC
815 /* If we haven't set a max value then we need to bail since we can't be
816 * sure we won't do bad things.
817 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 818 */
b03c9f9f 819 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
dbcfe5f7
GB
820 verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
821 regno);
822 return -EACCES;
823 }
b03c9f9f 824 err = __check_map_access(env, regno, reg->umax_value + off, size);
f1174f77
EC
825 if (err)
826 verbose("R%d max value is outside of the array range\n", regno);
827 return err;
dbcfe5f7
GB
828}
829
969bf05e
AS
830#define MAX_PACKET_OFF 0xffff
831
58e2af8b 832static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
833 const struct bpf_call_arg_meta *meta,
834 enum bpf_access_type t)
4acf6c0b 835{
36bbef52 836 switch (env->prog->type) {
3a0af8fd
TG
837 case BPF_PROG_TYPE_LWT_IN:
838 case BPF_PROG_TYPE_LWT_OUT:
839 /* dst_input() and dst_output() can't write for now */
840 if (t == BPF_WRITE)
841 return false;
7e57fbb2 842 /* fallthrough */
36bbef52
DB
843 case BPF_PROG_TYPE_SCHED_CLS:
844 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 845 case BPF_PROG_TYPE_XDP:
3a0af8fd 846 case BPF_PROG_TYPE_LWT_XMIT:
36bbef52
DB
847 if (meta)
848 return meta->pkt_access;
849
850 env->seen_direct_write = true;
4acf6c0b
BB
851 return true;
852 default:
853 return false;
854 }
855}
856
f1174f77
EC
857static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
858 int off, int size)
969bf05e 859{
58e2af8b
JK
860 struct bpf_reg_state *regs = env->cur_state.regs;
861 struct bpf_reg_state *reg = &regs[regno];
969bf05e 862
f1174f77 863 if (off < 0 || size <= 0 || (u64)off + size > reg->range) {
d91b28ed
AS
864 verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
865 off, size, regno, reg->id, reg->off, reg->range);
969bf05e
AS
866 return -EACCES;
867 }
868 return 0;
869}
870
f1174f77
EC
871static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
872 int size)
873{
874 struct bpf_reg_state *regs = env->cur_state.regs;
875 struct bpf_reg_state *reg = &regs[regno];
876 int err;
877
878 /* We may have added a variable offset to the packet pointer; but any
879 * reg->range we have comes after that. We are only checking the fixed
880 * offset.
881 */
882
883 /* We don't allow negative numbers, because we aren't tracking enough
884 * detail to prove they're safe.
885 */
b03c9f9f 886 if (reg->smin_value < 0) {
f1174f77
EC
887 verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
888 regno);
889 return -EACCES;
890 }
891 err = __check_packet_access(env, regno, off, size);
892 if (err) {
893 verbose("R%d offset is outside of the packet\n", regno);
894 return err;
895 }
896 return err;
897}
898
899/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 900static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
19de99f7 901 enum bpf_access_type t, enum bpf_reg_type *reg_type)
17a52670 902{
f96da094
DB
903 struct bpf_insn_access_aux info = {
904 .reg_type = *reg_type,
905 };
31fd8581 906
13a27dfc
JK
907 /* for analyzer ctx accesses are already validated and converted */
908 if (env->analyzer_ops)
909 return 0;
910
17a52670 911 if (env->prog->aux->ops->is_valid_access &&
23994631 912 env->prog->aux->ops->is_valid_access(off, size, t, &info)) {
f96da094
DB
913 /* A non zero info.ctx_field_size indicates that this field is a
914 * candidate for later verifier transformation to load the whole
915 * field and then apply a mask when accessed with a narrower
916 * access than actual ctx access size. A zero info.ctx_field_size
917 * will only allow for whole field access and rejects any other
918 * type of narrower access.
31fd8581 919 */
f96da094 920 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
23994631 921 *reg_type = info.reg_type;
31fd8581 922
32bbe007
AS
923 /* remember the offset of last byte accessed in ctx */
924 if (env->prog->aux->max_ctx_offset < off + size)
925 env->prog->aux->max_ctx_offset = off + size;
17a52670 926 return 0;
32bbe007 927 }
17a52670
AS
928
929 verbose("invalid bpf_context access off=%d size=%d\n", off, size);
930 return -EACCES;
931}
932
4cabc5b1
DB
933static bool __is_pointer_value(bool allow_ptr_leaks,
934 const struct bpf_reg_state *reg)
1be7f75d 935{
4cabc5b1 936 if (allow_ptr_leaks)
1be7f75d
AS
937 return false;
938
f1174f77 939 return reg->type != SCALAR_VALUE;
1be7f75d
AS
940}
941
4cabc5b1
DB
942static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
943{
944 return __is_pointer_value(env->allow_ptr_leaks, &env->cur_state.regs[regno]);
945}
946
79adffcd 947static int check_pkt_ptr_alignment(const struct bpf_reg_state *reg,
d1174416 948 int off, int size, bool strict)
969bf05e 949{
f1174f77 950 struct tnum reg_off;
e07b98d9 951 int ip_align;
d1174416
DM
952
953 /* Byte size accesses are always allowed. */
954 if (!strict || size == 1)
955 return 0;
956
e4eda884
DM
957 /* For platforms that do not have a Kconfig enabling
958 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
959 * NET_IP_ALIGN is universally set to '2'. And on platforms
960 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
961 * to this code only in strict mode where we want to emulate
962 * the NET_IP_ALIGN==2 checking. Therefore use an
963 * unconditional IP align value of '2'.
e07b98d9 964 */
e4eda884 965 ip_align = 2;
f1174f77
EC
966
967 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
968 if (!tnum_is_aligned(reg_off, size)) {
969 char tn_buf[48];
970
971 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
972 verbose("misaligned packet access off %d+%s+%d+%d size %d\n",
973 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
974 return -EACCES;
975 }
79adffcd 976
969bf05e
AS
977 return 0;
978}
979
f1174f77
EC
980static int check_generic_ptr_alignment(const struct bpf_reg_state *reg,
981 const char *pointer_desc,
982 int off, int size, bool strict)
79adffcd 983{
f1174f77
EC
984 struct tnum reg_off;
985
986 /* Byte size accesses are always allowed. */
987 if (!strict || size == 1)
988 return 0;
989
990 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
991 if (!tnum_is_aligned(reg_off, size)) {
992 char tn_buf[48];
993
994 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
995 verbose("misaligned %saccess off %s+%d+%d size %d\n",
996 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
997 return -EACCES;
998 }
999
969bf05e
AS
1000 return 0;
1001}
1002
e07b98d9
DM
1003static int check_ptr_alignment(struct bpf_verifier_env *env,
1004 const struct bpf_reg_state *reg,
79adffcd
DB
1005 int off, int size)
1006{
e07b98d9 1007 bool strict = env->strict_alignment;
f1174f77 1008 const char *pointer_desc = "";
d1174416 1009
79adffcd
DB
1010 switch (reg->type) {
1011 case PTR_TO_PACKET:
f1174f77 1012 /* special case, because of NET_IP_ALIGN */
d1174416 1013 return check_pkt_ptr_alignment(reg, off, size, strict);
f1174f77
EC
1014 case PTR_TO_MAP_VALUE:
1015 pointer_desc = "value ";
1016 break;
1017 case PTR_TO_CTX:
1018 pointer_desc = "context ";
1019 break;
1020 case PTR_TO_STACK:
1021 pointer_desc = "stack ";
1022 break;
79adffcd 1023 default:
f1174f77 1024 break;
79adffcd 1025 }
f1174f77 1026 return check_generic_ptr_alignment(reg, pointer_desc, off, size, strict);
79adffcd
DB
1027}
1028
17a52670
AS
1029/* check whether memory at (regno + off) is accessible for t = (read | write)
1030 * if t==write, value_regno is a register which value is stored into memory
1031 * if t==read, value_regno is a register which will receive the value from memory
1032 * if t==write && value_regno==-1, some unknown value is stored into memory
1033 * if t==read && value_regno==-1, don't care what we read from memory
1034 */
31fd8581 1035static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
17a52670
AS
1036 int bpf_size, enum bpf_access_type t,
1037 int value_regno)
1038{
58e2af8b
JK
1039 struct bpf_verifier_state *state = &env->cur_state;
1040 struct bpf_reg_state *reg = &state->regs[regno];
17a52670
AS
1041 int size, err = 0;
1042
1043 size = bpf_size_to_bytes(bpf_size);
1044 if (size < 0)
1045 return size;
1046
f1174f77 1047 /* alignment checks will add in reg->off themselves */
e07b98d9 1048 err = check_ptr_alignment(env, reg, off, size);
969bf05e
AS
1049 if (err)
1050 return err;
17a52670 1051
f1174f77
EC
1052 /* for access checks, reg->off is just part of off */
1053 off += reg->off;
1054
1055 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
1056 if (t == BPF_WRITE && value_regno >= 0 &&
1057 is_pointer_value(env, value_regno)) {
1058 verbose("R%d leaks addr into map\n", value_regno);
1059 return -EACCES;
1060 }
48461135 1061
f1174f77 1062 err = check_map_access(env, regno, off, size);
17a52670 1063 if (!err && t == BPF_READ && value_regno >= 0)
f1174f77 1064 mark_reg_unknown(state->regs, value_regno);
17a52670 1065
1a0dc1ac 1066 } else if (reg->type == PTR_TO_CTX) {
f1174f77 1067 enum bpf_reg_type reg_type = SCALAR_VALUE;
19de99f7 1068
1be7f75d
AS
1069 if (t == BPF_WRITE && value_regno >= 0 &&
1070 is_pointer_value(env, value_regno)) {
1071 verbose("R%d leaks addr into ctx\n", value_regno);
1072 return -EACCES;
1073 }
f1174f77
EC
1074 /* ctx accesses must be at a fixed offset, so that we can
1075 * determine what type of data were returned.
1076 */
1077 if (!tnum_is_const(reg->var_off)) {
1078 char tn_buf[48];
1079
1080 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1081 verbose("variable ctx access var_off=%s off=%d size=%d",
1082 tn_buf, off, size);
1083 return -EACCES;
1084 }
1085 off += reg->var_off.value;
31fd8581 1086 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
969bf05e 1087 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77
EC
1088 /* ctx access returns either a scalar, or a
1089 * PTR_TO_PACKET[_END]. In the latter case, we know
1090 * the offset is zero.
1091 */
1092 if (reg_type == SCALAR_VALUE)
1093 mark_reg_unknown(state->regs, value_regno);
1094 else
1095 mark_reg_known_zero(state->regs, value_regno);
1096 state->regs[value_regno].id = 0;
1097 state->regs[value_regno].off = 0;
1098 state->regs[value_regno].range = 0;
1955351d 1099 state->regs[value_regno].type = reg_type;
969bf05e 1100 }
17a52670 1101
f1174f77
EC
1102 } else if (reg->type == PTR_TO_STACK) {
1103 /* stack accesses must be at a fixed offset, so that we can
1104 * determine what type of data were returned.
1105 * See check_stack_read().
1106 */
1107 if (!tnum_is_const(reg->var_off)) {
1108 char tn_buf[48];
1109
1110 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1111 verbose("variable stack access var_off=%s off=%d size=%d",
1112 tn_buf, off, size);
1113 return -EACCES;
1114 }
1115 off += reg->var_off.value;
17a52670
AS
1116 if (off >= 0 || off < -MAX_BPF_STACK) {
1117 verbose("invalid stack off=%d size=%d\n", off, size);
1118 return -EACCES;
1119 }
8726679a
AS
1120
1121 if (env->prog->aux->stack_depth < -off)
1122 env->prog->aux->stack_depth = -off;
1123
1be7f75d
AS
1124 if (t == BPF_WRITE) {
1125 if (!env->allow_ptr_leaks &&
1126 state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
1127 size != BPF_REG_SIZE) {
1128 verbose("attempt to corrupt spilled pointer on stack\n");
1129 return -EACCES;
1130 }
17a52670 1131 err = check_stack_write(state, off, size, value_regno);
1be7f75d 1132 } else {
17a52670 1133 err = check_stack_read(state, off, size, value_regno);
1be7f75d 1134 }
f1174f77 1135 } else if (reg->type == PTR_TO_PACKET) {
3a0af8fd 1136 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
969bf05e
AS
1137 verbose("cannot write into packet\n");
1138 return -EACCES;
1139 }
4acf6c0b
BB
1140 if (t == BPF_WRITE && value_regno >= 0 &&
1141 is_pointer_value(env, value_regno)) {
1142 verbose("R%d leaks addr into packet\n", value_regno);
1143 return -EACCES;
1144 }
969bf05e
AS
1145 err = check_packet_access(env, regno, off, size);
1146 if (!err && t == BPF_READ && value_regno >= 0)
f1174f77 1147 mark_reg_unknown(state->regs, value_regno);
17a52670
AS
1148 } else {
1149 verbose("R%d invalid mem access '%s'\n",
1a0dc1ac 1150 regno, reg_type_str[reg->type]);
17a52670
AS
1151 return -EACCES;
1152 }
969bf05e 1153
f1174f77
EC
1154 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1155 state->regs[value_regno].type == SCALAR_VALUE) {
1156 /* b/h/w load zero-extends, mark upper bits as known 0 */
1157 state->regs[value_regno].var_off = tnum_cast(
1158 state->regs[value_regno].var_off, size);
b03c9f9f 1159 __update_reg_bounds(&state->regs[value_regno]);
969bf05e 1160 }
17a52670
AS
1161 return err;
1162}
1163
31fd8581 1164static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 1165{
58e2af8b 1166 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
1167 int err;
1168
1169 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1170 insn->imm != 0) {
1171 verbose("BPF_XADD uses reserved fields\n");
1172 return -EINVAL;
1173 }
1174
1175 /* check src1 operand */
1176 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1177 if (err)
1178 return err;
1179
1180 /* check src2 operand */
1181 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1182 if (err)
1183 return err;
1184
6bdf6abc
DB
1185 if (is_pointer_value(env, insn->src_reg)) {
1186 verbose("R%d leaks addr into mem\n", insn->src_reg);
1187 return -EACCES;
1188 }
1189
17a52670 1190 /* check whether atomic_add can read the memory */
31fd8581 1191 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
17a52670
AS
1192 BPF_SIZE(insn->code), BPF_READ, -1);
1193 if (err)
1194 return err;
1195
1196 /* check whether atomic_add can write into the same memory */
31fd8581 1197 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
17a52670
AS
1198 BPF_SIZE(insn->code), BPF_WRITE, -1);
1199}
1200
f1174f77
EC
1201/* Does this register contain a constant zero? */
1202static bool register_is_null(struct bpf_reg_state reg)
1203{
1204 return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
1205}
1206
17a52670
AS
1207/* when register 'regno' is passed into function that will read 'access_size'
1208 * bytes from that pointer, make sure that it's within stack boundary
f1174f77
EC
1209 * and all elements of stack are initialized.
1210 * Unlike most pointer bounds-checking functions, this one doesn't take an
1211 * 'off' argument, so it has to add in reg->off itself.
17a52670 1212 */
58e2af8b 1213static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
1214 int access_size, bool zero_size_allowed,
1215 struct bpf_call_arg_meta *meta)
17a52670 1216{
58e2af8b
JK
1217 struct bpf_verifier_state *state = &env->cur_state;
1218 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1219 int off, i;
1220
8e2fe1d9 1221 if (regs[regno].type != PTR_TO_STACK) {
f1174f77 1222 /* Allow zero-byte read from NULL, regardless of pointer type */
8e2fe1d9 1223 if (zero_size_allowed && access_size == 0 &&
f1174f77 1224 register_is_null(regs[regno]))
8e2fe1d9
DB
1225 return 0;
1226
1227 verbose("R%d type=%s expected=%s\n", regno,
1228 reg_type_str[regs[regno].type],
1229 reg_type_str[PTR_TO_STACK]);
17a52670 1230 return -EACCES;
8e2fe1d9 1231 }
17a52670 1232
f1174f77
EC
1233 /* Only allow fixed-offset stack reads */
1234 if (!tnum_is_const(regs[regno].var_off)) {
1235 char tn_buf[48];
1236
1237 tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
1238 verbose("invalid variable stack read R%d var_off=%s\n",
1239 regno, tn_buf);
1240 }
1241 off = regs[regno].off + regs[regno].var_off.value;
17a52670
AS
1242 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1243 access_size <= 0) {
1244 verbose("invalid stack type R%d off=%d access_size=%d\n",
1245 regno, off, access_size);
1246 return -EACCES;
1247 }
1248
8726679a
AS
1249 if (env->prog->aux->stack_depth < -off)
1250 env->prog->aux->stack_depth = -off;
1251
435faee1
DB
1252 if (meta && meta->raw_mode) {
1253 meta->access_size = access_size;
1254 meta->regno = regno;
1255 return 0;
1256 }
1257
17a52670 1258 for (i = 0; i < access_size; i++) {
9c399760 1259 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
17a52670
AS
1260 verbose("invalid indirect read from stack off %d+%d size %d\n",
1261 off, i, access_size);
1262 return -EACCES;
1263 }
1264 }
1265 return 0;
1266}
1267
06c1c049
GB
1268static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1269 int access_size, bool zero_size_allowed,
1270 struct bpf_call_arg_meta *meta)
1271{
f1174f77 1272 struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
06c1c049 1273
f1174f77 1274 switch (reg->type) {
06c1c049 1275 case PTR_TO_PACKET:
f1174f77 1276 return check_packet_access(env, regno, reg->off, access_size);
06c1c049 1277 case PTR_TO_MAP_VALUE:
f1174f77
EC
1278 return check_map_access(env, regno, reg->off, access_size);
1279 default: /* scalar_value|ptr_to_stack or invalid ptr */
06c1c049
GB
1280 return check_stack_boundary(env, regno, access_size,
1281 zero_size_allowed, meta);
1282 }
1283}
1284
58e2af8b 1285static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
33ff9823
DB
1286 enum bpf_arg_type arg_type,
1287 struct bpf_call_arg_meta *meta)
17a52670 1288{
58e2af8b 1289 struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
6841de8b 1290 enum bpf_reg_type expected_type, type = reg->type;
17a52670
AS
1291 int err = 0;
1292
80f1d68c 1293 if (arg_type == ARG_DONTCARE)
17a52670
AS
1294 return 0;
1295
6841de8b 1296 if (type == NOT_INIT) {
17a52670
AS
1297 verbose("R%d !read_ok\n", regno);
1298 return -EACCES;
1299 }
1300
1be7f75d
AS
1301 if (arg_type == ARG_ANYTHING) {
1302 if (is_pointer_value(env, regno)) {
1303 verbose("R%d leaks addr into helper function\n", regno);
1304 return -EACCES;
1305 }
80f1d68c 1306 return 0;
1be7f75d 1307 }
80f1d68c 1308
3a0af8fd
TG
1309 if (type == PTR_TO_PACKET &&
1310 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
36bbef52 1311 verbose("helper access to the packet is not allowed\n");
6841de8b
AS
1312 return -EACCES;
1313 }
1314
8e2fe1d9 1315 if (arg_type == ARG_PTR_TO_MAP_KEY ||
17a52670
AS
1316 arg_type == ARG_PTR_TO_MAP_VALUE) {
1317 expected_type = PTR_TO_STACK;
6841de8b
AS
1318 if (type != PTR_TO_PACKET && type != expected_type)
1319 goto err_type;
39f19ebb
AS
1320 } else if (arg_type == ARG_CONST_SIZE ||
1321 arg_type == ARG_CONST_SIZE_OR_ZERO) {
f1174f77
EC
1322 expected_type = SCALAR_VALUE;
1323 if (type != expected_type)
6841de8b 1324 goto err_type;
17a52670
AS
1325 } else if (arg_type == ARG_CONST_MAP_PTR) {
1326 expected_type = CONST_PTR_TO_MAP;
6841de8b
AS
1327 if (type != expected_type)
1328 goto err_type;
608cd71a
AS
1329 } else if (arg_type == ARG_PTR_TO_CTX) {
1330 expected_type = PTR_TO_CTX;
6841de8b
AS
1331 if (type != expected_type)
1332 goto err_type;
39f19ebb
AS
1333 } else if (arg_type == ARG_PTR_TO_MEM ||
1334 arg_type == ARG_PTR_TO_UNINIT_MEM) {
8e2fe1d9
DB
1335 expected_type = PTR_TO_STACK;
1336 /* One exception here. In case function allows for NULL to be
f1174f77 1337 * passed in as argument, it's a SCALAR_VALUE type. Final test
8e2fe1d9
DB
1338 * happens during stack boundary checking.
1339 */
f1174f77 1340 if (register_is_null(*reg))
6841de8b 1341 /* final test in check_stack_boundary() */;
5722569b 1342 else if (type != PTR_TO_PACKET && type != PTR_TO_MAP_VALUE &&
f1174f77 1343 type != expected_type)
6841de8b 1344 goto err_type;
39f19ebb 1345 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
17a52670
AS
1346 } else {
1347 verbose("unsupported arg_type %d\n", arg_type);
1348 return -EFAULT;
1349 }
1350
17a52670
AS
1351 if (arg_type == ARG_CONST_MAP_PTR) {
1352 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 1353 meta->map_ptr = reg->map_ptr;
17a52670
AS
1354 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1355 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1356 * check that [key, key + map->key_size) are within
1357 * stack limits and initialized
1358 */
33ff9823 1359 if (!meta->map_ptr) {
17a52670
AS
1360 /* in function declaration map_ptr must come before
1361 * map_key, so that it's verified and known before
1362 * we have to check map_key here. Otherwise it means
1363 * that kernel subsystem misconfigured verifier
1364 */
1365 verbose("invalid map_ptr to access map->key\n");
1366 return -EACCES;
1367 }
6841de8b 1368 if (type == PTR_TO_PACKET)
f1174f77 1369 err = check_packet_access(env, regno, reg->off,
6841de8b
AS
1370 meta->map_ptr->key_size);
1371 else
1372 err = check_stack_boundary(env, regno,
1373 meta->map_ptr->key_size,
1374 false, NULL);
17a52670
AS
1375 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1376 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1377 * check [value, value + map->value_size) validity
1378 */
33ff9823 1379 if (!meta->map_ptr) {
17a52670
AS
1380 /* kernel subsystem misconfigured verifier */
1381 verbose("invalid map_ptr to access map->value\n");
1382 return -EACCES;
1383 }
6841de8b 1384 if (type == PTR_TO_PACKET)
f1174f77 1385 err = check_packet_access(env, regno, reg->off,
6841de8b
AS
1386 meta->map_ptr->value_size);
1387 else
1388 err = check_stack_boundary(env, regno,
1389 meta->map_ptr->value_size,
1390 false, NULL);
39f19ebb
AS
1391 } else if (arg_type == ARG_CONST_SIZE ||
1392 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1393 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 1394
17a52670
AS
1395 /* bpf_xxx(..., buf, len) call will access 'len' bytes
1396 * from stack pointer 'buf'. Check it
1397 * note: regno == len, regno - 1 == buf
1398 */
1399 if (regno == 0) {
1400 /* kernel subsystem misconfigured verifier */
39f19ebb 1401 verbose("ARG_CONST_SIZE cannot be first argument\n");
17a52670
AS
1402 return -EACCES;
1403 }
06c1c049 1404
f1174f77
EC
1405 /* The register is SCALAR_VALUE; the access check
1406 * happens using its boundaries.
06c1c049 1407 */
f1174f77
EC
1408
1409 if (!tnum_is_const(reg->var_off))
06c1c049
GB
1410 /* For unprivileged variable accesses, disable raw
1411 * mode so that the program is required to
1412 * initialize all the memory that the helper could
1413 * just partially fill up.
1414 */
1415 meta = NULL;
1416
b03c9f9f 1417 if (reg->smin_value < 0) {
f1174f77
EC
1418 verbose("R%d min value is negative, either use unsigned or 'var &= const'\n",
1419 regno);
1420 return -EACCES;
1421 }
06c1c049 1422
b03c9f9f 1423 if (reg->umin_value == 0) {
f1174f77
EC
1424 err = check_helper_mem_access(env, regno - 1, 0,
1425 zero_size_allowed,
1426 meta);
06c1c049
GB
1427 if (err)
1428 return err;
06c1c049 1429 }
f1174f77 1430
b03c9f9f 1431 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
f1174f77
EC
1432 verbose("R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
1433 regno);
1434 return -EACCES;
1435 }
1436 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 1437 reg->umax_value,
f1174f77 1438 zero_size_allowed, meta);
17a52670
AS
1439 }
1440
1441 return err;
6841de8b
AS
1442err_type:
1443 verbose("R%d type=%s expected=%s\n", regno,
1444 reg_type_str[type], reg_type_str[expected_type]);
1445 return -EACCES;
17a52670
AS
1446}
1447
35578d79
KX
1448static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1449{
35578d79
KX
1450 if (!map)
1451 return 0;
1452
6aff67c8
AS
1453 /* We need a two way check, first is from map perspective ... */
1454 switch (map->map_type) {
1455 case BPF_MAP_TYPE_PROG_ARRAY:
1456 if (func_id != BPF_FUNC_tail_call)
1457 goto error;
1458 break;
1459 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1460 if (func_id != BPF_FUNC_perf_event_read &&
1461 func_id != BPF_FUNC_perf_event_output)
1462 goto error;
1463 break;
1464 case BPF_MAP_TYPE_STACK_TRACE:
1465 if (func_id != BPF_FUNC_get_stackid)
1466 goto error;
1467 break;
4ed8ec52 1468 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 1469 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 1470 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
1471 goto error;
1472 break;
546ac1ff
JF
1473 /* devmap returns a pointer to a live net_device ifindex that we cannot
1474 * allow to be modified from bpf side. So do not allow lookup elements
1475 * for now.
1476 */
1477 case BPF_MAP_TYPE_DEVMAP:
2ddf71e2 1478 if (func_id != BPF_FUNC_redirect_map)
546ac1ff
JF
1479 goto error;
1480 break;
56f668df 1481 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 1482 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
1483 if (func_id != BPF_FUNC_map_lookup_elem)
1484 goto error;
6aff67c8
AS
1485 default:
1486 break;
1487 }
1488
1489 /* ... and second from the function itself. */
1490 switch (func_id) {
1491 case BPF_FUNC_tail_call:
1492 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1493 goto error;
1494 break;
1495 case BPF_FUNC_perf_event_read:
1496 case BPF_FUNC_perf_event_output:
1497 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1498 goto error;
1499 break;
1500 case BPF_FUNC_get_stackid:
1501 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1502 goto error;
1503 break;
60d20f91 1504 case BPF_FUNC_current_task_under_cgroup:
747ea55e 1505 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
1506 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1507 goto error;
1508 break;
97f91a7c
JF
1509 case BPF_FUNC_redirect_map:
1510 if (map->map_type != BPF_MAP_TYPE_DEVMAP)
1511 goto error;
1512 break;
6aff67c8
AS
1513 default:
1514 break;
35578d79
KX
1515 }
1516
1517 return 0;
6aff67c8 1518error:
ebb676da
TG
1519 verbose("cannot pass map_type %d into func %s#%d\n",
1520 map->map_type, func_id_name(func_id), func_id);
6aff67c8 1521 return -EINVAL;
35578d79
KX
1522}
1523
435faee1
DB
1524static int check_raw_mode(const struct bpf_func_proto *fn)
1525{
1526 int count = 0;
1527
39f19ebb 1528 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1529 count++;
39f19ebb 1530 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1531 count++;
39f19ebb 1532 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1533 count++;
39f19ebb 1534 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1535 count++;
39f19ebb 1536 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
1537 count++;
1538
1539 return count > 1 ? -EINVAL : 0;
1540}
1541
f1174f77
EC
1542/* Packet data might have moved, any old PTR_TO_PACKET[_END] are now invalid,
1543 * so turn them into unknown SCALAR_VALUE.
1544 */
58e2af8b 1545static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
969bf05e 1546{
58e2af8b
JK
1547 struct bpf_verifier_state *state = &env->cur_state;
1548 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
1549 int i;
1550
1551 for (i = 0; i < MAX_BPF_REG; i++)
1552 if (regs[i].type == PTR_TO_PACKET ||
1553 regs[i].type == PTR_TO_PACKET_END)
f1174f77 1554 mark_reg_unknown(regs, i);
969bf05e
AS
1555
1556 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1557 if (state->stack_slot_type[i] != STACK_SPILL)
1558 continue;
1559 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1560 if (reg->type != PTR_TO_PACKET &&
1561 reg->type != PTR_TO_PACKET_END)
1562 continue;
f1174f77 1563 __mark_reg_unknown(reg);
969bf05e
AS
1564 }
1565}
1566
81ed18ab 1567static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 1568{
58e2af8b 1569 struct bpf_verifier_state *state = &env->cur_state;
17a52670 1570 const struct bpf_func_proto *fn = NULL;
58e2af8b 1571 struct bpf_reg_state *regs = state->regs;
33ff9823 1572 struct bpf_call_arg_meta meta;
969bf05e 1573 bool changes_data;
17a52670
AS
1574 int i, err;
1575
1576 /* find function prototype */
1577 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
ebb676da 1578 verbose("invalid func %s#%d\n", func_id_name(func_id), func_id);
17a52670
AS
1579 return -EINVAL;
1580 }
1581
1582 if (env->prog->aux->ops->get_func_proto)
1583 fn = env->prog->aux->ops->get_func_proto(func_id);
1584
1585 if (!fn) {
ebb676da 1586 verbose("unknown func %s#%d\n", func_id_name(func_id), func_id);
17a52670
AS
1587 return -EINVAL;
1588 }
1589
1590 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 1591 if (!env->prog->gpl_compatible && fn->gpl_only) {
17a52670
AS
1592 verbose("cannot call GPL only function from proprietary program\n");
1593 return -EINVAL;
1594 }
1595
17bedab2 1596 changes_data = bpf_helper_changes_pkt_data(fn->func);
969bf05e 1597
33ff9823 1598 memset(&meta, 0, sizeof(meta));
36bbef52 1599 meta.pkt_access = fn->pkt_access;
33ff9823 1600
435faee1
DB
1601 /* We only support one arg being in raw mode at the moment, which
1602 * is sufficient for the helper functions we have right now.
1603 */
1604 err = check_raw_mode(fn);
1605 if (err) {
ebb676da
TG
1606 verbose("kernel subsystem misconfigured func %s#%d\n",
1607 func_id_name(func_id), func_id);
435faee1
DB
1608 return err;
1609 }
1610
17a52670 1611 /* check args */
33ff9823 1612 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
17a52670
AS
1613 if (err)
1614 return err;
33ff9823 1615 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
17a52670
AS
1616 if (err)
1617 return err;
33ff9823 1618 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
17a52670
AS
1619 if (err)
1620 return err;
33ff9823 1621 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
17a52670
AS
1622 if (err)
1623 return err;
33ff9823 1624 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
17a52670
AS
1625 if (err)
1626 return err;
1627
435faee1
DB
1628 /* Mark slots with STACK_MISC in case of raw mode, stack offset
1629 * is inferred from register state.
1630 */
1631 for (i = 0; i < meta.access_size; i++) {
31fd8581 1632 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
435faee1
DB
1633 if (err)
1634 return err;
1635 }
1636
17a52670 1637 /* reset caller saved regs */
a9789ef9
DB
1638 for (i = 0; i < CALLER_SAVED_REGS; i++)
1639 mark_reg_not_init(regs, caller_saved[i]);
17a52670
AS
1640
1641 /* update return register */
1642 if (fn->ret_type == RET_INTEGER) {
f1174f77
EC
1643 /* sets type to SCALAR_VALUE */
1644 mark_reg_unknown(regs, BPF_REG_0);
17a52670
AS
1645 } else if (fn->ret_type == RET_VOID) {
1646 regs[BPF_REG_0].type = NOT_INIT;
1647 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
fad73a1a
MKL
1648 struct bpf_insn_aux_data *insn_aux;
1649
17a52670 1650 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
f1174f77
EC
1651 /* There is no offset yet applied, variable or fixed */
1652 mark_reg_known_zero(regs, BPF_REG_0);
1653 regs[BPF_REG_0].off = 0;
17a52670
AS
1654 /* remember map_ptr, so that check_map_access()
1655 * can check 'value_size' boundary of memory access
1656 * to map element returned from bpf_map_lookup_elem()
1657 */
33ff9823 1658 if (meta.map_ptr == NULL) {
17a52670
AS
1659 verbose("kernel subsystem misconfigured verifier\n");
1660 return -EINVAL;
1661 }
33ff9823 1662 regs[BPF_REG_0].map_ptr = meta.map_ptr;
57a09bf0 1663 regs[BPF_REG_0].id = ++env->id_gen;
fad73a1a
MKL
1664 insn_aux = &env->insn_aux_data[insn_idx];
1665 if (!insn_aux->map_ptr)
1666 insn_aux->map_ptr = meta.map_ptr;
1667 else if (insn_aux->map_ptr != meta.map_ptr)
1668 insn_aux->map_ptr = BPF_MAP_PTR_POISON;
17a52670 1669 } else {
ebb676da
TG
1670 verbose("unknown return type %d of func %s#%d\n",
1671 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
1672 return -EINVAL;
1673 }
04fd61ab 1674
33ff9823 1675 err = check_map_func_compatibility(meta.map_ptr, func_id);
35578d79
KX
1676 if (err)
1677 return err;
04fd61ab 1678
969bf05e
AS
1679 if (changes_data)
1680 clear_all_pkt_pointers(env);
1681 return 0;
1682}
1683
f1174f77
EC
1684static void coerce_reg_to_32(struct bpf_reg_state *reg)
1685{
f1174f77
EC
1686 /* clear high 32 bits */
1687 reg->var_off = tnum_cast(reg->var_off, 4);
b03c9f9f
EC
1688 /* Update bounds */
1689 __update_reg_bounds(reg);
1690}
1691
1692static bool signed_add_overflows(s64 a, s64 b)
1693{
1694 /* Do the add in u64, where overflow is well-defined */
1695 s64 res = (s64)((u64)a + (u64)b);
1696
1697 if (b < 0)
1698 return res > a;
1699 return res < a;
1700}
1701
1702static bool signed_sub_overflows(s64 a, s64 b)
1703{
1704 /* Do the sub in u64, where overflow is well-defined */
1705 s64 res = (s64)((u64)a - (u64)b);
1706
1707 if (b < 0)
1708 return res < a;
1709 return res > a;
969bf05e
AS
1710}
1711
f1174f77 1712/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
1713 * Caller should also handle BPF_MOV case separately.
1714 * If we return -EACCES, caller may want to try again treating pointer as a
1715 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
1716 */
1717static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
1718 struct bpf_insn *insn,
1719 const struct bpf_reg_state *ptr_reg,
1720 const struct bpf_reg_state *off_reg)
969bf05e 1721{
f1174f77
EC
1722 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1723 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
1724 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
1725 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
1726 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
1727 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
969bf05e 1728 u8 opcode = BPF_OP(insn->code);
f1174f77 1729 u32 dst = insn->dst_reg;
969bf05e 1730
f1174f77 1731 dst_reg = &regs[dst];
969bf05e 1732
b03c9f9f 1733 if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
f1174f77 1734 print_verifier_state(&env->cur_state);
b03c9f9f
EC
1735 verbose("verifier internal error: known but bad sbounds\n");
1736 return -EINVAL;
1737 }
1738 if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
1739 print_verifier_state(&env->cur_state);
1740 verbose("verifier internal error: known but bad ubounds\n");
f1174f77
EC
1741 return -EINVAL;
1742 }
1743
1744 if (BPF_CLASS(insn->code) != BPF_ALU64) {
1745 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
1746 if (!env->allow_ptr_leaks)
1747 verbose("R%d 32-bit pointer arithmetic prohibited\n",
1748 dst);
1749 return -EACCES;
969bf05e
AS
1750 }
1751
f1174f77
EC
1752 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
1753 if (!env->allow_ptr_leaks)
1754 verbose("R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
1755 dst);
1756 return -EACCES;
1757 }
1758 if (ptr_reg->type == CONST_PTR_TO_MAP) {
1759 if (!env->allow_ptr_leaks)
1760 verbose("R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
1761 dst);
1762 return -EACCES;
1763 }
1764 if (ptr_reg->type == PTR_TO_PACKET_END) {
1765 if (!env->allow_ptr_leaks)
1766 verbose("R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
1767 dst);
1768 return -EACCES;
1769 }
1770
1771 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
1772 * The id may be overwritten later if we create a new variable offset.
969bf05e 1773 */
f1174f77
EC
1774 dst_reg->type = ptr_reg->type;
1775 dst_reg->id = ptr_reg->id;
969bf05e 1776
f1174f77
EC
1777 switch (opcode) {
1778 case BPF_ADD:
1779 /* We can take a fixed offset as long as it doesn't overflow
1780 * the s32 'off' field
969bf05e 1781 */
b03c9f9f
EC
1782 if (known && (ptr_reg->off + smin_val ==
1783 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 1784 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
1785 dst_reg->smin_value = smin_ptr;
1786 dst_reg->smax_value = smax_ptr;
1787 dst_reg->umin_value = umin_ptr;
1788 dst_reg->umax_value = umax_ptr;
f1174f77 1789 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 1790 dst_reg->off = ptr_reg->off + smin_val;
f1174f77
EC
1791 dst_reg->range = ptr_reg->range;
1792 break;
1793 }
f1174f77
EC
1794 /* A new variable offset is created. Note that off_reg->off
1795 * == 0, since it's a scalar.
1796 * dst_reg gets the pointer type and since some positive
1797 * integer value was added to the pointer, give it a new 'id'
1798 * if it's a PTR_TO_PACKET.
1799 * this creates a new 'base' pointer, off_reg (variable) gets
1800 * added into the variable offset, and we copy the fixed offset
1801 * from ptr_reg.
969bf05e 1802 */
b03c9f9f
EC
1803 if (signed_add_overflows(smin_ptr, smin_val) ||
1804 signed_add_overflows(smax_ptr, smax_val)) {
1805 dst_reg->smin_value = S64_MIN;
1806 dst_reg->smax_value = S64_MAX;
1807 } else {
1808 dst_reg->smin_value = smin_ptr + smin_val;
1809 dst_reg->smax_value = smax_ptr + smax_val;
1810 }
1811 if (umin_ptr + umin_val < umin_ptr ||
1812 umax_ptr + umax_val < umax_ptr) {
1813 dst_reg->umin_value = 0;
1814 dst_reg->umax_value = U64_MAX;
1815 } else {
1816 dst_reg->umin_value = umin_ptr + umin_val;
1817 dst_reg->umax_value = umax_ptr + umax_val;
1818 }
f1174f77
EC
1819 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
1820 dst_reg->off = ptr_reg->off;
1821 if (ptr_reg->type == PTR_TO_PACKET) {
1822 dst_reg->id = ++env->id_gen;
1823 /* something was added to pkt_ptr, set range to zero */
1824 dst_reg->range = 0;
1825 }
1826 break;
1827 case BPF_SUB:
1828 if (dst_reg == off_reg) {
1829 /* scalar -= pointer. Creates an unknown scalar */
1830 if (!env->allow_ptr_leaks)
1831 verbose("R%d tried to subtract pointer from scalar\n",
1832 dst);
1833 return -EACCES;
1834 }
1835 /* We don't allow subtraction from FP, because (according to
1836 * test_verifier.c test "invalid fp arithmetic", JITs might not
1837 * be able to deal with it.
969bf05e 1838 */
f1174f77
EC
1839 if (ptr_reg->type == PTR_TO_STACK) {
1840 if (!env->allow_ptr_leaks)
1841 verbose("R%d subtraction from stack pointer prohibited\n",
1842 dst);
1843 return -EACCES;
1844 }
b03c9f9f
EC
1845 if (known && (ptr_reg->off - smin_val ==
1846 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 1847 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
1848 dst_reg->smin_value = smin_ptr;
1849 dst_reg->smax_value = smax_ptr;
1850 dst_reg->umin_value = umin_ptr;
1851 dst_reg->umax_value = umax_ptr;
f1174f77
EC
1852 dst_reg->var_off = ptr_reg->var_off;
1853 dst_reg->id = ptr_reg->id;
b03c9f9f 1854 dst_reg->off = ptr_reg->off - smin_val;
f1174f77
EC
1855 dst_reg->range = ptr_reg->range;
1856 break;
1857 }
f1174f77
EC
1858 /* A new variable offset is created. If the subtrahend is known
1859 * nonnegative, then any reg->range we had before is still good.
969bf05e 1860 */
b03c9f9f
EC
1861 if (signed_sub_overflows(smin_ptr, smax_val) ||
1862 signed_sub_overflows(smax_ptr, smin_val)) {
1863 /* Overflow possible, we know nothing */
1864 dst_reg->smin_value = S64_MIN;
1865 dst_reg->smax_value = S64_MAX;
1866 } else {
1867 dst_reg->smin_value = smin_ptr - smax_val;
1868 dst_reg->smax_value = smax_ptr - smin_val;
1869 }
1870 if (umin_ptr < umax_val) {
1871 /* Overflow possible, we know nothing */
1872 dst_reg->umin_value = 0;
1873 dst_reg->umax_value = U64_MAX;
1874 } else {
1875 /* Cannot overflow (as long as bounds are consistent) */
1876 dst_reg->umin_value = umin_ptr - umax_val;
1877 dst_reg->umax_value = umax_ptr - umin_val;
1878 }
f1174f77
EC
1879 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
1880 dst_reg->off = ptr_reg->off;
1881 if (ptr_reg->type == PTR_TO_PACKET) {
1882 dst_reg->id = ++env->id_gen;
1883 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 1884 if (smin_val < 0)
f1174f77 1885 dst_reg->range = 0;
43188702 1886 }
f1174f77
EC
1887 break;
1888 case BPF_AND:
1889 case BPF_OR:
1890 case BPF_XOR:
1891 /* bitwise ops on pointers are troublesome, prohibit for now.
1892 * (However, in principle we could allow some cases, e.g.
1893 * ptr &= ~3 which would reduce min_value by 3.)
1894 */
1895 if (!env->allow_ptr_leaks)
1896 verbose("R%d bitwise operator %s on pointer prohibited\n",
1897 dst, bpf_alu_string[opcode >> 4]);
1898 return -EACCES;
1899 default:
1900 /* other operators (e.g. MUL,LSH) produce non-pointer results */
1901 if (!env->allow_ptr_leaks)
1902 verbose("R%d pointer arithmetic with %s operator prohibited\n",
1903 dst, bpf_alu_string[opcode >> 4]);
1904 return -EACCES;
43188702
JF
1905 }
1906
b03c9f9f
EC
1907 __update_reg_bounds(dst_reg);
1908 __reg_deduce_bounds(dst_reg);
1909 __reg_bound_offset(dst_reg);
43188702
JF
1910 return 0;
1911}
1912
f1174f77
EC
1913static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
1914 struct bpf_insn *insn,
1915 struct bpf_reg_state *dst_reg,
1916 struct bpf_reg_state src_reg)
969bf05e 1917{
58e2af8b 1918 struct bpf_reg_state *regs = env->cur_state.regs;
48461135 1919 u8 opcode = BPF_OP(insn->code);
f1174f77 1920 bool src_known, dst_known;
b03c9f9f
EC
1921 s64 smin_val, smax_val;
1922 u64 umin_val, umax_val;
48461135 1923
f1174f77
EC
1924 if (BPF_CLASS(insn->code) != BPF_ALU64) {
1925 /* 32-bit ALU ops are (32,32)->64 */
1926 coerce_reg_to_32(dst_reg);
1927 coerce_reg_to_32(&src_reg);
9305706c 1928 }
b03c9f9f
EC
1929 smin_val = src_reg.smin_value;
1930 smax_val = src_reg.smax_value;
1931 umin_val = src_reg.umin_value;
1932 umax_val = src_reg.umax_value;
f1174f77
EC
1933 src_known = tnum_is_const(src_reg.var_off);
1934 dst_known = tnum_is_const(dst_reg->var_off);
f23cc643 1935
48461135
JB
1936 switch (opcode) {
1937 case BPF_ADD:
b03c9f9f
EC
1938 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
1939 signed_add_overflows(dst_reg->smax_value, smax_val)) {
1940 dst_reg->smin_value = S64_MIN;
1941 dst_reg->smax_value = S64_MAX;
1942 } else {
1943 dst_reg->smin_value += smin_val;
1944 dst_reg->smax_value += smax_val;
1945 }
1946 if (dst_reg->umin_value + umin_val < umin_val ||
1947 dst_reg->umax_value + umax_val < umax_val) {
1948 dst_reg->umin_value = 0;
1949 dst_reg->umax_value = U64_MAX;
1950 } else {
1951 dst_reg->umin_value += umin_val;
1952 dst_reg->umax_value += umax_val;
1953 }
f1174f77 1954 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
1955 break;
1956 case BPF_SUB:
b03c9f9f
EC
1957 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
1958 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
1959 /* Overflow possible, we know nothing */
1960 dst_reg->smin_value = S64_MIN;
1961 dst_reg->smax_value = S64_MAX;
1962 } else {
1963 dst_reg->smin_value -= smax_val;
1964 dst_reg->smax_value -= smin_val;
1965 }
1966 if (dst_reg->umin_value < umax_val) {
1967 /* Overflow possible, we know nothing */
1968 dst_reg->umin_value = 0;
1969 dst_reg->umax_value = U64_MAX;
1970 } else {
1971 /* Cannot overflow (as long as bounds are consistent) */
1972 dst_reg->umin_value -= umax_val;
1973 dst_reg->umax_value -= umin_val;
1974 }
f1174f77 1975 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
1976 break;
1977 case BPF_MUL:
b03c9f9f
EC
1978 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
1979 if (smin_val < 0 || dst_reg->smin_value < 0) {
f1174f77 1980 /* Ain't nobody got time to multiply that sign */
b03c9f9f
EC
1981 __mark_reg_unbounded(dst_reg);
1982 __update_reg_bounds(dst_reg);
f1174f77
EC
1983 break;
1984 }
b03c9f9f
EC
1985 /* Both values are positive, so we can work with unsigned and
1986 * copy the result to signed (unless it exceeds S64_MAX).
f1174f77 1987 */
b03c9f9f
EC
1988 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
1989 /* Potential overflow, we know nothing */
1990 __mark_reg_unbounded(dst_reg);
1991 /* (except what we can learn from the var_off) */
1992 __update_reg_bounds(dst_reg);
1993 break;
1994 }
1995 dst_reg->umin_value *= umin_val;
1996 dst_reg->umax_value *= umax_val;
1997 if (dst_reg->umax_value > S64_MAX) {
1998 /* Overflow possible, we know nothing */
1999 dst_reg->smin_value = S64_MIN;
2000 dst_reg->smax_value = S64_MAX;
2001 } else {
2002 dst_reg->smin_value = dst_reg->umin_value;
2003 dst_reg->smax_value = dst_reg->umax_value;
2004 }
48461135
JB
2005 break;
2006 case BPF_AND:
f1174f77 2007 if (src_known && dst_known) {
b03c9f9f
EC
2008 __mark_reg_known(dst_reg, dst_reg->var_off.value &
2009 src_reg.var_off.value);
f1174f77
EC
2010 break;
2011 }
b03c9f9f
EC
2012 /* We get our minimum from the var_off, since that's inherently
2013 * bitwise. Our maximum is the minimum of the operands' maxima.
f23cc643 2014 */
f1174f77 2015 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
b03c9f9f
EC
2016 dst_reg->umin_value = dst_reg->var_off.value;
2017 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2018 if (dst_reg->smin_value < 0 || smin_val < 0) {
2019 /* Lose signed bounds when ANDing negative numbers,
2020 * ain't nobody got time for that.
2021 */
2022 dst_reg->smin_value = S64_MIN;
2023 dst_reg->smax_value = S64_MAX;
2024 } else {
2025 /* ANDing two positives gives a positive, so safe to
2026 * cast result into s64.
2027 */
2028 dst_reg->smin_value = dst_reg->umin_value;
2029 dst_reg->smax_value = dst_reg->umax_value;
2030 }
2031 /* We may learn something more from the var_off */
2032 __update_reg_bounds(dst_reg);
f1174f77
EC
2033 break;
2034 case BPF_OR:
2035 if (src_known && dst_known) {
b03c9f9f
EC
2036 __mark_reg_known(dst_reg, dst_reg->var_off.value |
2037 src_reg.var_off.value);
f1174f77
EC
2038 break;
2039 }
b03c9f9f
EC
2040 /* We get our maximum from the var_off, and our minimum is the
2041 * maximum of the operands' minima
f1174f77
EC
2042 */
2043 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
b03c9f9f
EC
2044 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2045 dst_reg->umax_value = dst_reg->var_off.value |
2046 dst_reg->var_off.mask;
2047 if (dst_reg->smin_value < 0 || smin_val < 0) {
2048 /* Lose signed bounds when ORing negative numbers,
2049 * ain't nobody got time for that.
2050 */
2051 dst_reg->smin_value = S64_MIN;
2052 dst_reg->smax_value = S64_MAX;
f1174f77 2053 } else {
b03c9f9f
EC
2054 /* ORing two positives gives a positive, so safe to
2055 * cast result into s64.
2056 */
2057 dst_reg->smin_value = dst_reg->umin_value;
2058 dst_reg->smax_value = dst_reg->umax_value;
f1174f77 2059 }
b03c9f9f
EC
2060 /* We may learn something more from the var_off */
2061 __update_reg_bounds(dst_reg);
48461135
JB
2062 break;
2063 case BPF_LSH:
b03c9f9f
EC
2064 if (umax_val > 63) {
2065 /* Shifts greater than 63 are undefined. This includes
2066 * shifts by a negative number.
2067 */
f1174f77
EC
2068 mark_reg_unknown(regs, insn->dst_reg);
2069 break;
2070 }
b03c9f9f
EC
2071 /* We lose all sign bit information (except what we can pick
2072 * up from var_off)
48461135 2073 */
b03c9f9f
EC
2074 dst_reg->smin_value = S64_MIN;
2075 dst_reg->smax_value = S64_MAX;
2076 /* If we might shift our top bit out, then we know nothing */
2077 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2078 dst_reg->umin_value = 0;
2079 dst_reg->umax_value = U64_MAX;
d1174416 2080 } else {
b03c9f9f
EC
2081 dst_reg->umin_value <<= umin_val;
2082 dst_reg->umax_value <<= umax_val;
d1174416 2083 }
b03c9f9f
EC
2084 if (src_known)
2085 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2086 else
2087 dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
2088 /* We may learn something more from the var_off */
2089 __update_reg_bounds(dst_reg);
48461135
JB
2090 break;
2091 case BPF_RSH:
b03c9f9f
EC
2092 if (umax_val > 63) {
2093 /* Shifts greater than 63 are undefined. This includes
2094 * shifts by a negative number.
2095 */
f1174f77
EC
2096 mark_reg_unknown(regs, insn->dst_reg);
2097 break;
2098 }
2099 /* BPF_RSH is an unsigned shift, so make the appropriate casts */
b03c9f9f
EC
2100 if (dst_reg->smin_value < 0) {
2101 if (umin_val) {
f1174f77 2102 /* Sign bit will be cleared */
b03c9f9f
EC
2103 dst_reg->smin_value = 0;
2104 } else {
2105 /* Lost sign bit information */
2106 dst_reg->smin_value = S64_MIN;
2107 dst_reg->smax_value = S64_MAX;
2108 }
d1174416 2109 } else {
b03c9f9f
EC
2110 dst_reg->smin_value =
2111 (u64)(dst_reg->smin_value) >> umax_val;
d1174416 2112 }
f1174f77 2113 if (src_known)
b03c9f9f
EC
2114 dst_reg->var_off = tnum_rshift(dst_reg->var_off,
2115 umin_val);
f1174f77 2116 else
b03c9f9f
EC
2117 dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
2118 dst_reg->umin_value >>= umax_val;
2119 dst_reg->umax_value >>= umin_val;
2120 /* We may learn something more from the var_off */
2121 __update_reg_bounds(dst_reg);
48461135
JB
2122 break;
2123 default:
f1174f77 2124 mark_reg_unknown(regs, insn->dst_reg);
48461135
JB
2125 break;
2126 }
2127
b03c9f9f
EC
2128 __reg_deduce_bounds(dst_reg);
2129 __reg_bound_offset(dst_reg);
f1174f77
EC
2130 return 0;
2131}
2132
2133/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2134 * and var_off.
2135 */
2136static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2137 struct bpf_insn *insn)
2138{
2139 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg, *src_reg;
2140 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2141 u8 opcode = BPF_OP(insn->code);
2142 int rc;
2143
2144 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
2145 src_reg = NULL;
2146 if (dst_reg->type != SCALAR_VALUE)
2147 ptr_reg = dst_reg;
2148 if (BPF_SRC(insn->code) == BPF_X) {
2149 src_reg = &regs[insn->src_reg];
f1174f77
EC
2150 if (src_reg->type != SCALAR_VALUE) {
2151 if (dst_reg->type != SCALAR_VALUE) {
2152 /* Combining two pointers by any ALU op yields
2153 * an arbitrary scalar.
2154 */
2155 if (!env->allow_ptr_leaks) {
2156 verbose("R%d pointer %s pointer prohibited\n",
2157 insn->dst_reg,
2158 bpf_alu_string[opcode >> 4]);
2159 return -EACCES;
2160 }
2161 mark_reg_unknown(regs, insn->dst_reg);
2162 return 0;
2163 } else {
2164 /* scalar += pointer
2165 * This is legal, but we have to reverse our
2166 * src/dest handling in computing the range
2167 */
2168 rc = adjust_ptr_min_max_vals(env, insn,
2169 src_reg, dst_reg);
2170 if (rc == -EACCES && env->allow_ptr_leaks) {
2171 /* scalar += unknown scalar */
2172 __mark_reg_unknown(&off_reg);
2173 return adjust_scalar_min_max_vals(
2174 env, insn,
2175 dst_reg, off_reg);
2176 }
2177 return rc;
2178 }
2179 } else if (ptr_reg) {
2180 /* pointer += scalar */
2181 rc = adjust_ptr_min_max_vals(env, insn,
2182 dst_reg, src_reg);
2183 if (rc == -EACCES && env->allow_ptr_leaks) {
2184 /* unknown scalar += scalar */
2185 __mark_reg_unknown(dst_reg);
2186 return adjust_scalar_min_max_vals(
2187 env, insn, dst_reg, *src_reg);
2188 }
2189 return rc;
2190 }
2191 } else {
2192 /* Pretend the src is a reg with a known value, since we only
2193 * need to be able to read from this state.
2194 */
2195 off_reg.type = SCALAR_VALUE;
b03c9f9f 2196 __mark_reg_known(&off_reg, insn->imm);
f1174f77 2197 src_reg = &off_reg;
f1174f77
EC
2198 if (ptr_reg) { /* pointer += K */
2199 rc = adjust_ptr_min_max_vals(env, insn,
2200 ptr_reg, src_reg);
2201 if (rc == -EACCES && env->allow_ptr_leaks) {
2202 /* unknown scalar += K */
2203 __mark_reg_unknown(dst_reg);
2204 return adjust_scalar_min_max_vals(
2205 env, insn, dst_reg, off_reg);
2206 }
2207 return rc;
2208 }
2209 }
2210
2211 /* Got here implies adding two SCALAR_VALUEs */
2212 if (WARN_ON_ONCE(ptr_reg)) {
2213 print_verifier_state(&env->cur_state);
2214 verbose("verifier internal error: unexpected ptr_reg\n");
2215 return -EINVAL;
2216 }
2217 if (WARN_ON(!src_reg)) {
2218 print_verifier_state(&env->cur_state);
2219 verbose("verifier internal error: no src_reg\n");
2220 return -EINVAL;
2221 }
2222 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
2223}
2224
17a52670 2225/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 2226static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 2227{
f1174f77 2228 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
2229 u8 opcode = BPF_OP(insn->code);
2230 int err;
2231
2232 if (opcode == BPF_END || opcode == BPF_NEG) {
2233 if (opcode == BPF_NEG) {
2234 if (BPF_SRC(insn->code) != 0 ||
2235 insn->src_reg != BPF_REG_0 ||
2236 insn->off != 0 || insn->imm != 0) {
2237 verbose("BPF_NEG uses reserved fields\n");
2238 return -EINVAL;
2239 }
2240 } else {
2241 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
2242 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
2243 verbose("BPF_END uses reserved fields\n");
2244 return -EINVAL;
2245 }
2246 }
2247
2248 /* check src operand */
2249 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2250 if (err)
2251 return err;
2252
1be7f75d
AS
2253 if (is_pointer_value(env, insn->dst_reg)) {
2254 verbose("R%d pointer arithmetic prohibited\n",
2255 insn->dst_reg);
2256 return -EACCES;
2257 }
2258
17a52670
AS
2259 /* check dest operand */
2260 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
2261 if (err)
2262 return err;
2263
2264 } else if (opcode == BPF_MOV) {
2265
2266 if (BPF_SRC(insn->code) == BPF_X) {
2267 if (insn->imm != 0 || insn->off != 0) {
2268 verbose("BPF_MOV uses reserved fields\n");
2269 return -EINVAL;
2270 }
2271
2272 /* check src operand */
2273 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2274 if (err)
2275 return err;
2276 } else {
2277 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2278 verbose("BPF_MOV uses reserved fields\n");
2279 return -EINVAL;
2280 }
2281 }
2282
2283 /* check dest operand */
2284 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
2285 if (err)
2286 return err;
2287
2288 if (BPF_SRC(insn->code) == BPF_X) {
2289 if (BPF_CLASS(insn->code) == BPF_ALU64) {
2290 /* case: R1 = R2
2291 * copy register state to dest reg
2292 */
2293 regs[insn->dst_reg] = regs[insn->src_reg];
2294 } else {
f1174f77 2295 /* R1 = (u32) R2 */
1be7f75d
AS
2296 if (is_pointer_value(env, insn->src_reg)) {
2297 verbose("R%d partial copy of pointer\n",
2298 insn->src_reg);
2299 return -EACCES;
2300 }
f1174f77 2301 mark_reg_unknown(regs, insn->dst_reg);
b03c9f9f 2302 /* high 32 bits are known zero. */
f1174f77
EC
2303 regs[insn->dst_reg].var_off = tnum_cast(
2304 regs[insn->dst_reg].var_off, 4);
b03c9f9f 2305 __update_reg_bounds(&regs[insn->dst_reg]);
17a52670
AS
2306 }
2307 } else {
2308 /* case: R = imm
2309 * remember the value we stored into this reg
2310 */
f1174f77 2311 regs[insn->dst_reg].type = SCALAR_VALUE;
b03c9f9f 2312 __mark_reg_known(regs + insn->dst_reg, insn->imm);
17a52670
AS
2313 }
2314
2315 } else if (opcode > BPF_END) {
2316 verbose("invalid BPF_ALU opcode %x\n", opcode);
2317 return -EINVAL;
2318
2319 } else { /* all other ALU ops: and, sub, xor, add, ... */
2320
17a52670
AS
2321 if (BPF_SRC(insn->code) == BPF_X) {
2322 if (insn->imm != 0 || insn->off != 0) {
2323 verbose("BPF_ALU uses reserved fields\n");
2324 return -EINVAL;
2325 }
2326 /* check src1 operand */
2327 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2328 if (err)
2329 return err;
2330 } else {
2331 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2332 verbose("BPF_ALU uses reserved fields\n");
2333 return -EINVAL;
2334 }
2335 }
2336
2337 /* check src2 operand */
2338 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2339 if (err)
2340 return err;
2341
2342 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
2343 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
2344 verbose("div by zero\n");
2345 return -EINVAL;
2346 }
2347
229394e8
RV
2348 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
2349 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
2350 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
2351
2352 if (insn->imm < 0 || insn->imm >= size) {
2353 verbose("invalid shift %d\n", insn->imm);
2354 return -EINVAL;
2355 }
2356 }
2357
1a0dc1ac
AS
2358 /* check dest operand */
2359 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2360 if (err)
2361 return err;
2362
f1174f77 2363 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
2364 }
2365
2366 return 0;
2367}
2368
58e2af8b
JK
2369static void find_good_pkt_pointers(struct bpf_verifier_state *state,
2370 struct bpf_reg_state *dst_reg)
969bf05e 2371{
58e2af8b 2372 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e 2373 int i;
2d2be8ca 2374
f1174f77
EC
2375 if (dst_reg->off < 0)
2376 /* This doesn't give us any range */
2377 return;
2378
b03c9f9f
EC
2379 if (dst_reg->umax_value > MAX_PACKET_OFF ||
2380 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
2381 /* Risk of overflow. For instance, ptr + (1<<63) may be less
2382 * than pkt_end, but that's because it's also less than pkt.
2383 */
2384 return;
2385
2d2be8ca
DB
2386 /* LLVM can generate two kind of checks:
2387 *
2388 * Type 1:
2389 *
2390 * r2 = r3;
2391 * r2 += 8;
2392 * if (r2 > pkt_end) goto <handle exception>
2393 * <access okay>
2394 *
2395 * Where:
2396 * r2 == dst_reg, pkt_end == src_reg
2397 * r2=pkt(id=n,off=8,r=0)
2398 * r3=pkt(id=n,off=0,r=0)
2399 *
2400 * Type 2:
2401 *
2402 * r2 = r3;
2403 * r2 += 8;
2404 * if (pkt_end >= r2) goto <access okay>
2405 * <handle exception>
2406 *
2407 * Where:
2408 * pkt_end == dst_reg, r2 == src_reg
2409 * r2=pkt(id=n,off=8,r=0)
2410 * r3=pkt(id=n,off=0,r=0)
2411 *
2412 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
2413 * so that range of bytes [r3, r3 + 8) is safe to access.
969bf05e 2414 */
2d2be8ca 2415
f1174f77
EC
2416 /* If our ids match, then we must have the same max_value. And we
2417 * don't care about the other reg's fixed offset, since if it's too big
2418 * the range won't allow anything.
2419 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
2420 */
969bf05e
AS
2421 for (i = 0; i < MAX_BPF_REG; i++)
2422 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
b1977682 2423 /* keep the maximum range already checked */
f1174f77 2424 regs[i].range = max_t(u16, regs[i].range, dst_reg->off);
969bf05e
AS
2425
2426 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2427 if (state->stack_slot_type[i] != STACK_SPILL)
2428 continue;
2429 reg = &state->spilled_regs[i / BPF_REG_SIZE];
2430 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
f1174f77 2431 reg->range = max_t(u16, reg->range, dst_reg->off);
969bf05e
AS
2432 }
2433}
2434
48461135
JB
2435/* Adjusts the register min/max values in the case that the dst_reg is the
2436 * variable register that we are working on, and src_reg is a constant or we're
2437 * simply doing a BPF_K check.
f1174f77 2438 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
2439 */
2440static void reg_set_min_max(struct bpf_reg_state *true_reg,
2441 struct bpf_reg_state *false_reg, u64 val,
2442 u8 opcode)
2443{
f1174f77
EC
2444 /* If the dst_reg is a pointer, we can't learn anything about its
2445 * variable offset from the compare (unless src_reg were a pointer into
2446 * the same object, but we don't bother with that.
2447 * Since false_reg and true_reg have the same type by construction, we
2448 * only need to check one of them for pointerness.
2449 */
2450 if (__is_pointer_value(false, false_reg))
2451 return;
4cabc5b1 2452
48461135
JB
2453 switch (opcode) {
2454 case BPF_JEQ:
2455 /* If this is false then we know nothing Jon Snow, but if it is
2456 * true then we know for sure.
2457 */
b03c9f9f 2458 __mark_reg_known(true_reg, val);
48461135
JB
2459 break;
2460 case BPF_JNE:
2461 /* If this is true we know nothing Jon Snow, but if it is false
2462 * we know the value for sure;
2463 */
b03c9f9f 2464 __mark_reg_known(false_reg, val);
48461135
JB
2465 break;
2466 case BPF_JGT:
b03c9f9f
EC
2467 false_reg->umax_value = min(false_reg->umax_value, val);
2468 true_reg->umin_value = max(true_reg->umin_value, val + 1);
2469 break;
48461135 2470 case BPF_JSGT:
b03c9f9f
EC
2471 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
2472 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
48461135
JB
2473 break;
2474 case BPF_JGE:
b03c9f9f
EC
2475 false_reg->umax_value = min(false_reg->umax_value, val - 1);
2476 true_reg->umin_value = max(true_reg->umin_value, val);
2477 break;
48461135 2478 case BPF_JSGE:
b03c9f9f
EC
2479 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
2480 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
48461135
JB
2481 break;
2482 default:
2483 break;
2484 }
2485
b03c9f9f
EC
2486 __reg_deduce_bounds(false_reg);
2487 __reg_deduce_bounds(true_reg);
2488 /* We might have learned some bits from the bounds. */
2489 __reg_bound_offset(false_reg);
2490 __reg_bound_offset(true_reg);
2491 /* Intersecting with the old var_off might have improved our bounds
2492 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2493 * then new var_off is (0; 0x7f...fc) which improves our umax.
2494 */
2495 __update_reg_bounds(false_reg);
2496 __update_reg_bounds(true_reg);
48461135
JB
2497}
2498
f1174f77
EC
2499/* Same as above, but for the case that dst_reg holds a constant and src_reg is
2500 * the variable reg.
48461135
JB
2501 */
2502static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
2503 struct bpf_reg_state *false_reg, u64 val,
2504 u8 opcode)
2505{
f1174f77
EC
2506 if (__is_pointer_value(false, false_reg))
2507 return;
4cabc5b1 2508
48461135
JB
2509 switch (opcode) {
2510 case BPF_JEQ:
2511 /* If this is false then we know nothing Jon Snow, but if it is
2512 * true then we know for sure.
2513 */
b03c9f9f 2514 __mark_reg_known(true_reg, val);
48461135
JB
2515 break;
2516 case BPF_JNE:
2517 /* If this is true we know nothing Jon Snow, but if it is false
2518 * we know the value for sure;
2519 */
b03c9f9f 2520 __mark_reg_known(false_reg, val);
48461135
JB
2521 break;
2522 case BPF_JGT:
b03c9f9f
EC
2523 true_reg->umax_value = min(true_reg->umax_value, val - 1);
2524 false_reg->umin_value = max(false_reg->umin_value, val);
2525 break;
48461135 2526 case BPF_JSGT:
b03c9f9f
EC
2527 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
2528 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
48461135
JB
2529 break;
2530 case BPF_JGE:
b03c9f9f
EC
2531 true_reg->umax_value = min(true_reg->umax_value, val);
2532 false_reg->umin_value = max(false_reg->umin_value, val + 1);
2533 break;
48461135 2534 case BPF_JSGE:
b03c9f9f
EC
2535 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
2536 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
48461135
JB
2537 break;
2538 default:
2539 break;
2540 }
2541
b03c9f9f
EC
2542 __reg_deduce_bounds(false_reg);
2543 __reg_deduce_bounds(true_reg);
2544 /* We might have learned some bits from the bounds. */
2545 __reg_bound_offset(false_reg);
2546 __reg_bound_offset(true_reg);
2547 /* Intersecting with the old var_off might have improved our bounds
2548 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2549 * then new var_off is (0; 0x7f...fc) which improves our umax.
2550 */
2551 __update_reg_bounds(false_reg);
2552 __update_reg_bounds(true_reg);
f1174f77
EC
2553}
2554
2555/* Regs are known to be equal, so intersect their min/max/var_off */
2556static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
2557 struct bpf_reg_state *dst_reg)
2558{
b03c9f9f
EC
2559 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
2560 dst_reg->umin_value);
2561 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
2562 dst_reg->umax_value);
2563 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
2564 dst_reg->smin_value);
2565 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
2566 dst_reg->smax_value);
f1174f77
EC
2567 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
2568 dst_reg->var_off);
b03c9f9f
EC
2569 /* We might have learned new bounds from the var_off. */
2570 __update_reg_bounds(src_reg);
2571 __update_reg_bounds(dst_reg);
2572 /* We might have learned something about the sign bit. */
2573 __reg_deduce_bounds(src_reg);
2574 __reg_deduce_bounds(dst_reg);
2575 /* We might have learned some bits from the bounds. */
2576 __reg_bound_offset(src_reg);
2577 __reg_bound_offset(dst_reg);
2578 /* Intersecting with the old var_off might have improved our bounds
2579 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2580 * then new var_off is (0; 0x7f...fc) which improves our umax.
2581 */
2582 __update_reg_bounds(src_reg);
2583 __update_reg_bounds(dst_reg);
f1174f77
EC
2584}
2585
2586static void reg_combine_min_max(struct bpf_reg_state *true_src,
2587 struct bpf_reg_state *true_dst,
2588 struct bpf_reg_state *false_src,
2589 struct bpf_reg_state *false_dst,
2590 u8 opcode)
2591{
2592 switch (opcode) {
2593 case BPF_JEQ:
2594 __reg_combine_min_max(true_src, true_dst);
2595 break;
2596 case BPF_JNE:
2597 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 2598 break;
4cabc5b1 2599 }
48461135
JB
2600}
2601
57a09bf0 2602static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
f1174f77 2603 bool is_null)
57a09bf0
TG
2604{
2605 struct bpf_reg_state *reg = &regs[regno];
2606
2607 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
f1174f77
EC
2608 /* Old offset (both fixed and variable parts) should
2609 * have been known-zero, because we don't allow pointer
2610 * arithmetic on pointers that might be NULL.
2611 */
b03c9f9f
EC
2612 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
2613 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 2614 reg->off)) {
b03c9f9f
EC
2615 __mark_reg_known_zero(reg);
2616 reg->off = 0;
f1174f77
EC
2617 }
2618 if (is_null) {
2619 reg->type = SCALAR_VALUE;
56f668df
MKL
2620 } else if (reg->map_ptr->inner_map_meta) {
2621 reg->type = CONST_PTR_TO_MAP;
2622 reg->map_ptr = reg->map_ptr->inner_map_meta;
2623 } else {
f1174f77 2624 reg->type = PTR_TO_MAP_VALUE;
56f668df 2625 }
a08dd0da
DB
2626 /* We don't need id from this point onwards anymore, thus we
2627 * should better reset it, so that state pruning has chances
2628 * to take effect.
2629 */
2630 reg->id = 0;
57a09bf0
TG
2631 }
2632}
2633
2634/* The logic is similar to find_good_pkt_pointers(), both could eventually
2635 * be folded together at some point.
2636 */
2637static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
f1174f77 2638 bool is_null)
57a09bf0
TG
2639{
2640 struct bpf_reg_state *regs = state->regs;
a08dd0da 2641 u32 id = regs[regno].id;
57a09bf0
TG
2642 int i;
2643
2644 for (i = 0; i < MAX_BPF_REG; i++)
f1174f77 2645 mark_map_reg(regs, i, id, is_null);
57a09bf0
TG
2646
2647 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2648 if (state->stack_slot_type[i] != STACK_SPILL)
2649 continue;
f1174f77 2650 mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, is_null);
57a09bf0
TG
2651 }
2652}
2653
58e2af8b 2654static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
2655 struct bpf_insn *insn, int *insn_idx)
2656{
58e2af8b
JK
2657 struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
2658 struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
17a52670
AS
2659 u8 opcode = BPF_OP(insn->code);
2660 int err;
2661
2662 if (opcode > BPF_EXIT) {
2663 verbose("invalid BPF_JMP opcode %x\n", opcode);
2664 return -EINVAL;
2665 }
2666
2667 if (BPF_SRC(insn->code) == BPF_X) {
2668 if (insn->imm != 0) {
2669 verbose("BPF_JMP uses reserved fields\n");
2670 return -EINVAL;
2671 }
2672
2673 /* check src1 operand */
2674 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2675 if (err)
2676 return err;
1be7f75d
AS
2677
2678 if (is_pointer_value(env, insn->src_reg)) {
2679 verbose("R%d pointer comparison prohibited\n",
2680 insn->src_reg);
2681 return -EACCES;
2682 }
17a52670
AS
2683 } else {
2684 if (insn->src_reg != BPF_REG_0) {
2685 verbose("BPF_JMP uses reserved fields\n");
2686 return -EINVAL;
2687 }
2688 }
2689
2690 /* check src2 operand */
2691 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2692 if (err)
2693 return err;
2694
1a0dc1ac
AS
2695 dst_reg = &regs[insn->dst_reg];
2696
17a52670
AS
2697 /* detect if R == 0 where R was initialized to zero earlier */
2698 if (BPF_SRC(insn->code) == BPF_K &&
2699 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
f1174f77
EC
2700 dst_reg->type == SCALAR_VALUE &&
2701 tnum_equals_const(dst_reg->var_off, insn->imm)) {
17a52670
AS
2702 if (opcode == BPF_JEQ) {
2703 /* if (imm == imm) goto pc+off;
2704 * only follow the goto, ignore fall-through
2705 */
2706 *insn_idx += insn->off;
2707 return 0;
2708 } else {
2709 /* if (imm != imm) goto pc+off;
2710 * only follow fall-through branch, since
2711 * that's where the program will go
2712 */
2713 return 0;
2714 }
2715 }
2716
2717 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
2718 if (!other_branch)
2719 return -EFAULT;
2720
48461135
JB
2721 /* detect if we are comparing against a constant value so we can adjust
2722 * our min/max values for our dst register.
f1174f77
EC
2723 * this is only legit if both are scalars (or pointers to the same
2724 * object, I suppose, but we don't support that right now), because
2725 * otherwise the different base pointers mean the offsets aren't
2726 * comparable.
48461135
JB
2727 */
2728 if (BPF_SRC(insn->code) == BPF_X) {
f1174f77
EC
2729 if (dst_reg->type == SCALAR_VALUE &&
2730 regs[insn->src_reg].type == SCALAR_VALUE) {
2731 if (tnum_is_const(regs[insn->src_reg].var_off))
2732 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2733 dst_reg, regs[insn->src_reg].var_off.value,
2734 opcode);
2735 else if (tnum_is_const(dst_reg->var_off))
2736 reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
2737 &regs[insn->src_reg],
2738 dst_reg->var_off.value, opcode);
2739 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
2740 /* Comparing for equality, we can combine knowledge */
2741 reg_combine_min_max(&other_branch->regs[insn->src_reg],
2742 &other_branch->regs[insn->dst_reg],
2743 &regs[insn->src_reg],
2744 &regs[insn->dst_reg], opcode);
2745 }
2746 } else if (dst_reg->type == SCALAR_VALUE) {
48461135
JB
2747 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2748 dst_reg, insn->imm, opcode);
2749 }
2750
58e2af8b 2751 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
17a52670 2752 if (BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac
AS
2753 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
2754 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
57a09bf0
TG
2755 /* Mark all identical map registers in each branch as either
2756 * safe or unknown depending R == 0 or R != 0 conditional.
2757 */
f1174f77
EC
2758 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
2759 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
969bf05e
AS
2760 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
2761 dst_reg->type == PTR_TO_PACKET &&
2762 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
2d2be8ca
DB
2763 find_good_pkt_pointers(this_branch, dst_reg);
2764 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
2765 dst_reg->type == PTR_TO_PACKET_END &&
2766 regs[insn->src_reg].type == PTR_TO_PACKET) {
2767 find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
1be7f75d
AS
2768 } else if (is_pointer_value(env, insn->dst_reg)) {
2769 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
2770 return -EACCES;
17a52670
AS
2771 }
2772 if (log_level)
2d2be8ca 2773 print_verifier_state(this_branch);
17a52670
AS
2774 return 0;
2775}
2776
0246e64d
AS
2777/* return the map pointer stored inside BPF_LD_IMM64 instruction */
2778static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
2779{
2780 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
2781
2782 return (struct bpf_map *) (unsigned long) imm64;
2783}
2784
17a52670 2785/* verify BPF_LD_IMM64 instruction */
58e2af8b 2786static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 2787{
58e2af8b 2788 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
2789 int err;
2790
2791 if (BPF_SIZE(insn->code) != BPF_DW) {
2792 verbose("invalid BPF_LD_IMM insn\n");
2793 return -EINVAL;
2794 }
2795 if (insn->off != 0) {
2796 verbose("BPF_LD_IMM64 uses reserved fields\n");
2797 return -EINVAL;
2798 }
2799
2800 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
2801 if (err)
2802 return err;
2803
6b173873 2804 if (insn->src_reg == 0) {
6b173873
JK
2805 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
2806
f1174f77 2807 regs[insn->dst_reg].type = SCALAR_VALUE;
b03c9f9f 2808 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 2809 return 0;
6b173873 2810 }
17a52670
AS
2811
2812 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
2813 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
2814
2815 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
2816 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
2817 return 0;
2818}
2819
96be4325
DB
2820static bool may_access_skb(enum bpf_prog_type type)
2821{
2822 switch (type) {
2823 case BPF_PROG_TYPE_SOCKET_FILTER:
2824 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 2825 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
2826 return true;
2827 default:
2828 return false;
2829 }
2830}
2831
ddd872bc
AS
2832/* verify safety of LD_ABS|LD_IND instructions:
2833 * - they can only appear in the programs where ctx == skb
2834 * - since they are wrappers of function calls, they scratch R1-R5 registers,
2835 * preserve R6-R9, and store return value into R0
2836 *
2837 * Implicit input:
2838 * ctx == skb == R6 == CTX
2839 *
2840 * Explicit input:
2841 * SRC == any register
2842 * IMM == 32-bit immediate
2843 *
2844 * Output:
2845 * R0 - 8/16/32-bit skb data converted to cpu endianness
2846 */
58e2af8b 2847static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 2848{
58e2af8b 2849 struct bpf_reg_state *regs = env->cur_state.regs;
ddd872bc 2850 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
2851 int i, err;
2852
24701ece 2853 if (!may_access_skb(env->prog->type)) {
1a0dc1ac 2854 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
2855 return -EINVAL;
2856 }
2857
2858 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 2859 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 2860 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
1a0dc1ac 2861 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
2862 return -EINVAL;
2863 }
2864
2865 /* check whether implicit source operand (register R6) is readable */
2866 err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
2867 if (err)
2868 return err;
2869
2870 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
2871 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
2872 return -EINVAL;
2873 }
2874
2875 if (mode == BPF_IND) {
2876 /* check explicit source operand */
2877 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2878 if (err)
2879 return err;
2880 }
2881
2882 /* reset caller saved regs to unreadable */
a9789ef9
DB
2883 for (i = 0; i < CALLER_SAVED_REGS; i++)
2884 mark_reg_not_init(regs, caller_saved[i]);
ddd872bc
AS
2885
2886 /* mark destination R0 register as readable, since it contains
2887 * the value fetched from the packet
2888 */
f1174f77 2889 mark_reg_unknown(regs, BPF_REG_0);
ddd872bc
AS
2890 return 0;
2891}
2892
475fb78f
AS
2893/* non-recursive DFS pseudo code
2894 * 1 procedure DFS-iterative(G,v):
2895 * 2 label v as discovered
2896 * 3 let S be a stack
2897 * 4 S.push(v)
2898 * 5 while S is not empty
2899 * 6 t <- S.pop()
2900 * 7 if t is what we're looking for:
2901 * 8 return t
2902 * 9 for all edges e in G.adjacentEdges(t) do
2903 * 10 if edge e is already labelled
2904 * 11 continue with the next edge
2905 * 12 w <- G.adjacentVertex(t,e)
2906 * 13 if vertex w is not discovered and not explored
2907 * 14 label e as tree-edge
2908 * 15 label w as discovered
2909 * 16 S.push(w)
2910 * 17 continue at 5
2911 * 18 else if vertex w is discovered
2912 * 19 label e as back-edge
2913 * 20 else
2914 * 21 // vertex w is explored
2915 * 22 label e as forward- or cross-edge
2916 * 23 label t as explored
2917 * 24 S.pop()
2918 *
2919 * convention:
2920 * 0x10 - discovered
2921 * 0x11 - discovered and fall-through edge labelled
2922 * 0x12 - discovered and fall-through and branch edges labelled
2923 * 0x20 - explored
2924 */
2925
2926enum {
2927 DISCOVERED = 0x10,
2928 EXPLORED = 0x20,
2929 FALLTHROUGH = 1,
2930 BRANCH = 2,
2931};
2932
58e2af8b 2933#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
f1bca824 2934
475fb78f
AS
2935static int *insn_stack; /* stack of insns to process */
2936static int cur_stack; /* current stack index */
2937static int *insn_state;
2938
2939/* t, w, e - match pseudo-code above:
2940 * t - index of current instruction
2941 * w - next instruction
2942 * e - edge
2943 */
58e2af8b 2944static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
475fb78f
AS
2945{
2946 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
2947 return 0;
2948
2949 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
2950 return 0;
2951
2952 if (w < 0 || w >= env->prog->len) {
2953 verbose("jump out of range from insn %d to %d\n", t, w);
2954 return -EINVAL;
2955 }
2956
f1bca824
AS
2957 if (e == BRANCH)
2958 /* mark branch target for state pruning */
2959 env->explored_states[w] = STATE_LIST_MARK;
2960
475fb78f
AS
2961 if (insn_state[w] == 0) {
2962 /* tree-edge */
2963 insn_state[t] = DISCOVERED | e;
2964 insn_state[w] = DISCOVERED;
2965 if (cur_stack >= env->prog->len)
2966 return -E2BIG;
2967 insn_stack[cur_stack++] = w;
2968 return 1;
2969 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2970 verbose("back-edge from insn %d to %d\n", t, w);
2971 return -EINVAL;
2972 } else if (insn_state[w] == EXPLORED) {
2973 /* forward- or cross-edge */
2974 insn_state[t] = DISCOVERED | e;
2975 } else {
2976 verbose("insn state internal bug\n");
2977 return -EFAULT;
2978 }
2979 return 0;
2980}
2981
2982/* non-recursive depth-first-search to detect loops in BPF program
2983 * loop == back-edge in directed graph
2984 */
58e2af8b 2985static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
2986{
2987 struct bpf_insn *insns = env->prog->insnsi;
2988 int insn_cnt = env->prog->len;
2989 int ret = 0;
2990 int i, t;
2991
2992 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2993 if (!insn_state)
2994 return -ENOMEM;
2995
2996 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2997 if (!insn_stack) {
2998 kfree(insn_state);
2999 return -ENOMEM;
3000 }
3001
3002 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
3003 insn_stack[0] = 0; /* 0 is the first instruction */
3004 cur_stack = 1;
3005
3006peek_stack:
3007 if (cur_stack == 0)
3008 goto check_state;
3009 t = insn_stack[cur_stack - 1];
3010
3011 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
3012 u8 opcode = BPF_OP(insns[t].code);
3013
3014 if (opcode == BPF_EXIT) {
3015 goto mark_explored;
3016 } else if (opcode == BPF_CALL) {
3017 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3018 if (ret == 1)
3019 goto peek_stack;
3020 else if (ret < 0)
3021 goto err_free;
07016151
DB
3022 if (t + 1 < insn_cnt)
3023 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
3024 } else if (opcode == BPF_JA) {
3025 if (BPF_SRC(insns[t].code) != BPF_K) {
3026 ret = -EINVAL;
3027 goto err_free;
3028 }
3029 /* unconditional jump with single edge */
3030 ret = push_insn(t, t + insns[t].off + 1,
3031 FALLTHROUGH, env);
3032 if (ret == 1)
3033 goto peek_stack;
3034 else if (ret < 0)
3035 goto err_free;
f1bca824
AS
3036 /* tell verifier to check for equivalent states
3037 * after every call and jump
3038 */
c3de6317
AS
3039 if (t + 1 < insn_cnt)
3040 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
3041 } else {
3042 /* conditional jump with two edges */
3c2ce60b 3043 env->explored_states[t] = STATE_LIST_MARK;
475fb78f
AS
3044 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3045 if (ret == 1)
3046 goto peek_stack;
3047 else if (ret < 0)
3048 goto err_free;
3049
3050 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
3051 if (ret == 1)
3052 goto peek_stack;
3053 else if (ret < 0)
3054 goto err_free;
3055 }
3056 } else {
3057 /* all other non-branch instructions with single
3058 * fall-through edge
3059 */
3060 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3061 if (ret == 1)
3062 goto peek_stack;
3063 else if (ret < 0)
3064 goto err_free;
3065 }
3066
3067mark_explored:
3068 insn_state[t] = EXPLORED;
3069 if (cur_stack-- <= 0) {
3070 verbose("pop stack internal bug\n");
3071 ret = -EFAULT;
3072 goto err_free;
3073 }
3074 goto peek_stack;
3075
3076check_state:
3077 for (i = 0; i < insn_cnt; i++) {
3078 if (insn_state[i] != EXPLORED) {
3079 verbose("unreachable insn %d\n", i);
3080 ret = -EINVAL;
3081 goto err_free;
3082 }
3083 }
3084 ret = 0; /* cfg looks good */
3085
3086err_free:
3087 kfree(insn_state);
3088 kfree(insn_stack);
3089 return ret;
3090}
3091
f1174f77
EC
3092/* check %cur's range satisfies %old's */
3093static bool range_within(struct bpf_reg_state *old,
3094 struct bpf_reg_state *cur)
3095{
b03c9f9f
EC
3096 return old->umin_value <= cur->umin_value &&
3097 old->umax_value >= cur->umax_value &&
3098 old->smin_value <= cur->smin_value &&
3099 old->smax_value >= cur->smax_value;
f1174f77
EC
3100}
3101
3102/* Maximum number of register states that can exist at once */
3103#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
3104struct idpair {
3105 u32 old;
3106 u32 cur;
3107};
3108
3109/* If in the old state two registers had the same id, then they need to have
3110 * the same id in the new state as well. But that id could be different from
3111 * the old state, so we need to track the mapping from old to new ids.
3112 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
3113 * regs with old id 5 must also have new id 9 for the new state to be safe. But
3114 * regs with a different old id could still have new id 9, we don't care about
3115 * that.
3116 * So we look through our idmap to see if this old id has been seen before. If
3117 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 3118 */
f1174f77 3119static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 3120{
f1174f77 3121 unsigned int i;
969bf05e 3122
f1174f77
EC
3123 for (i = 0; i < ID_MAP_SIZE; i++) {
3124 if (!idmap[i].old) {
3125 /* Reached an empty slot; haven't seen this id before */
3126 idmap[i].old = old_id;
3127 idmap[i].cur = cur_id;
3128 return true;
3129 }
3130 if (idmap[i].old == old_id)
3131 return idmap[i].cur == cur_id;
3132 }
3133 /* We ran out of idmap slots, which should be impossible */
3134 WARN_ON_ONCE(1);
3135 return false;
3136}
3137
3138/* Returns true if (rold safe implies rcur safe) */
3139static bool regsafe(struct bpf_reg_state *rold,
3140 struct bpf_reg_state *rcur,
3141 bool varlen_map_access, struct idpair *idmap)
3142{
3143 if (memcmp(rold, rcur, sizeof(*rold)) == 0)
969bf05e
AS
3144 return true;
3145
f1174f77
EC
3146 if (rold->type == NOT_INIT)
3147 /* explored state can't have used this */
969bf05e 3148 return true;
f1174f77
EC
3149 if (rcur->type == NOT_INIT)
3150 return false;
3151 switch (rold->type) {
3152 case SCALAR_VALUE:
3153 if (rcur->type == SCALAR_VALUE) {
3154 /* new val must satisfy old val knowledge */
3155 return range_within(rold, rcur) &&
3156 tnum_in(rold->var_off, rcur->var_off);
3157 } else {
3158 /* if we knew anything about the old value, we're not
3159 * equal, because we can't know anything about the
3160 * scalar value of the pointer in the new value.
3161 */
b03c9f9f
EC
3162 return rold->umin_value == 0 &&
3163 rold->umax_value == U64_MAX &&
3164 rold->smin_value == S64_MIN &&
3165 rold->smax_value == S64_MAX &&
f1174f77
EC
3166 tnum_is_unknown(rold->var_off);
3167 }
3168 case PTR_TO_MAP_VALUE:
3169 if (varlen_map_access) {
3170 /* If the new min/max/var_off satisfy the old ones and
3171 * everything else matches, we are OK.
3172 * We don't care about the 'id' value, because nothing
3173 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
3174 */
3175 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
3176 range_within(rold, rcur) &&
3177 tnum_in(rold->var_off, rcur->var_off);
3178 } else {
3179 /* If the ranges/var_off were not the same, but
3180 * everything else was and we didn't do a variable
3181 * access into a map then we are a-ok.
3182 */
3183 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0;
3184 }
3185 case PTR_TO_MAP_VALUE_OR_NULL:
3186 /* a PTR_TO_MAP_VALUE could be safe to use as a
3187 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
3188 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
3189 * checked, doing so could have affected others with the same
3190 * id, and we can't check for that because we lost the id when
3191 * we converted to a PTR_TO_MAP_VALUE.
3192 */
3193 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
3194 return false;
3195 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
3196 return false;
3197 /* Check our ids match any regs they're supposed to */
3198 return check_ids(rold->id, rcur->id, idmap);
3199 case PTR_TO_PACKET:
3200 if (rcur->type != PTR_TO_PACKET)
3201 return false;
3202 /* We must have at least as much range as the old ptr
3203 * did, so that any accesses which were safe before are
3204 * still safe. This is true even if old range < old off,
3205 * since someone could have accessed through (ptr - k), or
3206 * even done ptr -= k in a register, to get a safe access.
3207 */
3208 if (rold->range > rcur->range)
3209 return false;
3210 /* If the offsets don't match, we can't trust our alignment;
3211 * nor can we be sure that we won't fall out of range.
3212 */
3213 if (rold->off != rcur->off)
3214 return false;
3215 /* id relations must be preserved */
3216 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
3217 return false;
3218 /* new val must satisfy old val knowledge */
3219 return range_within(rold, rcur) &&
3220 tnum_in(rold->var_off, rcur->var_off);
3221 case PTR_TO_CTX:
3222 case CONST_PTR_TO_MAP:
3223 case PTR_TO_STACK:
3224 case PTR_TO_PACKET_END:
3225 /* Only valid matches are exact, which memcmp() above
3226 * would have accepted
3227 */
3228 default:
3229 /* Don't know what's going on, just say it's not safe */
3230 return false;
3231 }
969bf05e 3232
f1174f77
EC
3233 /* Shouldn't get here; if we do, say it's not safe */
3234 WARN_ON_ONCE(1);
969bf05e
AS
3235 return false;
3236}
3237
f1bca824
AS
3238/* compare two verifier states
3239 *
3240 * all states stored in state_list are known to be valid, since
3241 * verifier reached 'bpf_exit' instruction through them
3242 *
3243 * this function is called when verifier exploring different branches of
3244 * execution popped from the state stack. If it sees an old state that has
3245 * more strict register state and more strict stack state then this execution
3246 * branch doesn't need to be explored further, since verifier already
3247 * concluded that more strict state leads to valid finish.
3248 *
3249 * Therefore two states are equivalent if register state is more conservative
3250 * and explored stack state is more conservative than the current one.
3251 * Example:
3252 * explored current
3253 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
3254 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
3255 *
3256 * In other words if current stack state (one being explored) has more
3257 * valid slots than old one that already passed validation, it means
3258 * the verifier can stop exploring and conclude that current state is valid too
3259 *
3260 * Similarly with registers. If explored state has register type as invalid
3261 * whereas register type in current state is meaningful, it means that
3262 * the current state will reach 'bpf_exit' instruction safely
3263 */
48461135
JB
3264static bool states_equal(struct bpf_verifier_env *env,
3265 struct bpf_verifier_state *old,
58e2af8b 3266 struct bpf_verifier_state *cur)
f1bca824 3267{
e2d2afe1 3268 bool varlen_map_access = env->varlen_map_value_access;
f1174f77
EC
3269 struct idpair *idmap;
3270 bool ret = false;
f1bca824
AS
3271 int i;
3272
f1174f77
EC
3273 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
3274 /* If we failed to allocate the idmap, just say it's not safe */
3275 if (!idmap)
1a0dc1ac 3276 return false;
f1174f77
EC
3277
3278 for (i = 0; i < MAX_BPF_REG; i++) {
3279 if (!regsafe(&old->regs[i], &cur->regs[i], varlen_map_access,
3280 idmap))
3281 goto out_free;
f1bca824
AS
3282 }
3283
3284 for (i = 0; i < MAX_BPF_STACK; i++) {
9c399760
AS
3285 if (old->stack_slot_type[i] == STACK_INVALID)
3286 continue;
3287 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
3288 /* Ex: old explored (safe) state has STACK_SPILL in
3289 * this stack slot, but current has has STACK_MISC ->
3290 * this verifier states are not equivalent,
3291 * return false to continue verification of this path
3292 */
f1174f77 3293 goto out_free;
9c399760
AS
3294 if (i % BPF_REG_SIZE)
3295 continue;
d25da6ca
DB
3296 if (old->stack_slot_type[i] != STACK_SPILL)
3297 continue;
f1174f77
EC
3298 if (!regsafe(&old->spilled_regs[i / BPF_REG_SIZE],
3299 &cur->spilled_regs[i / BPF_REG_SIZE],
3300 varlen_map_access, idmap))
3301 /* when explored and current stack slot are both storing
3302 * spilled registers, check that stored pointers types
9c399760
AS
3303 * are the same as well.
3304 * Ex: explored safe path could have stored
f1174f77 3305 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9c399760 3306 * but current path has stored:
f1174f77 3307 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9c399760
AS
3308 * such verifier states are not equivalent.
3309 * return false to continue verification of this path
3310 */
f1174f77 3311 goto out_free;
9c399760
AS
3312 else
3313 continue;
f1bca824 3314 }
f1174f77
EC
3315 ret = true;
3316out_free:
3317 kfree(idmap);
3318 return ret;
f1bca824
AS
3319}
3320
58e2af8b 3321static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 3322{
58e2af8b
JK
3323 struct bpf_verifier_state_list *new_sl;
3324 struct bpf_verifier_state_list *sl;
f1bca824
AS
3325
3326 sl = env->explored_states[insn_idx];
3327 if (!sl)
3328 /* this 'insn_idx' instruction wasn't marked, so we will not
3329 * be doing state search here
3330 */
3331 return 0;
3332
3333 while (sl != STATE_LIST_MARK) {
48461135 3334 if (states_equal(env, &sl->state, &env->cur_state))
f1bca824
AS
3335 /* reached equivalent register/stack state,
3336 * prune the search
3337 */
3338 return 1;
3339 sl = sl->next;
3340 }
3341
3342 /* there were no equivalent states, remember current one.
3343 * technically the current state is not proven to be safe yet,
3344 * but it will either reach bpf_exit (which means it's safe) or
3345 * it will be rejected. Since there are no loops, we won't be
3346 * seeing this 'insn_idx' instruction again on the way to bpf_exit
3347 */
58e2af8b 3348 new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
f1bca824
AS
3349 if (!new_sl)
3350 return -ENOMEM;
3351
3352 /* add new state to the head of linked list */
3353 memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
3354 new_sl->next = env->explored_states[insn_idx];
3355 env->explored_states[insn_idx] = new_sl;
3356 return 0;
3357}
3358
13a27dfc
JK
3359static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
3360 int insn_idx, int prev_insn_idx)
3361{
3362 if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
3363 return 0;
3364
3365 return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
3366}
3367
58e2af8b 3368static int do_check(struct bpf_verifier_env *env)
17a52670 3369{
58e2af8b 3370 struct bpf_verifier_state *state = &env->cur_state;
17a52670 3371 struct bpf_insn *insns = env->prog->insnsi;
58e2af8b 3372 struct bpf_reg_state *regs = state->regs;
17a52670
AS
3373 int insn_cnt = env->prog->len;
3374 int insn_idx, prev_insn_idx = 0;
3375 int insn_processed = 0;
3376 bool do_print_state = false;
3377
3378 init_reg_state(regs);
3379 insn_idx = 0;
48461135 3380 env->varlen_map_value_access = false;
17a52670
AS
3381 for (;;) {
3382 struct bpf_insn *insn;
3383 u8 class;
3384 int err;
3385
3386 if (insn_idx >= insn_cnt) {
3387 verbose("invalid insn idx %d insn_cnt %d\n",
3388 insn_idx, insn_cnt);
3389 return -EFAULT;
3390 }
3391
3392 insn = &insns[insn_idx];
3393 class = BPF_CLASS(insn->code);
3394
07016151 3395 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
bc1750f3 3396 verbose("BPF program is too large. Processed %d insn\n",
17a52670
AS
3397 insn_processed);
3398 return -E2BIG;
3399 }
3400
f1bca824
AS
3401 err = is_state_visited(env, insn_idx);
3402 if (err < 0)
3403 return err;
3404 if (err == 1) {
3405 /* found equivalent state, can prune the search */
3406 if (log_level) {
3407 if (do_print_state)
3408 verbose("\nfrom %d to %d: safe\n",
3409 prev_insn_idx, insn_idx);
3410 else
3411 verbose("%d: safe\n", insn_idx);
3412 }
3413 goto process_bpf_exit;
3414 }
3415
3c2ce60b
DB
3416 if (need_resched())
3417 cond_resched();
3418
c5fc9692
DM
3419 if (log_level > 1 || (log_level && do_print_state)) {
3420 if (log_level > 1)
3421 verbose("%d:", insn_idx);
3422 else
3423 verbose("\nfrom %d to %d:",
3424 prev_insn_idx, insn_idx);
1a0dc1ac 3425 print_verifier_state(&env->cur_state);
17a52670
AS
3426 do_print_state = false;
3427 }
3428
3429 if (log_level) {
3430 verbose("%d: ", insn_idx);
0d0e5769 3431 print_bpf_insn(env, insn);
17a52670
AS
3432 }
3433
13a27dfc
JK
3434 err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
3435 if (err)
3436 return err;
3437
17a52670 3438 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 3439 err = check_alu_op(env, insn);
17a52670
AS
3440 if (err)
3441 return err;
3442
3443 } else if (class == BPF_LDX) {
3df126f3 3444 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
3445
3446 /* check for reserved fields is already done */
3447
17a52670
AS
3448 /* check src operand */
3449 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
3450 if (err)
3451 return err;
3452
3453 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
3454 if (err)
3455 return err;
3456
725f9dcd
AS
3457 src_reg_type = regs[insn->src_reg].type;
3458
17a52670
AS
3459 /* check that memory (src_reg + off) is readable,
3460 * the state of dst_reg will be updated by this func
3461 */
31fd8581 3462 err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
17a52670
AS
3463 BPF_SIZE(insn->code), BPF_READ,
3464 insn->dst_reg);
3465 if (err)
3466 return err;
3467
3df126f3
JK
3468 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
3469
3470 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
3471 /* saw a valid insn
3472 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 3473 * save type to validate intersecting paths
9bac3d6d 3474 */
3df126f3 3475 *prev_src_type = src_reg_type;
9bac3d6d 3476
3df126f3 3477 } else if (src_reg_type != *prev_src_type &&
9bac3d6d 3478 (src_reg_type == PTR_TO_CTX ||
3df126f3 3479 *prev_src_type == PTR_TO_CTX)) {
9bac3d6d
AS
3480 /* ABuser program is trying to use the same insn
3481 * dst_reg = *(u32*) (src_reg + off)
3482 * with different pointer types:
3483 * src_reg == ctx in one branch and
3484 * src_reg == stack|map in some other branch.
3485 * Reject it.
3486 */
3487 verbose("same insn cannot be used with different pointers\n");
3488 return -EINVAL;
3489 }
3490
17a52670 3491 } else if (class == BPF_STX) {
3df126f3 3492 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 3493
17a52670 3494 if (BPF_MODE(insn->code) == BPF_XADD) {
31fd8581 3495 err = check_xadd(env, insn_idx, insn);
17a52670
AS
3496 if (err)
3497 return err;
3498 insn_idx++;
3499 continue;
3500 }
3501
17a52670
AS
3502 /* check src1 operand */
3503 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
3504 if (err)
3505 return err;
3506 /* check src2 operand */
3507 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
3508 if (err)
3509 return err;
3510
d691f9e8
AS
3511 dst_reg_type = regs[insn->dst_reg].type;
3512
17a52670 3513 /* check that memory (dst_reg + off) is writeable */
31fd8581 3514 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
17a52670
AS
3515 BPF_SIZE(insn->code), BPF_WRITE,
3516 insn->src_reg);
3517 if (err)
3518 return err;
3519
3df126f3
JK
3520 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
3521
3522 if (*prev_dst_type == NOT_INIT) {
3523 *prev_dst_type = dst_reg_type;
3524 } else if (dst_reg_type != *prev_dst_type &&
d691f9e8 3525 (dst_reg_type == PTR_TO_CTX ||
3df126f3 3526 *prev_dst_type == PTR_TO_CTX)) {
d691f9e8
AS
3527 verbose("same insn cannot be used with different pointers\n");
3528 return -EINVAL;
3529 }
3530
17a52670
AS
3531 } else if (class == BPF_ST) {
3532 if (BPF_MODE(insn->code) != BPF_MEM ||
3533 insn->src_reg != BPF_REG_0) {
3534 verbose("BPF_ST uses reserved fields\n");
3535 return -EINVAL;
3536 }
3537 /* check src operand */
3538 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
3539 if (err)
3540 return err;
3541
3542 /* check that memory (dst_reg + off) is writeable */
31fd8581 3543 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
17a52670
AS
3544 BPF_SIZE(insn->code), BPF_WRITE,
3545 -1);
3546 if (err)
3547 return err;
3548
3549 } else if (class == BPF_JMP) {
3550 u8 opcode = BPF_OP(insn->code);
3551
3552 if (opcode == BPF_CALL) {
3553 if (BPF_SRC(insn->code) != BPF_K ||
3554 insn->off != 0 ||
3555 insn->src_reg != BPF_REG_0 ||
3556 insn->dst_reg != BPF_REG_0) {
3557 verbose("BPF_CALL uses reserved fields\n");
3558 return -EINVAL;
3559 }
3560
81ed18ab 3561 err = check_call(env, insn->imm, insn_idx);
17a52670
AS
3562 if (err)
3563 return err;
3564
3565 } else if (opcode == BPF_JA) {
3566 if (BPF_SRC(insn->code) != BPF_K ||
3567 insn->imm != 0 ||
3568 insn->src_reg != BPF_REG_0 ||
3569 insn->dst_reg != BPF_REG_0) {
3570 verbose("BPF_JA uses reserved fields\n");
3571 return -EINVAL;
3572 }
3573
3574 insn_idx += insn->off + 1;
3575 continue;
3576
3577 } else if (opcode == BPF_EXIT) {
3578 if (BPF_SRC(insn->code) != BPF_K ||
3579 insn->imm != 0 ||
3580 insn->src_reg != BPF_REG_0 ||
3581 insn->dst_reg != BPF_REG_0) {
3582 verbose("BPF_EXIT uses reserved fields\n");
3583 return -EINVAL;
3584 }
3585
3586 /* eBPF calling convetion is such that R0 is used
3587 * to return the value from eBPF program.
3588 * Make sure that it's readable at this time
3589 * of bpf_exit, which means that program wrote
3590 * something into it earlier
3591 */
3592 err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
3593 if (err)
3594 return err;
3595
1be7f75d
AS
3596 if (is_pointer_value(env, BPF_REG_0)) {
3597 verbose("R0 leaks addr as return value\n");
3598 return -EACCES;
3599 }
3600
f1bca824 3601process_bpf_exit:
17a52670
AS
3602 insn_idx = pop_stack(env, &prev_insn_idx);
3603 if (insn_idx < 0) {
3604 break;
3605 } else {
3606 do_print_state = true;
3607 continue;
3608 }
3609 } else {
3610 err = check_cond_jmp_op(env, insn, &insn_idx);
3611 if (err)
3612 return err;
3613 }
3614 } else if (class == BPF_LD) {
3615 u8 mode = BPF_MODE(insn->code);
3616
3617 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
3618 err = check_ld_abs(env, insn);
3619 if (err)
3620 return err;
3621
17a52670
AS
3622 } else if (mode == BPF_IMM) {
3623 err = check_ld_imm(env, insn);
3624 if (err)
3625 return err;
3626
3627 insn_idx++;
3628 } else {
3629 verbose("invalid BPF_LD mode\n");
3630 return -EINVAL;
3631 }
3632 } else {
3633 verbose("unknown insn class %d\n", class);
3634 return -EINVAL;
3635 }
3636
3637 insn_idx++;
3638 }
3639
8726679a
AS
3640 verbose("processed %d insns, stack depth %d\n",
3641 insn_processed, env->prog->aux->stack_depth);
17a52670
AS
3642 return 0;
3643}
3644
56f668df
MKL
3645static int check_map_prealloc(struct bpf_map *map)
3646{
3647 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
3648 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
3649 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
3650 !(map->map_flags & BPF_F_NO_PREALLOC);
3651}
3652
fdc15d38
AS
3653static int check_map_prog_compatibility(struct bpf_map *map,
3654 struct bpf_prog *prog)
3655
3656{
56f668df
MKL
3657 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
3658 * preallocated hash maps, since doing memory allocation
3659 * in overflow_handler can crash depending on where nmi got
3660 * triggered.
3661 */
3662 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
3663 if (!check_map_prealloc(map)) {
3664 verbose("perf_event programs can only use preallocated hash map\n");
3665 return -EINVAL;
3666 }
3667 if (map->inner_map_meta &&
3668 !check_map_prealloc(map->inner_map_meta)) {
3669 verbose("perf_event programs can only use preallocated inner hash map\n");
3670 return -EINVAL;
3671 }
fdc15d38
AS
3672 }
3673 return 0;
3674}
3675
0246e64d
AS
3676/* look for pseudo eBPF instructions that access map FDs and
3677 * replace them with actual map pointers
3678 */
58e2af8b 3679static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
3680{
3681 struct bpf_insn *insn = env->prog->insnsi;
3682 int insn_cnt = env->prog->len;
fdc15d38 3683 int i, j, err;
0246e64d 3684
f1f7714e 3685 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
3686 if (err)
3687 return err;
3688
0246e64d 3689 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 3690 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 3691 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
9bac3d6d
AS
3692 verbose("BPF_LDX uses reserved fields\n");
3693 return -EINVAL;
3694 }
3695
d691f9e8
AS
3696 if (BPF_CLASS(insn->code) == BPF_STX &&
3697 ((BPF_MODE(insn->code) != BPF_MEM &&
3698 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
3699 verbose("BPF_STX uses reserved fields\n");
3700 return -EINVAL;
3701 }
3702
0246e64d
AS
3703 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
3704 struct bpf_map *map;
3705 struct fd f;
3706
3707 if (i == insn_cnt - 1 || insn[1].code != 0 ||
3708 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
3709 insn[1].off != 0) {
3710 verbose("invalid bpf_ld_imm64 insn\n");
3711 return -EINVAL;
3712 }
3713
3714 if (insn->src_reg == 0)
3715 /* valid generic load 64-bit imm */
3716 goto next_insn;
3717
3718 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
3719 verbose("unrecognized bpf_ld_imm64 insn\n");
3720 return -EINVAL;
3721 }
3722
3723 f = fdget(insn->imm);
c2101297 3724 map = __bpf_map_get(f);
0246e64d
AS
3725 if (IS_ERR(map)) {
3726 verbose("fd %d is not pointing to valid bpf_map\n",
3727 insn->imm);
0246e64d
AS
3728 return PTR_ERR(map);
3729 }
3730
fdc15d38
AS
3731 err = check_map_prog_compatibility(map, env->prog);
3732 if (err) {
3733 fdput(f);
3734 return err;
3735 }
3736
0246e64d
AS
3737 /* store map pointer inside BPF_LD_IMM64 instruction */
3738 insn[0].imm = (u32) (unsigned long) map;
3739 insn[1].imm = ((u64) (unsigned long) map) >> 32;
3740
3741 /* check whether we recorded this map already */
3742 for (j = 0; j < env->used_map_cnt; j++)
3743 if (env->used_maps[j] == map) {
3744 fdput(f);
3745 goto next_insn;
3746 }
3747
3748 if (env->used_map_cnt >= MAX_USED_MAPS) {
3749 fdput(f);
3750 return -E2BIG;
3751 }
3752
0246e64d
AS
3753 /* hold the map. If the program is rejected by verifier,
3754 * the map will be released by release_maps() or it
3755 * will be used by the valid program until it's unloaded
3756 * and all maps are released in free_bpf_prog_info()
3757 */
92117d84
AS
3758 map = bpf_map_inc(map, false);
3759 if (IS_ERR(map)) {
3760 fdput(f);
3761 return PTR_ERR(map);
3762 }
3763 env->used_maps[env->used_map_cnt++] = map;
3764
0246e64d
AS
3765 fdput(f);
3766next_insn:
3767 insn++;
3768 i++;
3769 }
3770 }
3771
3772 /* now all pseudo BPF_LD_IMM64 instructions load valid
3773 * 'struct bpf_map *' into a register instead of user map_fd.
3774 * These pointers will be used later by verifier to validate map access.
3775 */
3776 return 0;
3777}
3778
3779/* drop refcnt of maps used by the rejected program */
58e2af8b 3780static void release_maps(struct bpf_verifier_env *env)
0246e64d
AS
3781{
3782 int i;
3783
3784 for (i = 0; i < env->used_map_cnt; i++)
3785 bpf_map_put(env->used_maps[i]);
3786}
3787
3788/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 3789static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
3790{
3791 struct bpf_insn *insn = env->prog->insnsi;
3792 int insn_cnt = env->prog->len;
3793 int i;
3794
3795 for (i = 0; i < insn_cnt; i++, insn++)
3796 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
3797 insn->src_reg = 0;
3798}
3799
8041902d
AS
3800/* single env->prog->insni[off] instruction was replaced with the range
3801 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
3802 * [0, off) and [off, end) to new locations, so the patched range stays zero
3803 */
3804static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
3805 u32 off, u32 cnt)
3806{
3807 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
3808
3809 if (cnt == 1)
3810 return 0;
3811 new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
3812 if (!new_data)
3813 return -ENOMEM;
3814 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
3815 memcpy(new_data + off + cnt - 1, old_data + off,
3816 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
3817 env->insn_aux_data = new_data;
3818 vfree(old_data);
3819 return 0;
3820}
3821
3822static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
3823 const struct bpf_insn *patch, u32 len)
3824{
3825 struct bpf_prog *new_prog;
3826
3827 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
3828 if (!new_prog)
3829 return NULL;
3830 if (adjust_insn_aux_data(env, new_prog->len, off, len))
3831 return NULL;
3832 return new_prog;
3833}
3834
9bac3d6d
AS
3835/* convert load instructions that access fields of 'struct __sk_buff'
3836 * into sequence of instructions that access fields of 'struct sk_buff'
3837 */
58e2af8b 3838static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 3839{
36bbef52 3840 const struct bpf_verifier_ops *ops = env->prog->aux->ops;
f96da094 3841 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 3842 const int insn_cnt = env->prog->len;
36bbef52 3843 struct bpf_insn insn_buf[16], *insn;
9bac3d6d 3844 struct bpf_prog *new_prog;
d691f9e8 3845 enum bpf_access_type type;
f96da094
DB
3846 bool is_narrower_load;
3847 u32 target_size;
9bac3d6d 3848
36bbef52
DB
3849 if (ops->gen_prologue) {
3850 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
3851 env->prog);
3852 if (cnt >= ARRAY_SIZE(insn_buf)) {
3853 verbose("bpf verifier is misconfigured\n");
3854 return -EINVAL;
3855 } else if (cnt) {
8041902d 3856 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
3857 if (!new_prog)
3858 return -ENOMEM;
8041902d 3859
36bbef52 3860 env->prog = new_prog;
3df126f3 3861 delta += cnt - 1;
36bbef52
DB
3862 }
3863 }
3864
3865 if (!ops->convert_ctx_access)
9bac3d6d
AS
3866 return 0;
3867
3df126f3 3868 insn = env->prog->insnsi + delta;
36bbef52 3869
9bac3d6d 3870 for (i = 0; i < insn_cnt; i++, insn++) {
62c7989b
DB
3871 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
3872 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
3873 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 3874 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 3875 type = BPF_READ;
62c7989b
DB
3876 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
3877 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
3878 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 3879 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
3880 type = BPF_WRITE;
3881 else
9bac3d6d
AS
3882 continue;
3883
8041902d 3884 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
9bac3d6d 3885 continue;
9bac3d6d 3886
31fd8581 3887 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 3888 size = BPF_LDST_BYTES(insn);
31fd8581
YS
3889
3890 /* If the read access is a narrower load of the field,
3891 * convert to a 4/8-byte load, to minimum program type specific
3892 * convert_ctx_access changes. If conversion is successful,
3893 * we will apply proper mask to the result.
3894 */
f96da094 3895 is_narrower_load = size < ctx_field_size;
31fd8581 3896 if (is_narrower_load) {
f96da094
DB
3897 u32 off = insn->off;
3898 u8 size_code;
3899
3900 if (type == BPF_WRITE) {
3901 verbose("bpf verifier narrow ctx access misconfigured\n");
3902 return -EINVAL;
3903 }
31fd8581 3904
f96da094 3905 size_code = BPF_H;
31fd8581
YS
3906 if (ctx_field_size == 4)
3907 size_code = BPF_W;
3908 else if (ctx_field_size == 8)
3909 size_code = BPF_DW;
f96da094 3910
31fd8581
YS
3911 insn->off = off & ~(ctx_field_size - 1);
3912 insn->code = BPF_LDX | BPF_MEM | size_code;
3913 }
f96da094
DB
3914
3915 target_size = 0;
3916 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
3917 &target_size);
3918 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
3919 (ctx_field_size && !target_size)) {
9bac3d6d
AS
3920 verbose("bpf verifier is misconfigured\n");
3921 return -EINVAL;
3922 }
f96da094
DB
3923
3924 if (is_narrower_load && size < target_size) {
31fd8581
YS
3925 if (ctx_field_size <= 4)
3926 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 3927 (1 << size * 8) - 1);
31fd8581
YS
3928 else
3929 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
f96da094 3930 (1 << size * 8) - 1);
31fd8581 3931 }
9bac3d6d 3932
8041902d 3933 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
3934 if (!new_prog)
3935 return -ENOMEM;
3936
3df126f3 3937 delta += cnt - 1;
9bac3d6d
AS
3938
3939 /* keep walking new program and skip insns we just inserted */
3940 env->prog = new_prog;
3df126f3 3941 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
3942 }
3943
3944 return 0;
3945}
3946
79741b3b 3947/* fixup insn->imm field of bpf_call instructions
81ed18ab 3948 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
3949 *
3950 * this function is called after eBPF program passed verification
3951 */
79741b3b 3952static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 3953{
79741b3b
AS
3954 struct bpf_prog *prog = env->prog;
3955 struct bpf_insn *insn = prog->insnsi;
e245c5c6 3956 const struct bpf_func_proto *fn;
79741b3b 3957 const int insn_cnt = prog->len;
81ed18ab
AS
3958 struct bpf_insn insn_buf[16];
3959 struct bpf_prog *new_prog;
3960 struct bpf_map *map_ptr;
3961 int i, cnt, delta = 0;
e245c5c6 3962
79741b3b
AS
3963 for (i = 0; i < insn_cnt; i++, insn++) {
3964 if (insn->code != (BPF_JMP | BPF_CALL))
3965 continue;
e245c5c6 3966
79741b3b
AS
3967 if (insn->imm == BPF_FUNC_get_route_realm)
3968 prog->dst_needed = 1;
3969 if (insn->imm == BPF_FUNC_get_prandom_u32)
3970 bpf_user_rnd_init_once();
79741b3b 3971 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
3972 /* If we tail call into other programs, we
3973 * cannot make any assumptions since they can
3974 * be replaced dynamically during runtime in
3975 * the program array.
3976 */
3977 prog->cb_access = 1;
80a58d02 3978 env->prog->aux->stack_depth = MAX_BPF_STACK;
7b9f6da1 3979
79741b3b
AS
3980 /* mark bpf_tail_call as different opcode to avoid
3981 * conditional branch in the interpeter for every normal
3982 * call and to prevent accidental JITing by JIT compiler
3983 * that doesn't support bpf_tail_call yet
e245c5c6 3984 */
79741b3b 3985 insn->imm = 0;
71189fa9 3986 insn->code = BPF_JMP | BPF_TAIL_CALL;
79741b3b
AS
3987 continue;
3988 }
e245c5c6 3989
81ed18ab
AS
3990 if (ebpf_jit_enabled() && insn->imm == BPF_FUNC_map_lookup_elem) {
3991 map_ptr = env->insn_aux_data[i + delta].map_ptr;
fad73a1a
MKL
3992 if (map_ptr == BPF_MAP_PTR_POISON ||
3993 !map_ptr->ops->map_gen_lookup)
81ed18ab
AS
3994 goto patch_call_imm;
3995
3996 cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
3997 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
3998 verbose("bpf verifier is misconfigured\n");
3999 return -EINVAL;
4000 }
4001
4002 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
4003 cnt);
4004 if (!new_prog)
4005 return -ENOMEM;
4006
4007 delta += cnt - 1;
4008
4009 /* keep walking new program and skip insns we just inserted */
4010 env->prog = prog = new_prog;
4011 insn = new_prog->insnsi + i + delta;
4012 continue;
4013 }
4014
4015patch_call_imm:
79741b3b
AS
4016 fn = prog->aux->ops->get_func_proto(insn->imm);
4017 /* all functions that have prototype and verifier allowed
4018 * programs to call them, must be real in-kernel functions
4019 */
4020 if (!fn->func) {
4021 verbose("kernel subsystem misconfigured func %s#%d\n",
4022 func_id_name(insn->imm), insn->imm);
4023 return -EFAULT;
e245c5c6 4024 }
79741b3b 4025 insn->imm = fn->func - __bpf_call_base;
e245c5c6 4026 }
e245c5c6 4027
79741b3b
AS
4028 return 0;
4029}
e245c5c6 4030
58e2af8b 4031static void free_states(struct bpf_verifier_env *env)
f1bca824 4032{
58e2af8b 4033 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
4034 int i;
4035
4036 if (!env->explored_states)
4037 return;
4038
4039 for (i = 0; i < env->prog->len; i++) {
4040 sl = env->explored_states[i];
4041
4042 if (sl)
4043 while (sl != STATE_LIST_MARK) {
4044 sln = sl->next;
4045 kfree(sl);
4046 sl = sln;
4047 }
4048 }
4049
4050 kfree(env->explored_states);
4051}
4052
9bac3d6d 4053int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
51580e79 4054{
cbd35700 4055 char __user *log_ubuf = NULL;
58e2af8b 4056 struct bpf_verifier_env *env;
51580e79
AS
4057 int ret = -EINVAL;
4058
58e2af8b 4059 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
4060 * allocate/free it every time bpf_check() is called
4061 */
58e2af8b 4062 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
4063 if (!env)
4064 return -ENOMEM;
4065
3df126f3
JK
4066 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
4067 (*prog)->len);
4068 ret = -ENOMEM;
4069 if (!env->insn_aux_data)
4070 goto err_free_env;
9bac3d6d 4071 env->prog = *prog;
0246e64d 4072
cbd35700
AS
4073 /* grab the mutex to protect few globals used by verifier */
4074 mutex_lock(&bpf_verifier_lock);
4075
4076 if (attr->log_level || attr->log_buf || attr->log_size) {
4077 /* user requested verbose verifier output
4078 * and supplied buffer to store the verification trace
4079 */
4080 log_level = attr->log_level;
4081 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
4082 log_size = attr->log_size;
4083 log_len = 0;
4084
4085 ret = -EINVAL;
4086 /* log_* values have to be sane */
4087 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
4088 log_level == 0 || log_ubuf == NULL)
3df126f3 4089 goto err_unlock;
cbd35700
AS
4090
4091 ret = -ENOMEM;
4092 log_buf = vmalloc(log_size);
4093 if (!log_buf)
3df126f3 4094 goto err_unlock;
cbd35700
AS
4095 } else {
4096 log_level = 0;
4097 }
1ad2f583
DB
4098
4099 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
4100 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 4101 env->strict_alignment = true;
cbd35700 4102
0246e64d
AS
4103 ret = replace_map_fd_with_map_ptr(env);
4104 if (ret < 0)
4105 goto skip_full_check;
4106
9bac3d6d 4107 env->explored_states = kcalloc(env->prog->len,
58e2af8b 4108 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
4109 GFP_USER);
4110 ret = -ENOMEM;
4111 if (!env->explored_states)
4112 goto skip_full_check;
4113
475fb78f
AS
4114 ret = check_cfg(env);
4115 if (ret < 0)
4116 goto skip_full_check;
4117
1be7f75d
AS
4118 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
4119
17a52670 4120 ret = do_check(env);
cbd35700 4121
0246e64d 4122skip_full_check:
17a52670 4123 while (pop_stack(env, NULL) >= 0);
f1bca824 4124 free_states(env);
0246e64d 4125
9bac3d6d
AS
4126 if (ret == 0)
4127 /* program is valid, convert *(u32*)(ctx + off) accesses */
4128 ret = convert_ctx_accesses(env);
4129
e245c5c6 4130 if (ret == 0)
79741b3b 4131 ret = fixup_bpf_calls(env);
e245c5c6 4132
cbd35700
AS
4133 if (log_level && log_len >= log_size - 1) {
4134 BUG_ON(log_len >= log_size);
4135 /* verifier log exceeded user supplied buffer */
4136 ret = -ENOSPC;
4137 /* fall through to return what was recorded */
4138 }
4139
4140 /* copy verifier log back to user space including trailing zero */
4141 if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
4142 ret = -EFAULT;
4143 goto free_log_buf;
4144 }
4145
0246e64d
AS
4146 if (ret == 0 && env->used_map_cnt) {
4147 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
4148 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
4149 sizeof(env->used_maps[0]),
4150 GFP_KERNEL);
0246e64d 4151
9bac3d6d 4152 if (!env->prog->aux->used_maps) {
0246e64d
AS
4153 ret = -ENOMEM;
4154 goto free_log_buf;
4155 }
4156
9bac3d6d 4157 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 4158 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 4159 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
4160
4161 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
4162 * bpf_ld_imm64 instructions
4163 */
4164 convert_pseudo_ld_imm64(env);
4165 }
cbd35700
AS
4166
4167free_log_buf:
4168 if (log_level)
4169 vfree(log_buf);
9bac3d6d 4170 if (!env->prog->aux->used_maps)
0246e64d
AS
4171 /* if we didn't copy map pointers into bpf_prog_info, release
4172 * them now. Otherwise free_bpf_prog_info() will release them.
4173 */
4174 release_maps(env);
9bac3d6d 4175 *prog = env->prog;
3df126f3 4176err_unlock:
cbd35700 4177 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
4178 vfree(env->insn_aux_data);
4179err_free_env:
4180 kfree(env);
51580e79
AS
4181 return ret;
4182}
13a27dfc
JK
4183
4184int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
4185 void *priv)
4186{
4187 struct bpf_verifier_env *env;
4188 int ret;
4189
4190 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
4191 if (!env)
4192 return -ENOMEM;
4193
4194 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
4195 prog->len);
4196 ret = -ENOMEM;
4197 if (!env->insn_aux_data)
4198 goto err_free_env;
4199 env->prog = prog;
4200 env->analyzer_ops = ops;
4201 env->analyzer_priv = priv;
4202
4203 /* grab the mutex to protect few globals used by verifier */
4204 mutex_lock(&bpf_verifier_lock);
4205
4206 log_level = 0;
1ad2f583 4207
e07b98d9 4208 env->strict_alignment = false;
1ad2f583
DB
4209 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
4210 env->strict_alignment = true;
13a27dfc
JK
4211
4212 env->explored_states = kcalloc(env->prog->len,
4213 sizeof(struct bpf_verifier_state_list *),
4214 GFP_KERNEL);
4215 ret = -ENOMEM;
4216 if (!env->explored_states)
4217 goto skip_full_check;
4218
4219 ret = check_cfg(env);
4220 if (ret < 0)
4221 goto skip_full_check;
4222
4223 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
4224
4225 ret = do_check(env);
4226
4227skip_full_check:
4228 while (pop_stack(env, NULL) >= 0);
4229 free_states(env);
4230
4231 mutex_unlock(&bpf_verifier_lock);
4232 vfree(env->insn_aux_data);
4233err_free_env:
4234 kfree(env);
4235 return ret;
4236}
4237EXPORT_SYMBOL_GPL(bpf_analyzer);