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