verifier.c 55 KB

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