verifier.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923
  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. /* bpf_check() is a static code analyzer that walks eBPF program
  21. * instruction by instruction and updates register/stack state.
  22. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  23. *
  24. * The first pass is depth-first-search to check that the program is a DAG.
  25. * It rejects the following programs:
  26. * - larger than BPF_MAXINSNS insns
  27. * - if loop is present (detected via back-edge)
  28. * - unreachable insns exist (shouldn't be a forest. program = one function)
  29. * - out of bounds or malformed jumps
  30. * The second pass is all possible path descent from the 1st insn.
  31. * Since it's analyzing all pathes through the program, the length of the
  32. * analysis is limited to 32k insn, which may be hit even if total number of
  33. * insn is less then 4K, but there are too many branches that change stack/regs.
  34. * Number of 'branches to be analyzed' is limited to 1k
  35. *
  36. * On entry to each instruction, each register has a type, and the instruction
  37. * changes the types of the registers depending on instruction semantics.
  38. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  39. * copied to R1.
  40. *
  41. * All registers are 64-bit.
  42. * R0 - return register
  43. * R1-R5 argument passing registers
  44. * R6-R9 callee saved registers
  45. * R10 - frame pointer read-only
  46. *
  47. * At the start of BPF program the register R1 contains a pointer to bpf_context
  48. * and has type PTR_TO_CTX.
  49. *
  50. * Verifier tracks arithmetic operations on pointers in case:
  51. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  52. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  53. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  54. * and 2nd arithmetic instruction is pattern matched to recognize
  55. * that it wants to construct a pointer to some element within stack.
  56. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  57. * (and -20 constant is saved for further stack bounds checking).
  58. * Meaning that this reg is a pointer to stack plus known immediate constant.
  59. *
  60. * Most of the time the registers have UNKNOWN_VALUE type, which
  61. * means the register has some value, but it's not a valid pointer.
  62. * (like pointer plus pointer becomes UNKNOWN_VALUE type)
  63. *
  64. * When verifier sees load or store instructions the type of base register
  65. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
  66. * types recognized by check_mem_access() function.
  67. *
  68. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  69. * and the range of [ptr, ptr + map's value_size) is accessible.
  70. *
  71. * registers used to pass values to function calls are checked against
  72. * function argument constraints.
  73. *
  74. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  75. * It means that the register type passed to this function must be
  76. * PTR_TO_STACK and it will be used inside the function as
  77. * 'pointer to map element key'
  78. *
  79. * For example the argument constraints for bpf_map_lookup_elem():
  80. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  81. * .arg1_type = ARG_CONST_MAP_PTR,
  82. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  83. *
  84. * ret_type says that this function returns 'pointer to map elem value or null'
  85. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  86. * 2nd argument should be a pointer to stack, which will be used inside
  87. * the helper function as a pointer to map element key.
  88. *
  89. * On the kernel side the helper function looks like:
  90. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  91. * {
  92. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  93. * void *key = (void *) (unsigned long) r2;
  94. * void *value;
  95. *
  96. * here kernel can access 'key' and 'map' pointers safely, knowing that
  97. * [key, key + map->key_size) bytes are valid and were initialized on
  98. * the stack of eBPF program.
  99. * }
  100. *
  101. * Corresponding eBPF program may look like:
  102. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  103. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  104. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  105. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  106. * here verifier looks at prototype of map_lookup_elem() and sees:
  107. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  108. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  109. *
  110. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  111. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  112. * and were initialized prior to this call.
  113. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  114. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  115. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  116. * returns ether pointer to map value or NULL.
  117. *
  118. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  119. * insn, the register holding that pointer in the true branch changes state to
  120. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  121. * branch. See check_cond_jmp_op().
  122. *
  123. * After the call R0 is set to return type of the function and registers R1-R5
  124. * are set to NOT_INIT to indicate that they are no longer readable.
  125. */
  126. /* types of values stored in eBPF registers */
  127. enum bpf_reg_type {
  128. NOT_INIT = 0, /* nothing was written into register */
  129. UNKNOWN_VALUE, /* reg doesn't contain a valid pointer */
  130. PTR_TO_CTX, /* reg points to bpf_context */
  131. CONST_PTR_TO_MAP, /* reg points to struct bpf_map */
  132. PTR_TO_MAP_VALUE, /* reg points to map element value */
  133. PTR_TO_MAP_VALUE_OR_NULL,/* points to map elem value or NULL */
  134. FRAME_PTR, /* reg == frame_pointer */
  135. PTR_TO_STACK, /* reg == frame_pointer + imm */
  136. CONST_IMM, /* constant integer value */
  137. };
  138. struct reg_state {
  139. enum bpf_reg_type type;
  140. union {
  141. /* valid when type == CONST_IMM | PTR_TO_STACK */
  142. int imm;
  143. /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
  144. * PTR_TO_MAP_VALUE_OR_NULL
  145. */
  146. struct bpf_map *map_ptr;
  147. };
  148. };
  149. enum bpf_stack_slot_type {
  150. STACK_INVALID, /* nothing was stored in this stack slot */
  151. STACK_SPILL, /* 1st byte of register spilled into stack */
  152. STACK_SPILL_PART, /* other 7 bytes of register spill */
  153. STACK_MISC /* BPF program wrote some data into this slot */
  154. };
  155. struct bpf_stack_slot {
  156. enum bpf_stack_slot_type stype;
  157. struct reg_state reg_st;
  158. };
  159. /* state of the program:
  160. * type of all registers and stack info
  161. */
  162. struct verifier_state {
  163. struct reg_state regs[MAX_BPF_REG];
  164. struct bpf_stack_slot stack[MAX_BPF_STACK];
  165. };
  166. /* linked list of verifier states used to prune search */
  167. struct verifier_state_list {
  168. struct verifier_state state;
  169. struct verifier_state_list *next;
  170. };
  171. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  172. struct verifier_stack_elem {
  173. /* verifer state is 'st'
  174. * before processing instruction 'insn_idx'
  175. * and after processing instruction 'prev_insn_idx'
  176. */
  177. struct verifier_state st;
  178. int insn_idx;
  179. int prev_insn_idx;
  180. struct verifier_stack_elem *next;
  181. };
  182. #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
  183. /* single container for all structs
  184. * one verifier_env per bpf_check() call
  185. */
  186. struct verifier_env {
  187. struct bpf_prog *prog; /* eBPF program being verified */
  188. struct verifier_stack_elem *head; /* stack of verifier states to be processed */
  189. int stack_size; /* number of states to be processed */
  190. struct verifier_state cur_state; /* current verifier state */
  191. struct verifier_state_list **explored_states; /* search pruning optimization */
  192. struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
  193. u32 used_map_cnt; /* number of used maps */
  194. };
  195. /* verbose verifier prints what it's seeing
  196. * bpf_check() is called under lock, so no race to access these global vars
  197. */
  198. static u32 log_level, log_size, log_len;
  199. static char *log_buf;
  200. static DEFINE_MUTEX(bpf_verifier_lock);
  201. /* log_level controls verbosity level of eBPF verifier.
  202. * verbose() is used to dump the verification trace to the log, so the user
  203. * can figure out what's wrong with the program
  204. */
  205. static void verbose(const char *fmt, ...)
  206. {
  207. va_list args;
  208. if (log_level == 0 || log_len >= log_size - 1)
  209. return;
  210. va_start(args, fmt);
  211. log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
  212. va_end(args);
  213. }
  214. /* string representation of 'enum bpf_reg_type' */
  215. static const char * const reg_type_str[] = {
  216. [NOT_INIT] = "?",
  217. [UNKNOWN_VALUE] = "inv",
  218. [PTR_TO_CTX] = "ctx",
  219. [CONST_PTR_TO_MAP] = "map_ptr",
  220. [PTR_TO_MAP_VALUE] = "map_value",
  221. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  222. [FRAME_PTR] = "fp",
  223. [PTR_TO_STACK] = "fp",
  224. [CONST_IMM] = "imm",
  225. };
  226. static void print_verifier_state(struct verifier_env *env)
  227. {
  228. enum bpf_reg_type t;
  229. int i;
  230. for (i = 0; i < MAX_BPF_REG; i++) {
  231. t = env->cur_state.regs[i].type;
  232. if (t == NOT_INIT)
  233. continue;
  234. verbose(" R%d=%s", i, reg_type_str[t]);
  235. if (t == CONST_IMM || t == PTR_TO_STACK)
  236. verbose("%d", env->cur_state.regs[i].imm);
  237. else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
  238. t == PTR_TO_MAP_VALUE_OR_NULL)
  239. verbose("(ks=%d,vs=%d)",
  240. env->cur_state.regs[i].map_ptr->key_size,
  241. env->cur_state.regs[i].map_ptr->value_size);
  242. }
  243. for (i = 0; i < MAX_BPF_STACK; i++) {
  244. if (env->cur_state.stack[i].stype == STACK_SPILL)
  245. verbose(" fp%d=%s", -MAX_BPF_STACK + i,
  246. reg_type_str[env->cur_state.stack[i].reg_st.type]);
  247. }
  248. verbose("\n");
  249. }
  250. static const char *const bpf_class_string[] = {
  251. [BPF_LD] = "ld",
  252. [BPF_LDX] = "ldx",
  253. [BPF_ST] = "st",
  254. [BPF_STX] = "stx",
  255. [BPF_ALU] = "alu",
  256. [BPF_JMP] = "jmp",
  257. [BPF_RET] = "BUG",
  258. [BPF_ALU64] = "alu64",
  259. };
  260. static const char *const bpf_alu_string[] = {
  261. [BPF_ADD >> 4] = "+=",
  262. [BPF_SUB >> 4] = "-=",
  263. [BPF_MUL >> 4] = "*=",
  264. [BPF_DIV >> 4] = "/=",
  265. [BPF_OR >> 4] = "|=",
  266. [BPF_AND >> 4] = "&=",
  267. [BPF_LSH >> 4] = "<<=",
  268. [BPF_RSH >> 4] = ">>=",
  269. [BPF_NEG >> 4] = "neg",
  270. [BPF_MOD >> 4] = "%=",
  271. [BPF_XOR >> 4] = "^=",
  272. [BPF_MOV >> 4] = "=",
  273. [BPF_ARSH >> 4] = "s>>=",
  274. [BPF_END >> 4] = "endian",
  275. };
  276. static const char *const bpf_ldst_string[] = {
  277. [BPF_W >> 3] = "u32",
  278. [BPF_H >> 3] = "u16",
  279. [BPF_B >> 3] = "u8",
  280. [BPF_DW >> 3] = "u64",
  281. };
  282. static const char *const bpf_jmp_string[] = {
  283. [BPF_JA >> 4] = "jmp",
  284. [BPF_JEQ >> 4] = "==",
  285. [BPF_JGT >> 4] = ">",
  286. [BPF_JGE >> 4] = ">=",
  287. [BPF_JSET >> 4] = "&",
  288. [BPF_JNE >> 4] = "!=",
  289. [BPF_JSGT >> 4] = "s>",
  290. [BPF_JSGE >> 4] = "s>=",
  291. [BPF_CALL >> 4] = "call",
  292. [BPF_EXIT >> 4] = "exit",
  293. };
  294. static void print_bpf_insn(struct bpf_insn *insn)
  295. {
  296. u8 class = BPF_CLASS(insn->code);
  297. if (class == BPF_ALU || class == BPF_ALU64) {
  298. if (BPF_SRC(insn->code) == BPF_X)
  299. verbose("(%02x) %sr%d %s %sr%d\n",
  300. insn->code, class == BPF_ALU ? "(u32) " : "",
  301. insn->dst_reg,
  302. bpf_alu_string[BPF_OP(insn->code) >> 4],
  303. class == BPF_ALU ? "(u32) " : "",
  304. insn->src_reg);
  305. else
  306. verbose("(%02x) %sr%d %s %s%d\n",
  307. insn->code, class == BPF_ALU ? "(u32) " : "",
  308. insn->dst_reg,
  309. bpf_alu_string[BPF_OP(insn->code) >> 4],
  310. class == BPF_ALU ? "(u32) " : "",
  311. insn->imm);
  312. } else if (class == BPF_STX) {
  313. if (BPF_MODE(insn->code) == BPF_MEM)
  314. verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
  315. insn->code,
  316. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  317. insn->dst_reg,
  318. insn->off, insn->src_reg);
  319. else if (BPF_MODE(insn->code) == BPF_XADD)
  320. verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
  321. insn->code,
  322. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  323. insn->dst_reg, insn->off,
  324. insn->src_reg);
  325. else
  326. verbose("BUG_%02x\n", insn->code);
  327. } else if (class == BPF_ST) {
  328. if (BPF_MODE(insn->code) != BPF_MEM) {
  329. verbose("BUG_st_%02x\n", insn->code);
  330. return;
  331. }
  332. verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
  333. insn->code,
  334. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  335. insn->dst_reg,
  336. insn->off, insn->imm);
  337. } else if (class == BPF_LDX) {
  338. if (BPF_MODE(insn->code) != BPF_MEM) {
  339. verbose("BUG_ldx_%02x\n", insn->code);
  340. return;
  341. }
  342. verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
  343. insn->code, insn->dst_reg,
  344. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  345. insn->src_reg, insn->off);
  346. } else if (class == BPF_LD) {
  347. if (BPF_MODE(insn->code) == BPF_ABS) {
  348. verbose("(%02x) r0 = *(%s *)skb[%d]\n",
  349. insn->code,
  350. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  351. insn->imm);
  352. } else if (BPF_MODE(insn->code) == BPF_IND) {
  353. verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
  354. insn->code,
  355. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  356. insn->src_reg, insn->imm);
  357. } else if (BPF_MODE(insn->code) == BPF_IMM) {
  358. verbose("(%02x) r%d = 0x%x\n",
  359. insn->code, insn->dst_reg, insn->imm);
  360. } else {
  361. verbose("BUG_ld_%02x\n", insn->code);
  362. return;
  363. }
  364. } else if (class == BPF_JMP) {
  365. u8 opcode = BPF_OP(insn->code);
  366. if (opcode == BPF_CALL) {
  367. verbose("(%02x) call %d\n", insn->code, insn->imm);
  368. } else if (insn->code == (BPF_JMP | BPF_JA)) {
  369. verbose("(%02x) goto pc%+d\n",
  370. insn->code, insn->off);
  371. } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
  372. verbose("(%02x) exit\n", insn->code);
  373. } else if (BPF_SRC(insn->code) == BPF_X) {
  374. verbose("(%02x) if r%d %s r%d goto pc%+d\n",
  375. insn->code, insn->dst_reg,
  376. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  377. insn->src_reg, insn->off);
  378. } else {
  379. verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
  380. insn->code, insn->dst_reg,
  381. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  382. insn->imm, insn->off);
  383. }
  384. } else {
  385. verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
  386. }
  387. }
  388. static int pop_stack(struct verifier_env *env, int *prev_insn_idx)
  389. {
  390. struct verifier_stack_elem *elem;
  391. int insn_idx;
  392. if (env->head == NULL)
  393. return -1;
  394. memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
  395. insn_idx = env->head->insn_idx;
  396. if (prev_insn_idx)
  397. *prev_insn_idx = env->head->prev_insn_idx;
  398. elem = env->head->next;
  399. kfree(env->head);
  400. env->head = elem;
  401. env->stack_size--;
  402. return insn_idx;
  403. }
  404. static struct verifier_state *push_stack(struct verifier_env *env, int insn_idx,
  405. int prev_insn_idx)
  406. {
  407. struct verifier_stack_elem *elem;
  408. elem = kmalloc(sizeof(struct verifier_stack_elem), GFP_KERNEL);
  409. if (!elem)
  410. goto err;
  411. memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
  412. elem->insn_idx = insn_idx;
  413. elem->prev_insn_idx = prev_insn_idx;
  414. elem->next = env->head;
  415. env->head = elem;
  416. env->stack_size++;
  417. if (env->stack_size > 1024) {
  418. verbose("BPF program is too complex\n");
  419. goto err;
  420. }
  421. return &elem->st;
  422. err:
  423. /* pop all elements and return */
  424. while (pop_stack(env, NULL) >= 0);
  425. return NULL;
  426. }
  427. #define CALLER_SAVED_REGS 6
  428. static const int caller_saved[CALLER_SAVED_REGS] = {
  429. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  430. };
  431. static void init_reg_state(struct reg_state *regs)
  432. {
  433. int i;
  434. for (i = 0; i < MAX_BPF_REG; i++) {
  435. regs[i].type = NOT_INIT;
  436. regs[i].imm = 0;
  437. regs[i].map_ptr = NULL;
  438. }
  439. /* frame pointer */
  440. regs[BPF_REG_FP].type = FRAME_PTR;
  441. /* 1st arg to a function */
  442. regs[BPF_REG_1].type = PTR_TO_CTX;
  443. }
  444. static void mark_reg_unknown_value(struct reg_state *regs, u32 regno)
  445. {
  446. BUG_ON(regno >= MAX_BPF_REG);
  447. regs[regno].type = UNKNOWN_VALUE;
  448. regs[regno].imm = 0;
  449. regs[regno].map_ptr = NULL;
  450. }
  451. enum reg_arg_type {
  452. SRC_OP, /* register is used as source operand */
  453. DST_OP, /* register is used as destination operand */
  454. DST_OP_NO_MARK /* same as above, check only, don't mark */
  455. };
  456. static int check_reg_arg(struct reg_state *regs, u32 regno,
  457. enum reg_arg_type t)
  458. {
  459. if (regno >= MAX_BPF_REG) {
  460. verbose("R%d is invalid\n", regno);
  461. return -EINVAL;
  462. }
  463. if (t == SRC_OP) {
  464. /* check whether register used as source operand can be read */
  465. if (regs[regno].type == NOT_INIT) {
  466. verbose("R%d !read_ok\n", regno);
  467. return -EACCES;
  468. }
  469. } else {
  470. /* check whether register used as dest operand can be written to */
  471. if (regno == BPF_REG_FP) {
  472. verbose("frame pointer is read only\n");
  473. return -EACCES;
  474. }
  475. if (t == DST_OP)
  476. mark_reg_unknown_value(regs, regno);
  477. }
  478. return 0;
  479. }
  480. static int bpf_size_to_bytes(int bpf_size)
  481. {
  482. if (bpf_size == BPF_W)
  483. return 4;
  484. else if (bpf_size == BPF_H)
  485. return 2;
  486. else if (bpf_size == BPF_B)
  487. return 1;
  488. else if (bpf_size == BPF_DW)
  489. return 8;
  490. else
  491. return -EINVAL;
  492. }
  493. /* check_stack_read/write functions track spill/fill of registers,
  494. * stack boundary and alignment are checked in check_mem_access()
  495. */
  496. static int check_stack_write(struct verifier_state *state, int off, int size,
  497. int value_regno)
  498. {
  499. struct bpf_stack_slot *slot;
  500. int i;
  501. if (value_regno >= 0 &&
  502. (state->regs[value_regno].type == PTR_TO_MAP_VALUE ||
  503. state->regs[value_regno].type == PTR_TO_STACK ||
  504. state->regs[value_regno].type == PTR_TO_CTX)) {
  505. /* register containing pointer is being spilled into stack */
  506. if (size != 8) {
  507. verbose("invalid size of register spill\n");
  508. return -EACCES;
  509. }
  510. slot = &state->stack[MAX_BPF_STACK + off];
  511. slot->stype = STACK_SPILL;
  512. /* save register state */
  513. slot->reg_st = state->regs[value_regno];
  514. for (i = 1; i < 8; i++) {
  515. slot = &state->stack[MAX_BPF_STACK + off + i];
  516. slot->stype = STACK_SPILL_PART;
  517. slot->reg_st.type = UNKNOWN_VALUE;
  518. slot->reg_st.map_ptr = NULL;
  519. }
  520. } else {
  521. /* regular write of data into stack */
  522. for (i = 0; i < size; i++) {
  523. slot = &state->stack[MAX_BPF_STACK + off + i];
  524. slot->stype = STACK_MISC;
  525. slot->reg_st.type = UNKNOWN_VALUE;
  526. slot->reg_st.map_ptr = NULL;
  527. }
  528. }
  529. return 0;
  530. }
  531. static int check_stack_read(struct verifier_state *state, int off, int size,
  532. int value_regno)
  533. {
  534. int i;
  535. struct bpf_stack_slot *slot;
  536. slot = &state->stack[MAX_BPF_STACK + off];
  537. if (slot->stype == STACK_SPILL) {
  538. if (size != 8) {
  539. verbose("invalid size of register spill\n");
  540. return -EACCES;
  541. }
  542. for (i = 1; i < 8; i++) {
  543. if (state->stack[MAX_BPF_STACK + off + i].stype !=
  544. STACK_SPILL_PART) {
  545. verbose("corrupted spill memory\n");
  546. return -EACCES;
  547. }
  548. }
  549. if (value_regno >= 0)
  550. /* restore register state from stack */
  551. state->regs[value_regno] = slot->reg_st;
  552. return 0;
  553. } else {
  554. for (i = 0; i < size; i++) {
  555. if (state->stack[MAX_BPF_STACK + off + i].stype !=
  556. STACK_MISC) {
  557. verbose("invalid read from stack off %d+%d size %d\n",
  558. off, i, size);
  559. return -EACCES;
  560. }
  561. }
  562. if (value_regno >= 0)
  563. /* have read misc data from the stack */
  564. mark_reg_unknown_value(state->regs, value_regno);
  565. return 0;
  566. }
  567. }
  568. /* check read/write into map element returned by bpf_map_lookup_elem() */
  569. static int check_map_access(struct verifier_env *env, u32 regno, int off,
  570. int size)
  571. {
  572. struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
  573. if (off < 0 || off + size > map->value_size) {
  574. verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
  575. map->value_size, off, size);
  576. return -EACCES;
  577. }
  578. return 0;
  579. }
  580. /* check access to 'struct bpf_context' fields */
  581. static int check_ctx_access(struct verifier_env *env, int off, int size,
  582. enum bpf_access_type t)
  583. {
  584. if (env->prog->aux->ops->is_valid_access &&
  585. env->prog->aux->ops->is_valid_access(off, size, t))
  586. return 0;
  587. verbose("invalid bpf_context access off=%d size=%d\n", off, size);
  588. return -EACCES;
  589. }
  590. /* check whether memory at (regno + off) is accessible for t = (read | write)
  591. * if t==write, value_regno is a register which value is stored into memory
  592. * if t==read, value_regno is a register which will receive the value from memory
  593. * if t==write && value_regno==-1, some unknown value is stored into memory
  594. * if t==read && value_regno==-1, don't care what we read from memory
  595. */
  596. static int check_mem_access(struct verifier_env *env, u32 regno, int off,
  597. int bpf_size, enum bpf_access_type t,
  598. int value_regno)
  599. {
  600. struct verifier_state *state = &env->cur_state;
  601. int size, err = 0;
  602. size = bpf_size_to_bytes(bpf_size);
  603. if (size < 0)
  604. return size;
  605. if (off % size != 0) {
  606. verbose("misaligned access off %d size %d\n", off, size);
  607. return -EACCES;
  608. }
  609. if (state->regs[regno].type == PTR_TO_MAP_VALUE) {
  610. err = check_map_access(env, regno, off, size);
  611. if (!err && t == BPF_READ && value_regno >= 0)
  612. mark_reg_unknown_value(state->regs, value_regno);
  613. } else if (state->regs[regno].type == PTR_TO_CTX) {
  614. err = check_ctx_access(env, off, size, t);
  615. if (!err && t == BPF_READ && value_regno >= 0)
  616. mark_reg_unknown_value(state->regs, value_regno);
  617. } else if (state->regs[regno].type == FRAME_PTR) {
  618. if (off >= 0 || off < -MAX_BPF_STACK) {
  619. verbose("invalid stack off=%d size=%d\n", off, size);
  620. return -EACCES;
  621. }
  622. if (t == BPF_WRITE)
  623. err = check_stack_write(state, off, size, value_regno);
  624. else
  625. err = check_stack_read(state, off, size, value_regno);
  626. } else {
  627. verbose("R%d invalid mem access '%s'\n",
  628. regno, reg_type_str[state->regs[regno].type]);
  629. return -EACCES;
  630. }
  631. return err;
  632. }
  633. static int check_xadd(struct verifier_env *env, struct bpf_insn *insn)
  634. {
  635. struct reg_state *regs = env->cur_state.regs;
  636. int err;
  637. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  638. insn->imm != 0) {
  639. verbose("BPF_XADD uses reserved fields\n");
  640. return -EINVAL;
  641. }
  642. /* check src1 operand */
  643. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  644. if (err)
  645. return err;
  646. /* check src2 operand */
  647. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  648. if (err)
  649. return err;
  650. /* check whether atomic_add can read the memory */
  651. err = check_mem_access(env, insn->dst_reg, insn->off,
  652. BPF_SIZE(insn->code), BPF_READ, -1);
  653. if (err)
  654. return err;
  655. /* check whether atomic_add can write into the same memory */
  656. return check_mem_access(env, insn->dst_reg, insn->off,
  657. BPF_SIZE(insn->code), BPF_WRITE, -1);
  658. }
  659. /* when register 'regno' is passed into function that will read 'access_size'
  660. * bytes from that pointer, make sure that it's within stack boundary
  661. * and all elements of stack are initialized
  662. */
  663. static int check_stack_boundary(struct verifier_env *env,
  664. int regno, int access_size)
  665. {
  666. struct verifier_state *state = &env->cur_state;
  667. struct reg_state *regs = state->regs;
  668. int off, i;
  669. if (regs[regno].type != PTR_TO_STACK)
  670. return -EACCES;
  671. off = regs[regno].imm;
  672. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  673. access_size <= 0) {
  674. verbose("invalid stack type R%d off=%d access_size=%d\n",
  675. regno, off, access_size);
  676. return -EACCES;
  677. }
  678. for (i = 0; i < access_size; i++) {
  679. if (state->stack[MAX_BPF_STACK + off + i].stype != STACK_MISC) {
  680. verbose("invalid indirect read from stack off %d+%d size %d\n",
  681. off, i, access_size);
  682. return -EACCES;
  683. }
  684. }
  685. return 0;
  686. }
  687. static int check_func_arg(struct verifier_env *env, u32 regno,
  688. enum bpf_arg_type arg_type, struct bpf_map **mapp)
  689. {
  690. struct reg_state *reg = env->cur_state.regs + regno;
  691. enum bpf_reg_type expected_type;
  692. int err = 0;
  693. if (arg_type == ARG_ANYTHING)
  694. return 0;
  695. if (reg->type == NOT_INIT) {
  696. verbose("R%d !read_ok\n", regno);
  697. return -EACCES;
  698. }
  699. if (arg_type == ARG_PTR_TO_STACK || arg_type == ARG_PTR_TO_MAP_KEY ||
  700. arg_type == ARG_PTR_TO_MAP_VALUE) {
  701. expected_type = PTR_TO_STACK;
  702. } else if (arg_type == ARG_CONST_STACK_SIZE) {
  703. expected_type = CONST_IMM;
  704. } else if (arg_type == ARG_CONST_MAP_PTR) {
  705. expected_type = CONST_PTR_TO_MAP;
  706. } else {
  707. verbose("unsupported arg_type %d\n", arg_type);
  708. return -EFAULT;
  709. }
  710. if (reg->type != expected_type) {
  711. verbose("R%d type=%s expected=%s\n", regno,
  712. reg_type_str[reg->type], reg_type_str[expected_type]);
  713. return -EACCES;
  714. }
  715. if (arg_type == ARG_CONST_MAP_PTR) {
  716. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  717. *mapp = reg->map_ptr;
  718. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  719. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  720. * check that [key, key + map->key_size) are within
  721. * stack limits and initialized
  722. */
  723. if (!*mapp) {
  724. /* in function declaration map_ptr must come before
  725. * map_key, so that it's verified and known before
  726. * we have to check map_key here. Otherwise it means
  727. * that kernel subsystem misconfigured verifier
  728. */
  729. verbose("invalid map_ptr to access map->key\n");
  730. return -EACCES;
  731. }
  732. err = check_stack_boundary(env, regno, (*mapp)->key_size);
  733. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  734. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  735. * check [value, value + map->value_size) validity
  736. */
  737. if (!*mapp) {
  738. /* kernel subsystem misconfigured verifier */
  739. verbose("invalid map_ptr to access map->value\n");
  740. return -EACCES;
  741. }
  742. err = check_stack_boundary(env, regno, (*mapp)->value_size);
  743. } else if (arg_type == ARG_CONST_STACK_SIZE) {
  744. /* bpf_xxx(..., buf, len) call will access 'len' bytes
  745. * from stack pointer 'buf'. Check it
  746. * note: regno == len, regno - 1 == buf
  747. */
  748. if (regno == 0) {
  749. /* kernel subsystem misconfigured verifier */
  750. verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
  751. return -EACCES;
  752. }
  753. err = check_stack_boundary(env, regno - 1, reg->imm);
  754. }
  755. return err;
  756. }
  757. static int check_call(struct verifier_env *env, int func_id)
  758. {
  759. struct verifier_state *state = &env->cur_state;
  760. const struct bpf_func_proto *fn = NULL;
  761. struct reg_state *regs = state->regs;
  762. struct bpf_map *map = NULL;
  763. struct reg_state *reg;
  764. int i, err;
  765. /* find function prototype */
  766. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  767. verbose("invalid func %d\n", func_id);
  768. return -EINVAL;
  769. }
  770. if (env->prog->aux->ops->get_func_proto)
  771. fn = env->prog->aux->ops->get_func_proto(func_id);
  772. if (!fn) {
  773. verbose("unknown func %d\n", func_id);
  774. return -EINVAL;
  775. }
  776. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  777. if (!env->prog->aux->is_gpl_compatible && fn->gpl_only) {
  778. verbose("cannot call GPL only function from proprietary program\n");
  779. return -EINVAL;
  780. }
  781. /* check args */
  782. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &map);
  783. if (err)
  784. return err;
  785. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &map);
  786. if (err)
  787. return err;
  788. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &map);
  789. if (err)
  790. return err;
  791. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &map);
  792. if (err)
  793. return err;
  794. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &map);
  795. if (err)
  796. return err;
  797. /* reset caller saved regs */
  798. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  799. reg = regs + caller_saved[i];
  800. reg->type = NOT_INIT;
  801. reg->imm = 0;
  802. }
  803. /* update return register */
  804. if (fn->ret_type == RET_INTEGER) {
  805. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  806. } else if (fn->ret_type == RET_VOID) {
  807. regs[BPF_REG_0].type = NOT_INIT;
  808. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  809. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  810. /* remember map_ptr, so that check_map_access()
  811. * can check 'value_size' boundary of memory access
  812. * to map element returned from bpf_map_lookup_elem()
  813. */
  814. if (map == NULL) {
  815. verbose("kernel subsystem misconfigured verifier\n");
  816. return -EINVAL;
  817. }
  818. regs[BPF_REG_0].map_ptr = map;
  819. } else {
  820. verbose("unknown return type %d of func %d\n",
  821. fn->ret_type, func_id);
  822. return -EINVAL;
  823. }
  824. return 0;
  825. }
  826. /* check validity of 32-bit and 64-bit arithmetic operations */
  827. static int check_alu_op(struct reg_state *regs, struct bpf_insn *insn)
  828. {
  829. u8 opcode = BPF_OP(insn->code);
  830. int err;
  831. if (opcode == BPF_END || opcode == BPF_NEG) {
  832. if (opcode == BPF_NEG) {
  833. if (BPF_SRC(insn->code) != 0 ||
  834. insn->src_reg != BPF_REG_0 ||
  835. insn->off != 0 || insn->imm != 0) {
  836. verbose("BPF_NEG uses reserved fields\n");
  837. return -EINVAL;
  838. }
  839. } else {
  840. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  841. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
  842. verbose("BPF_END uses reserved fields\n");
  843. return -EINVAL;
  844. }
  845. }
  846. /* check src operand */
  847. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  848. if (err)
  849. return err;
  850. /* check dest operand */
  851. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  852. if (err)
  853. return err;
  854. } else if (opcode == BPF_MOV) {
  855. if (BPF_SRC(insn->code) == BPF_X) {
  856. if (insn->imm != 0 || insn->off != 0) {
  857. verbose("BPF_MOV uses reserved fields\n");
  858. return -EINVAL;
  859. }
  860. /* check src operand */
  861. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  862. if (err)
  863. return err;
  864. } else {
  865. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  866. verbose("BPF_MOV uses reserved fields\n");
  867. return -EINVAL;
  868. }
  869. }
  870. /* check dest operand */
  871. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  872. if (err)
  873. return err;
  874. if (BPF_SRC(insn->code) == BPF_X) {
  875. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  876. /* case: R1 = R2
  877. * copy register state to dest reg
  878. */
  879. regs[insn->dst_reg] = regs[insn->src_reg];
  880. } else {
  881. regs[insn->dst_reg].type = UNKNOWN_VALUE;
  882. regs[insn->dst_reg].map_ptr = NULL;
  883. }
  884. } else {
  885. /* case: R = imm
  886. * remember the value we stored into this reg
  887. */
  888. regs[insn->dst_reg].type = CONST_IMM;
  889. regs[insn->dst_reg].imm = insn->imm;
  890. }
  891. } else if (opcode > BPF_END) {
  892. verbose("invalid BPF_ALU opcode %x\n", opcode);
  893. return -EINVAL;
  894. } else { /* all other ALU ops: and, sub, xor, add, ... */
  895. bool stack_relative = false;
  896. if (BPF_SRC(insn->code) == BPF_X) {
  897. if (insn->imm != 0 || insn->off != 0) {
  898. verbose("BPF_ALU uses reserved fields\n");
  899. return -EINVAL;
  900. }
  901. /* check src1 operand */
  902. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  903. if (err)
  904. return err;
  905. } else {
  906. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  907. verbose("BPF_ALU uses reserved fields\n");
  908. return -EINVAL;
  909. }
  910. }
  911. /* check src2 operand */
  912. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  913. if (err)
  914. return err;
  915. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  916. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  917. verbose("div by zero\n");
  918. return -EINVAL;
  919. }
  920. /* pattern match 'bpf_add Rx, imm' instruction */
  921. if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
  922. regs[insn->dst_reg].type == FRAME_PTR &&
  923. BPF_SRC(insn->code) == BPF_K)
  924. stack_relative = true;
  925. /* check dest operand */
  926. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  927. if (err)
  928. return err;
  929. if (stack_relative) {
  930. regs[insn->dst_reg].type = PTR_TO_STACK;
  931. regs[insn->dst_reg].imm = insn->imm;
  932. }
  933. }
  934. return 0;
  935. }
  936. static int check_cond_jmp_op(struct verifier_env *env,
  937. struct bpf_insn *insn, int *insn_idx)
  938. {
  939. struct reg_state *regs = env->cur_state.regs;
  940. struct verifier_state *other_branch;
  941. u8 opcode = BPF_OP(insn->code);
  942. int err;
  943. if (opcode > BPF_EXIT) {
  944. verbose("invalid BPF_JMP opcode %x\n", opcode);
  945. return -EINVAL;
  946. }
  947. if (BPF_SRC(insn->code) == BPF_X) {
  948. if (insn->imm != 0) {
  949. verbose("BPF_JMP uses reserved fields\n");
  950. return -EINVAL;
  951. }
  952. /* check src1 operand */
  953. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  954. if (err)
  955. return err;
  956. } else {
  957. if (insn->src_reg != BPF_REG_0) {
  958. verbose("BPF_JMP uses reserved fields\n");
  959. return -EINVAL;
  960. }
  961. }
  962. /* check src2 operand */
  963. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  964. if (err)
  965. return err;
  966. /* detect if R == 0 where R was initialized to zero earlier */
  967. if (BPF_SRC(insn->code) == BPF_K &&
  968. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  969. regs[insn->dst_reg].type == CONST_IMM &&
  970. regs[insn->dst_reg].imm == insn->imm) {
  971. if (opcode == BPF_JEQ) {
  972. /* if (imm == imm) goto pc+off;
  973. * only follow the goto, ignore fall-through
  974. */
  975. *insn_idx += insn->off;
  976. return 0;
  977. } else {
  978. /* if (imm != imm) goto pc+off;
  979. * only follow fall-through branch, since
  980. * that's where the program will go
  981. */
  982. return 0;
  983. }
  984. }
  985. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  986. if (!other_branch)
  987. return -EFAULT;
  988. /* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
  989. if (BPF_SRC(insn->code) == BPF_K &&
  990. insn->imm == 0 && (opcode == BPF_JEQ ||
  991. opcode == BPF_JNE) &&
  992. regs[insn->dst_reg].type == PTR_TO_MAP_VALUE_OR_NULL) {
  993. if (opcode == BPF_JEQ) {
  994. /* next fallthrough insn can access memory via
  995. * this register
  996. */
  997. regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  998. /* branch targer cannot access it, since reg == 0 */
  999. other_branch->regs[insn->dst_reg].type = CONST_IMM;
  1000. other_branch->regs[insn->dst_reg].imm = 0;
  1001. } else {
  1002. other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1003. regs[insn->dst_reg].type = CONST_IMM;
  1004. regs[insn->dst_reg].imm = 0;
  1005. }
  1006. } else if (BPF_SRC(insn->code) == BPF_K &&
  1007. (opcode == BPF_JEQ || opcode == BPF_JNE)) {
  1008. if (opcode == BPF_JEQ) {
  1009. /* detect if (R == imm) goto
  1010. * and in the target state recognize that R = imm
  1011. */
  1012. other_branch->regs[insn->dst_reg].type = CONST_IMM;
  1013. other_branch->regs[insn->dst_reg].imm = insn->imm;
  1014. } else {
  1015. /* detect if (R != imm) goto
  1016. * and in the fall-through state recognize that R = imm
  1017. */
  1018. regs[insn->dst_reg].type = CONST_IMM;
  1019. regs[insn->dst_reg].imm = insn->imm;
  1020. }
  1021. }
  1022. if (log_level)
  1023. print_verifier_state(env);
  1024. return 0;
  1025. }
  1026. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  1027. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  1028. {
  1029. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  1030. return (struct bpf_map *) (unsigned long) imm64;
  1031. }
  1032. /* verify BPF_LD_IMM64 instruction */
  1033. static int check_ld_imm(struct verifier_env *env, struct bpf_insn *insn)
  1034. {
  1035. struct reg_state *regs = env->cur_state.regs;
  1036. int err;
  1037. if (BPF_SIZE(insn->code) != BPF_DW) {
  1038. verbose("invalid BPF_LD_IMM insn\n");
  1039. return -EINVAL;
  1040. }
  1041. if (insn->off != 0) {
  1042. verbose("BPF_LD_IMM64 uses reserved fields\n");
  1043. return -EINVAL;
  1044. }
  1045. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1046. if (err)
  1047. return err;
  1048. if (insn->src_reg == 0)
  1049. /* generic move 64-bit immediate into a register */
  1050. return 0;
  1051. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  1052. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  1053. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  1054. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  1055. return 0;
  1056. }
  1057. /* non-recursive DFS pseudo code
  1058. * 1 procedure DFS-iterative(G,v):
  1059. * 2 label v as discovered
  1060. * 3 let S be a stack
  1061. * 4 S.push(v)
  1062. * 5 while S is not empty
  1063. * 6 t <- S.pop()
  1064. * 7 if t is what we're looking for:
  1065. * 8 return t
  1066. * 9 for all edges e in G.adjacentEdges(t) do
  1067. * 10 if edge e is already labelled
  1068. * 11 continue with the next edge
  1069. * 12 w <- G.adjacentVertex(t,e)
  1070. * 13 if vertex w is not discovered and not explored
  1071. * 14 label e as tree-edge
  1072. * 15 label w as discovered
  1073. * 16 S.push(w)
  1074. * 17 continue at 5
  1075. * 18 else if vertex w is discovered
  1076. * 19 label e as back-edge
  1077. * 20 else
  1078. * 21 // vertex w is explored
  1079. * 22 label e as forward- or cross-edge
  1080. * 23 label t as explored
  1081. * 24 S.pop()
  1082. *
  1083. * convention:
  1084. * 0x10 - discovered
  1085. * 0x11 - discovered and fall-through edge labelled
  1086. * 0x12 - discovered and fall-through and branch edges labelled
  1087. * 0x20 - explored
  1088. */
  1089. enum {
  1090. DISCOVERED = 0x10,
  1091. EXPLORED = 0x20,
  1092. FALLTHROUGH = 1,
  1093. BRANCH = 2,
  1094. };
  1095. #define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
  1096. static int *insn_stack; /* stack of insns to process */
  1097. static int cur_stack; /* current stack index */
  1098. static int *insn_state;
  1099. /* t, w, e - match pseudo-code above:
  1100. * t - index of current instruction
  1101. * w - next instruction
  1102. * e - edge
  1103. */
  1104. static int push_insn(int t, int w, int e, struct verifier_env *env)
  1105. {
  1106. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  1107. return 0;
  1108. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  1109. return 0;
  1110. if (w < 0 || w >= env->prog->len) {
  1111. verbose("jump out of range from insn %d to %d\n", t, w);
  1112. return -EINVAL;
  1113. }
  1114. if (e == BRANCH)
  1115. /* mark branch target for state pruning */
  1116. env->explored_states[w] = STATE_LIST_MARK;
  1117. if (insn_state[w] == 0) {
  1118. /* tree-edge */
  1119. insn_state[t] = DISCOVERED | e;
  1120. insn_state[w] = DISCOVERED;
  1121. if (cur_stack >= env->prog->len)
  1122. return -E2BIG;
  1123. insn_stack[cur_stack++] = w;
  1124. return 1;
  1125. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  1126. verbose("back-edge from insn %d to %d\n", t, w);
  1127. return -EINVAL;
  1128. } else if (insn_state[w] == EXPLORED) {
  1129. /* forward- or cross-edge */
  1130. insn_state[t] = DISCOVERED | e;
  1131. } else {
  1132. verbose("insn state internal bug\n");
  1133. return -EFAULT;
  1134. }
  1135. return 0;
  1136. }
  1137. /* non-recursive depth-first-search to detect loops in BPF program
  1138. * loop == back-edge in directed graph
  1139. */
  1140. static int check_cfg(struct verifier_env *env)
  1141. {
  1142. struct bpf_insn *insns = env->prog->insnsi;
  1143. int insn_cnt = env->prog->len;
  1144. int ret = 0;
  1145. int i, t;
  1146. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1147. if (!insn_state)
  1148. return -ENOMEM;
  1149. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1150. if (!insn_stack) {
  1151. kfree(insn_state);
  1152. return -ENOMEM;
  1153. }
  1154. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  1155. insn_stack[0] = 0; /* 0 is the first instruction */
  1156. cur_stack = 1;
  1157. peek_stack:
  1158. if (cur_stack == 0)
  1159. goto check_state;
  1160. t = insn_stack[cur_stack - 1];
  1161. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  1162. u8 opcode = BPF_OP(insns[t].code);
  1163. if (opcode == BPF_EXIT) {
  1164. goto mark_explored;
  1165. } else if (opcode == BPF_CALL) {
  1166. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1167. if (ret == 1)
  1168. goto peek_stack;
  1169. else if (ret < 0)
  1170. goto err_free;
  1171. } else if (opcode == BPF_JA) {
  1172. if (BPF_SRC(insns[t].code) != BPF_K) {
  1173. ret = -EINVAL;
  1174. goto err_free;
  1175. }
  1176. /* unconditional jump with single edge */
  1177. ret = push_insn(t, t + insns[t].off + 1,
  1178. FALLTHROUGH, env);
  1179. if (ret == 1)
  1180. goto peek_stack;
  1181. else if (ret < 0)
  1182. goto err_free;
  1183. /* tell verifier to check for equivalent states
  1184. * after every call and jump
  1185. */
  1186. env->explored_states[t + 1] = STATE_LIST_MARK;
  1187. } else {
  1188. /* conditional jump with two edges */
  1189. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1190. if (ret == 1)
  1191. goto peek_stack;
  1192. else if (ret < 0)
  1193. goto err_free;
  1194. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  1195. if (ret == 1)
  1196. goto peek_stack;
  1197. else if (ret < 0)
  1198. goto err_free;
  1199. }
  1200. } else {
  1201. /* all other non-branch instructions with single
  1202. * fall-through edge
  1203. */
  1204. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1205. if (ret == 1)
  1206. goto peek_stack;
  1207. else if (ret < 0)
  1208. goto err_free;
  1209. }
  1210. mark_explored:
  1211. insn_state[t] = EXPLORED;
  1212. if (cur_stack-- <= 0) {
  1213. verbose("pop stack internal bug\n");
  1214. ret = -EFAULT;
  1215. goto err_free;
  1216. }
  1217. goto peek_stack;
  1218. check_state:
  1219. for (i = 0; i < insn_cnt; i++) {
  1220. if (insn_state[i] != EXPLORED) {
  1221. verbose("unreachable insn %d\n", i);
  1222. ret = -EINVAL;
  1223. goto err_free;
  1224. }
  1225. }
  1226. ret = 0; /* cfg looks good */
  1227. err_free:
  1228. kfree(insn_state);
  1229. kfree(insn_stack);
  1230. return ret;
  1231. }
  1232. /* compare two verifier states
  1233. *
  1234. * all states stored in state_list are known to be valid, since
  1235. * verifier reached 'bpf_exit' instruction through them
  1236. *
  1237. * this function is called when verifier exploring different branches of
  1238. * execution popped from the state stack. If it sees an old state that has
  1239. * more strict register state and more strict stack state then this execution
  1240. * branch doesn't need to be explored further, since verifier already
  1241. * concluded that more strict state leads to valid finish.
  1242. *
  1243. * Therefore two states are equivalent if register state is more conservative
  1244. * and explored stack state is more conservative than the current one.
  1245. * Example:
  1246. * explored current
  1247. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  1248. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  1249. *
  1250. * In other words if current stack state (one being explored) has more
  1251. * valid slots than old one that already passed validation, it means
  1252. * the verifier can stop exploring and conclude that current state is valid too
  1253. *
  1254. * Similarly with registers. If explored state has register type as invalid
  1255. * whereas register type in current state is meaningful, it means that
  1256. * the current state will reach 'bpf_exit' instruction safely
  1257. */
  1258. static bool states_equal(struct verifier_state *old, struct verifier_state *cur)
  1259. {
  1260. int i;
  1261. for (i = 0; i < MAX_BPF_REG; i++) {
  1262. if (memcmp(&old->regs[i], &cur->regs[i],
  1263. sizeof(old->regs[0])) != 0) {
  1264. if (old->regs[i].type == NOT_INIT ||
  1265. old->regs[i].type == UNKNOWN_VALUE)
  1266. continue;
  1267. return false;
  1268. }
  1269. }
  1270. for (i = 0; i < MAX_BPF_STACK; i++) {
  1271. if (memcmp(&old->stack[i], &cur->stack[i],
  1272. sizeof(old->stack[0])) != 0) {
  1273. if (old->stack[i].stype == STACK_INVALID)
  1274. continue;
  1275. return false;
  1276. }
  1277. }
  1278. return true;
  1279. }
  1280. static int is_state_visited(struct verifier_env *env, int insn_idx)
  1281. {
  1282. struct verifier_state_list *new_sl;
  1283. struct verifier_state_list *sl;
  1284. sl = env->explored_states[insn_idx];
  1285. if (!sl)
  1286. /* this 'insn_idx' instruction wasn't marked, so we will not
  1287. * be doing state search here
  1288. */
  1289. return 0;
  1290. while (sl != STATE_LIST_MARK) {
  1291. if (states_equal(&sl->state, &env->cur_state))
  1292. /* reached equivalent register/stack state,
  1293. * prune the search
  1294. */
  1295. return 1;
  1296. sl = sl->next;
  1297. }
  1298. /* there were no equivalent states, remember current one.
  1299. * technically the current state is not proven to be safe yet,
  1300. * but it will either reach bpf_exit (which means it's safe) or
  1301. * it will be rejected. Since there are no loops, we won't be
  1302. * seeing this 'insn_idx' instruction again on the way to bpf_exit
  1303. */
  1304. new_sl = kmalloc(sizeof(struct verifier_state_list), GFP_USER);
  1305. if (!new_sl)
  1306. return -ENOMEM;
  1307. /* add new state to the head of linked list */
  1308. memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
  1309. new_sl->next = env->explored_states[insn_idx];
  1310. env->explored_states[insn_idx] = new_sl;
  1311. return 0;
  1312. }
  1313. static int do_check(struct verifier_env *env)
  1314. {
  1315. struct verifier_state *state = &env->cur_state;
  1316. struct bpf_insn *insns = env->prog->insnsi;
  1317. struct reg_state *regs = state->regs;
  1318. int insn_cnt = env->prog->len;
  1319. int insn_idx, prev_insn_idx = 0;
  1320. int insn_processed = 0;
  1321. bool do_print_state = false;
  1322. init_reg_state(regs);
  1323. insn_idx = 0;
  1324. for (;;) {
  1325. struct bpf_insn *insn;
  1326. u8 class;
  1327. int err;
  1328. if (insn_idx >= insn_cnt) {
  1329. verbose("invalid insn idx %d insn_cnt %d\n",
  1330. insn_idx, insn_cnt);
  1331. return -EFAULT;
  1332. }
  1333. insn = &insns[insn_idx];
  1334. class = BPF_CLASS(insn->code);
  1335. if (++insn_processed > 32768) {
  1336. verbose("BPF program is too large. Proccessed %d insn\n",
  1337. insn_processed);
  1338. return -E2BIG;
  1339. }
  1340. err = is_state_visited(env, insn_idx);
  1341. if (err < 0)
  1342. return err;
  1343. if (err == 1) {
  1344. /* found equivalent state, can prune the search */
  1345. if (log_level) {
  1346. if (do_print_state)
  1347. verbose("\nfrom %d to %d: safe\n",
  1348. prev_insn_idx, insn_idx);
  1349. else
  1350. verbose("%d: safe\n", insn_idx);
  1351. }
  1352. goto process_bpf_exit;
  1353. }
  1354. if (log_level && do_print_state) {
  1355. verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
  1356. print_verifier_state(env);
  1357. do_print_state = false;
  1358. }
  1359. if (log_level) {
  1360. verbose("%d: ", insn_idx);
  1361. print_bpf_insn(insn);
  1362. }
  1363. if (class == BPF_ALU || class == BPF_ALU64) {
  1364. err = check_alu_op(regs, insn);
  1365. if (err)
  1366. return err;
  1367. } else if (class == BPF_LDX) {
  1368. if (BPF_MODE(insn->code) != BPF_MEM ||
  1369. insn->imm != 0) {
  1370. verbose("BPF_LDX uses reserved fields\n");
  1371. return -EINVAL;
  1372. }
  1373. /* check src operand */
  1374. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1375. if (err)
  1376. return err;
  1377. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  1378. if (err)
  1379. return err;
  1380. /* check that memory (src_reg + off) is readable,
  1381. * the state of dst_reg will be updated by this func
  1382. */
  1383. err = check_mem_access(env, insn->src_reg, insn->off,
  1384. BPF_SIZE(insn->code), BPF_READ,
  1385. insn->dst_reg);
  1386. if (err)
  1387. return err;
  1388. } else if (class == BPF_STX) {
  1389. if (BPF_MODE(insn->code) == BPF_XADD) {
  1390. err = check_xadd(env, insn);
  1391. if (err)
  1392. return err;
  1393. insn_idx++;
  1394. continue;
  1395. }
  1396. if (BPF_MODE(insn->code) != BPF_MEM ||
  1397. insn->imm != 0) {
  1398. verbose("BPF_STX uses reserved fields\n");
  1399. return -EINVAL;
  1400. }
  1401. /* check src1 operand */
  1402. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1403. if (err)
  1404. return err;
  1405. /* check src2 operand */
  1406. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1407. if (err)
  1408. return err;
  1409. /* check that memory (dst_reg + off) is writeable */
  1410. err = check_mem_access(env, insn->dst_reg, insn->off,
  1411. BPF_SIZE(insn->code), BPF_WRITE,
  1412. insn->src_reg);
  1413. if (err)
  1414. return err;
  1415. } else if (class == BPF_ST) {
  1416. if (BPF_MODE(insn->code) != BPF_MEM ||
  1417. insn->src_reg != BPF_REG_0) {
  1418. verbose("BPF_ST uses reserved fields\n");
  1419. return -EINVAL;
  1420. }
  1421. /* check src operand */
  1422. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1423. if (err)
  1424. return err;
  1425. /* check that memory (dst_reg + off) is writeable */
  1426. err = check_mem_access(env, insn->dst_reg, insn->off,
  1427. BPF_SIZE(insn->code), BPF_WRITE,
  1428. -1);
  1429. if (err)
  1430. return err;
  1431. } else if (class == BPF_JMP) {
  1432. u8 opcode = BPF_OP(insn->code);
  1433. if (opcode == BPF_CALL) {
  1434. if (BPF_SRC(insn->code) != BPF_K ||
  1435. insn->off != 0 ||
  1436. insn->src_reg != BPF_REG_0 ||
  1437. insn->dst_reg != BPF_REG_0) {
  1438. verbose("BPF_CALL uses reserved fields\n");
  1439. return -EINVAL;
  1440. }
  1441. err = check_call(env, insn->imm);
  1442. if (err)
  1443. return err;
  1444. } else if (opcode == BPF_JA) {
  1445. if (BPF_SRC(insn->code) != BPF_K ||
  1446. insn->imm != 0 ||
  1447. insn->src_reg != BPF_REG_0 ||
  1448. insn->dst_reg != BPF_REG_0) {
  1449. verbose("BPF_JA uses reserved fields\n");
  1450. return -EINVAL;
  1451. }
  1452. insn_idx += insn->off + 1;
  1453. continue;
  1454. } else if (opcode == BPF_EXIT) {
  1455. if (BPF_SRC(insn->code) != BPF_K ||
  1456. insn->imm != 0 ||
  1457. insn->src_reg != BPF_REG_0 ||
  1458. insn->dst_reg != BPF_REG_0) {
  1459. verbose("BPF_EXIT uses reserved fields\n");
  1460. return -EINVAL;
  1461. }
  1462. /* eBPF calling convetion is such that R0 is used
  1463. * to return the value from eBPF program.
  1464. * Make sure that it's readable at this time
  1465. * of bpf_exit, which means that program wrote
  1466. * something into it earlier
  1467. */
  1468. err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
  1469. if (err)
  1470. return err;
  1471. process_bpf_exit:
  1472. insn_idx = pop_stack(env, &prev_insn_idx);
  1473. if (insn_idx < 0) {
  1474. break;
  1475. } else {
  1476. do_print_state = true;
  1477. continue;
  1478. }
  1479. } else {
  1480. err = check_cond_jmp_op(env, insn, &insn_idx);
  1481. if (err)
  1482. return err;
  1483. }
  1484. } else if (class == BPF_LD) {
  1485. u8 mode = BPF_MODE(insn->code);
  1486. if (mode == BPF_ABS || mode == BPF_IND) {
  1487. verbose("LD_ABS is not supported yet\n");
  1488. return -EINVAL;
  1489. } else if (mode == BPF_IMM) {
  1490. err = check_ld_imm(env, insn);
  1491. if (err)
  1492. return err;
  1493. insn_idx++;
  1494. } else {
  1495. verbose("invalid BPF_LD mode\n");
  1496. return -EINVAL;
  1497. }
  1498. } else {
  1499. verbose("unknown insn class %d\n", class);
  1500. return -EINVAL;
  1501. }
  1502. insn_idx++;
  1503. }
  1504. return 0;
  1505. }
  1506. /* look for pseudo eBPF instructions that access map FDs and
  1507. * replace them with actual map pointers
  1508. */
  1509. static int replace_map_fd_with_map_ptr(struct verifier_env *env)
  1510. {
  1511. struct bpf_insn *insn = env->prog->insnsi;
  1512. int insn_cnt = env->prog->len;
  1513. int i, j;
  1514. for (i = 0; i < insn_cnt; i++, insn++) {
  1515. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  1516. struct bpf_map *map;
  1517. struct fd f;
  1518. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  1519. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  1520. insn[1].off != 0) {
  1521. verbose("invalid bpf_ld_imm64 insn\n");
  1522. return -EINVAL;
  1523. }
  1524. if (insn->src_reg == 0)
  1525. /* valid generic load 64-bit imm */
  1526. goto next_insn;
  1527. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  1528. verbose("unrecognized bpf_ld_imm64 insn\n");
  1529. return -EINVAL;
  1530. }
  1531. f = fdget(insn->imm);
  1532. map = bpf_map_get(f);
  1533. if (IS_ERR(map)) {
  1534. verbose("fd %d is not pointing to valid bpf_map\n",
  1535. insn->imm);
  1536. fdput(f);
  1537. return PTR_ERR(map);
  1538. }
  1539. /* store map pointer inside BPF_LD_IMM64 instruction */
  1540. insn[0].imm = (u32) (unsigned long) map;
  1541. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  1542. /* check whether we recorded this map already */
  1543. for (j = 0; j < env->used_map_cnt; j++)
  1544. if (env->used_maps[j] == map) {
  1545. fdput(f);
  1546. goto next_insn;
  1547. }
  1548. if (env->used_map_cnt >= MAX_USED_MAPS) {
  1549. fdput(f);
  1550. return -E2BIG;
  1551. }
  1552. /* remember this map */
  1553. env->used_maps[env->used_map_cnt++] = map;
  1554. /* hold the map. If the program is rejected by verifier,
  1555. * the map will be released by release_maps() or it
  1556. * will be used by the valid program until it's unloaded
  1557. * and all maps are released in free_bpf_prog_info()
  1558. */
  1559. atomic_inc(&map->refcnt);
  1560. fdput(f);
  1561. next_insn:
  1562. insn++;
  1563. i++;
  1564. }
  1565. }
  1566. /* now all pseudo BPF_LD_IMM64 instructions load valid
  1567. * 'struct bpf_map *' into a register instead of user map_fd.
  1568. * These pointers will be used later by verifier to validate map access.
  1569. */
  1570. return 0;
  1571. }
  1572. /* drop refcnt of maps used by the rejected program */
  1573. static void release_maps(struct verifier_env *env)
  1574. {
  1575. int i;
  1576. for (i = 0; i < env->used_map_cnt; i++)
  1577. bpf_map_put(env->used_maps[i]);
  1578. }
  1579. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  1580. static void convert_pseudo_ld_imm64(struct verifier_env *env)
  1581. {
  1582. struct bpf_insn *insn = env->prog->insnsi;
  1583. int insn_cnt = env->prog->len;
  1584. int i;
  1585. for (i = 0; i < insn_cnt; i++, insn++)
  1586. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  1587. insn->src_reg = 0;
  1588. }
  1589. static void free_states(struct verifier_env *env)
  1590. {
  1591. struct verifier_state_list *sl, *sln;
  1592. int i;
  1593. if (!env->explored_states)
  1594. return;
  1595. for (i = 0; i < env->prog->len; i++) {
  1596. sl = env->explored_states[i];
  1597. if (sl)
  1598. while (sl != STATE_LIST_MARK) {
  1599. sln = sl->next;
  1600. kfree(sl);
  1601. sl = sln;
  1602. }
  1603. }
  1604. kfree(env->explored_states);
  1605. }
  1606. int bpf_check(struct bpf_prog *prog, union bpf_attr *attr)
  1607. {
  1608. char __user *log_ubuf = NULL;
  1609. struct verifier_env *env;
  1610. int ret = -EINVAL;
  1611. if (prog->len <= 0 || prog->len > BPF_MAXINSNS)
  1612. return -E2BIG;
  1613. /* 'struct verifier_env' can be global, but since it's not small,
  1614. * allocate/free it every time bpf_check() is called
  1615. */
  1616. env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL);
  1617. if (!env)
  1618. return -ENOMEM;
  1619. env->prog = prog;
  1620. /* grab the mutex to protect few globals used by verifier */
  1621. mutex_lock(&bpf_verifier_lock);
  1622. if (attr->log_level || attr->log_buf || attr->log_size) {
  1623. /* user requested verbose verifier output
  1624. * and supplied buffer to store the verification trace
  1625. */
  1626. log_level = attr->log_level;
  1627. log_ubuf = (char __user *) (unsigned long) attr->log_buf;
  1628. log_size = attr->log_size;
  1629. log_len = 0;
  1630. ret = -EINVAL;
  1631. /* log_* values have to be sane */
  1632. if (log_size < 128 || log_size > UINT_MAX >> 8 ||
  1633. log_level == 0 || log_ubuf == NULL)
  1634. goto free_env;
  1635. ret = -ENOMEM;
  1636. log_buf = vmalloc(log_size);
  1637. if (!log_buf)
  1638. goto free_env;
  1639. } else {
  1640. log_level = 0;
  1641. }
  1642. ret = replace_map_fd_with_map_ptr(env);
  1643. if (ret < 0)
  1644. goto skip_full_check;
  1645. env->explored_states = kcalloc(prog->len,
  1646. sizeof(struct verifier_state_list *),
  1647. GFP_USER);
  1648. ret = -ENOMEM;
  1649. if (!env->explored_states)
  1650. goto skip_full_check;
  1651. ret = check_cfg(env);
  1652. if (ret < 0)
  1653. goto skip_full_check;
  1654. ret = do_check(env);
  1655. skip_full_check:
  1656. while (pop_stack(env, NULL) >= 0);
  1657. free_states(env);
  1658. if (log_level && log_len >= log_size - 1) {
  1659. BUG_ON(log_len >= log_size);
  1660. /* verifier log exceeded user supplied buffer */
  1661. ret = -ENOSPC;
  1662. /* fall through to return what was recorded */
  1663. }
  1664. /* copy verifier log back to user space including trailing zero */
  1665. if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
  1666. ret = -EFAULT;
  1667. goto free_log_buf;
  1668. }
  1669. if (ret == 0 && env->used_map_cnt) {
  1670. /* if program passed verifier, update used_maps in bpf_prog_info */
  1671. prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  1672. sizeof(env->used_maps[0]),
  1673. GFP_KERNEL);
  1674. if (!prog->aux->used_maps) {
  1675. ret = -ENOMEM;
  1676. goto free_log_buf;
  1677. }
  1678. memcpy(prog->aux->used_maps, env->used_maps,
  1679. sizeof(env->used_maps[0]) * env->used_map_cnt);
  1680. prog->aux->used_map_cnt = env->used_map_cnt;
  1681. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  1682. * bpf_ld_imm64 instructions
  1683. */
  1684. convert_pseudo_ld_imm64(env);
  1685. }
  1686. free_log_buf:
  1687. if (log_level)
  1688. vfree(log_buf);
  1689. free_env:
  1690. if (!prog->aux->used_maps)
  1691. /* if we didn't copy map pointers into bpf_prog_info, release
  1692. * them now. Otherwise free_bpf_prog_info() will release them.
  1693. */
  1694. release_maps(env);
  1695. kfree(env);
  1696. mutex_unlock(&bpf_verifier_lock);
  1697. return ret;
  1698. }