verifier.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186
  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. if (state->regs[regno].type == PTR_TO_STACK)
  594. off += state->regs[regno].imm;
  595. size = bpf_size_to_bytes(bpf_size);
  596. if (size < 0)
  597. return size;
  598. if (off % size != 0) {
  599. verbose("misaligned access off %d size %d\n", off, size);
  600. return -EACCES;
  601. }
  602. if (state->regs[regno].type == PTR_TO_MAP_VALUE) {
  603. err = check_map_access(env, regno, off, size);
  604. if (!err && t == BPF_READ && value_regno >= 0)
  605. mark_reg_unknown_value(state->regs, value_regno);
  606. } else if (state->regs[regno].type == PTR_TO_CTX) {
  607. err = check_ctx_access(env, off, size, t);
  608. if (!err && t == BPF_READ && value_regno >= 0)
  609. mark_reg_unknown_value(state->regs, value_regno);
  610. } else if (state->regs[regno].type == FRAME_PTR ||
  611. state->regs[regno].type == PTR_TO_STACK) {
  612. if (off >= 0 || off < -MAX_BPF_STACK) {
  613. verbose("invalid stack off=%d size=%d\n", off, size);
  614. return -EACCES;
  615. }
  616. if (t == BPF_WRITE)
  617. err = check_stack_write(state, off, size, value_regno);
  618. else
  619. err = check_stack_read(state, off, size, value_regno);
  620. } else {
  621. verbose("R%d invalid mem access '%s'\n",
  622. regno, reg_type_str[state->regs[regno].type]);
  623. return -EACCES;
  624. }
  625. return err;
  626. }
  627. static int check_xadd(struct verifier_env *env, struct bpf_insn *insn)
  628. {
  629. struct reg_state *regs = env->cur_state.regs;
  630. int err;
  631. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  632. insn->imm != 0) {
  633. verbose("BPF_XADD uses reserved fields\n");
  634. return -EINVAL;
  635. }
  636. /* check src1 operand */
  637. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  638. if (err)
  639. return err;
  640. /* check src2 operand */
  641. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  642. if (err)
  643. return err;
  644. /* check whether atomic_add can read the memory */
  645. err = check_mem_access(env, insn->dst_reg, insn->off,
  646. BPF_SIZE(insn->code), BPF_READ, -1);
  647. if (err)
  648. return err;
  649. /* check whether atomic_add can write into the same memory */
  650. return check_mem_access(env, insn->dst_reg, insn->off,
  651. BPF_SIZE(insn->code), BPF_WRITE, -1);
  652. }
  653. /* when register 'regno' is passed into function that will read 'access_size'
  654. * bytes from that pointer, make sure that it's within stack boundary
  655. * and all elements of stack are initialized
  656. */
  657. static int check_stack_boundary(struct verifier_env *env,
  658. int regno, int access_size)
  659. {
  660. struct verifier_state *state = &env->cur_state;
  661. struct reg_state *regs = state->regs;
  662. int off, i;
  663. if (regs[regno].type != PTR_TO_STACK)
  664. return -EACCES;
  665. off = regs[regno].imm;
  666. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  667. access_size <= 0) {
  668. verbose("invalid stack type R%d off=%d access_size=%d\n",
  669. regno, off, access_size);
  670. return -EACCES;
  671. }
  672. for (i = 0; i < access_size; i++) {
  673. if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
  674. verbose("invalid indirect read from stack off %d+%d size %d\n",
  675. off, i, access_size);
  676. return -EACCES;
  677. }
  678. }
  679. return 0;
  680. }
  681. static int check_func_arg(struct verifier_env *env, u32 regno,
  682. enum bpf_arg_type arg_type, struct bpf_map **mapp)
  683. {
  684. struct reg_state *reg = env->cur_state.regs + regno;
  685. enum bpf_reg_type expected_type;
  686. int err = 0;
  687. if (arg_type == ARG_DONTCARE)
  688. return 0;
  689. if (reg->type == NOT_INIT) {
  690. verbose("R%d !read_ok\n", regno);
  691. return -EACCES;
  692. }
  693. if (arg_type == ARG_ANYTHING)
  694. return 0;
  695. if (arg_type == ARG_PTR_TO_STACK || arg_type == ARG_PTR_TO_MAP_KEY ||
  696. arg_type == ARG_PTR_TO_MAP_VALUE) {
  697. expected_type = PTR_TO_STACK;
  698. } else if (arg_type == ARG_CONST_STACK_SIZE) {
  699. expected_type = CONST_IMM;
  700. } else if (arg_type == ARG_CONST_MAP_PTR) {
  701. expected_type = CONST_PTR_TO_MAP;
  702. } else if (arg_type == ARG_PTR_TO_CTX) {
  703. expected_type = PTR_TO_CTX;
  704. } else {
  705. verbose("unsupported arg_type %d\n", arg_type);
  706. return -EFAULT;
  707. }
  708. if (reg->type != expected_type) {
  709. verbose("R%d type=%s expected=%s\n", regno,
  710. reg_type_str[reg->type], reg_type_str[expected_type]);
  711. return -EACCES;
  712. }
  713. if (arg_type == ARG_CONST_MAP_PTR) {
  714. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  715. *mapp = reg->map_ptr;
  716. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  717. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  718. * check that [key, key + map->key_size) are within
  719. * stack limits and initialized
  720. */
  721. if (!*mapp) {
  722. /* in function declaration map_ptr must come before
  723. * map_key, so that it's verified and known before
  724. * we have to check map_key here. Otherwise it means
  725. * that kernel subsystem misconfigured verifier
  726. */
  727. verbose("invalid map_ptr to access map->key\n");
  728. return -EACCES;
  729. }
  730. err = check_stack_boundary(env, regno, (*mapp)->key_size);
  731. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  732. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  733. * check [value, value + map->value_size) validity
  734. */
  735. if (!*mapp) {
  736. /* kernel subsystem misconfigured verifier */
  737. verbose("invalid map_ptr to access map->value\n");
  738. return -EACCES;
  739. }
  740. err = check_stack_boundary(env, regno, (*mapp)->value_size);
  741. } else if (arg_type == ARG_CONST_STACK_SIZE) {
  742. /* bpf_xxx(..., buf, len) call will access 'len' bytes
  743. * from stack pointer 'buf'. Check it
  744. * note: regno == len, regno - 1 == buf
  745. */
  746. if (regno == 0) {
  747. /* kernel subsystem misconfigured verifier */
  748. verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
  749. return -EACCES;
  750. }
  751. err = check_stack_boundary(env, regno - 1, reg->imm);
  752. }
  753. return err;
  754. }
  755. static int check_call(struct verifier_env *env, int func_id)
  756. {
  757. struct verifier_state *state = &env->cur_state;
  758. const struct bpf_func_proto *fn = NULL;
  759. struct reg_state *regs = state->regs;
  760. struct bpf_map *map = NULL;
  761. struct reg_state *reg;
  762. int i, err;
  763. /* find function prototype */
  764. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  765. verbose("invalid func %d\n", func_id);
  766. return -EINVAL;
  767. }
  768. if (env->prog->aux->ops->get_func_proto)
  769. fn = env->prog->aux->ops->get_func_proto(func_id);
  770. if (!fn) {
  771. verbose("unknown func %d\n", func_id);
  772. return -EINVAL;
  773. }
  774. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  775. if (!env->prog->gpl_compatible && fn->gpl_only) {
  776. verbose("cannot call GPL only function from proprietary program\n");
  777. return -EINVAL;
  778. }
  779. /* check args */
  780. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &map);
  781. if (err)
  782. return err;
  783. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &map);
  784. if (err)
  785. return err;
  786. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &map);
  787. if (err)
  788. return err;
  789. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &map);
  790. if (err)
  791. return err;
  792. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &map);
  793. if (err)
  794. return err;
  795. /* reset caller saved regs */
  796. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  797. reg = regs + caller_saved[i];
  798. reg->type = NOT_INIT;
  799. reg->imm = 0;
  800. }
  801. /* update return register */
  802. if (fn->ret_type == RET_INTEGER) {
  803. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  804. } else if (fn->ret_type == RET_VOID) {
  805. regs[BPF_REG_0].type = NOT_INIT;
  806. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  807. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  808. /* remember map_ptr, so that check_map_access()
  809. * can check 'value_size' boundary of memory access
  810. * to map element returned from bpf_map_lookup_elem()
  811. */
  812. if (map == NULL) {
  813. verbose("kernel subsystem misconfigured verifier\n");
  814. return -EINVAL;
  815. }
  816. regs[BPF_REG_0].map_ptr = map;
  817. } else {
  818. verbose("unknown return type %d of func %d\n",
  819. fn->ret_type, func_id);
  820. return -EINVAL;
  821. }
  822. if (map && map->map_type == BPF_MAP_TYPE_PROG_ARRAY &&
  823. func_id != BPF_FUNC_tail_call)
  824. /* prog_array map type needs extra care:
  825. * only allow to pass it into bpf_tail_call() for now.
  826. * bpf_map_delete_elem() can be allowed in the future,
  827. * while bpf_map_update_elem() must only be done via syscall
  828. */
  829. return -EINVAL;
  830. if (func_id == BPF_FUNC_tail_call &&
  831. map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  832. /* don't allow any other map type to be passed into
  833. * bpf_tail_call()
  834. */
  835. return -EINVAL;
  836. return 0;
  837. }
  838. /* check validity of 32-bit and 64-bit arithmetic operations */
  839. static int check_alu_op(struct reg_state *regs, struct bpf_insn *insn)
  840. {
  841. u8 opcode = BPF_OP(insn->code);
  842. int err;
  843. if (opcode == BPF_END || opcode == BPF_NEG) {
  844. if (opcode == BPF_NEG) {
  845. if (BPF_SRC(insn->code) != 0 ||
  846. insn->src_reg != BPF_REG_0 ||
  847. insn->off != 0 || insn->imm != 0) {
  848. verbose("BPF_NEG uses reserved fields\n");
  849. return -EINVAL;
  850. }
  851. } else {
  852. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  853. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
  854. verbose("BPF_END uses reserved fields\n");
  855. return -EINVAL;
  856. }
  857. }
  858. /* check src operand */
  859. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  860. if (err)
  861. return err;
  862. /* check dest operand */
  863. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  864. if (err)
  865. return err;
  866. } else if (opcode == BPF_MOV) {
  867. if (BPF_SRC(insn->code) == BPF_X) {
  868. if (insn->imm != 0 || insn->off != 0) {
  869. verbose("BPF_MOV uses reserved fields\n");
  870. return -EINVAL;
  871. }
  872. /* check src operand */
  873. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  874. if (err)
  875. return err;
  876. } else {
  877. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  878. verbose("BPF_MOV uses reserved fields\n");
  879. return -EINVAL;
  880. }
  881. }
  882. /* check dest operand */
  883. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  884. if (err)
  885. return err;
  886. if (BPF_SRC(insn->code) == BPF_X) {
  887. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  888. /* case: R1 = R2
  889. * copy register state to dest reg
  890. */
  891. regs[insn->dst_reg] = regs[insn->src_reg];
  892. } else {
  893. regs[insn->dst_reg].type = UNKNOWN_VALUE;
  894. regs[insn->dst_reg].map_ptr = NULL;
  895. }
  896. } else {
  897. /* case: R = imm
  898. * remember the value we stored into this reg
  899. */
  900. regs[insn->dst_reg].type = CONST_IMM;
  901. regs[insn->dst_reg].imm = insn->imm;
  902. }
  903. } else if (opcode > BPF_END) {
  904. verbose("invalid BPF_ALU opcode %x\n", opcode);
  905. return -EINVAL;
  906. } else { /* all other ALU ops: and, sub, xor, add, ... */
  907. bool stack_relative = false;
  908. if (BPF_SRC(insn->code) == BPF_X) {
  909. if (insn->imm != 0 || insn->off != 0) {
  910. verbose("BPF_ALU uses reserved fields\n");
  911. return -EINVAL;
  912. }
  913. /* check src1 operand */
  914. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  915. if (err)
  916. return err;
  917. } else {
  918. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  919. verbose("BPF_ALU uses reserved fields\n");
  920. return -EINVAL;
  921. }
  922. }
  923. /* check src2 operand */
  924. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  925. if (err)
  926. return err;
  927. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  928. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  929. verbose("div by zero\n");
  930. return -EINVAL;
  931. }
  932. /* pattern match 'bpf_add Rx, imm' instruction */
  933. if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
  934. regs[insn->dst_reg].type == FRAME_PTR &&
  935. BPF_SRC(insn->code) == BPF_K)
  936. stack_relative = true;
  937. /* check dest operand */
  938. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  939. if (err)
  940. return err;
  941. if (stack_relative) {
  942. regs[insn->dst_reg].type = PTR_TO_STACK;
  943. regs[insn->dst_reg].imm = insn->imm;
  944. }
  945. }
  946. return 0;
  947. }
  948. static int check_cond_jmp_op(struct verifier_env *env,
  949. struct bpf_insn *insn, int *insn_idx)
  950. {
  951. struct reg_state *regs = env->cur_state.regs;
  952. struct verifier_state *other_branch;
  953. u8 opcode = BPF_OP(insn->code);
  954. int err;
  955. if (opcode > BPF_EXIT) {
  956. verbose("invalid BPF_JMP opcode %x\n", opcode);
  957. return -EINVAL;
  958. }
  959. if (BPF_SRC(insn->code) == BPF_X) {
  960. if (insn->imm != 0) {
  961. verbose("BPF_JMP uses reserved fields\n");
  962. return -EINVAL;
  963. }
  964. /* check src1 operand */
  965. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  966. if (err)
  967. return err;
  968. } else {
  969. if (insn->src_reg != BPF_REG_0) {
  970. verbose("BPF_JMP uses reserved fields\n");
  971. return -EINVAL;
  972. }
  973. }
  974. /* check src2 operand */
  975. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  976. if (err)
  977. return err;
  978. /* detect if R == 0 where R was initialized to zero earlier */
  979. if (BPF_SRC(insn->code) == BPF_K &&
  980. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  981. regs[insn->dst_reg].type == CONST_IMM &&
  982. regs[insn->dst_reg].imm == insn->imm) {
  983. if (opcode == BPF_JEQ) {
  984. /* if (imm == imm) goto pc+off;
  985. * only follow the goto, ignore fall-through
  986. */
  987. *insn_idx += insn->off;
  988. return 0;
  989. } else {
  990. /* if (imm != imm) goto pc+off;
  991. * only follow fall-through branch, since
  992. * that's where the program will go
  993. */
  994. return 0;
  995. }
  996. }
  997. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  998. if (!other_branch)
  999. return -EFAULT;
  1000. /* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
  1001. if (BPF_SRC(insn->code) == BPF_K &&
  1002. insn->imm == 0 && (opcode == BPF_JEQ ||
  1003. opcode == BPF_JNE) &&
  1004. regs[insn->dst_reg].type == PTR_TO_MAP_VALUE_OR_NULL) {
  1005. if (opcode == BPF_JEQ) {
  1006. /* next fallthrough insn can access memory via
  1007. * this register
  1008. */
  1009. regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1010. /* branch targer cannot access it, since reg == 0 */
  1011. other_branch->regs[insn->dst_reg].type = CONST_IMM;
  1012. other_branch->regs[insn->dst_reg].imm = 0;
  1013. } else {
  1014. other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1015. regs[insn->dst_reg].type = CONST_IMM;
  1016. regs[insn->dst_reg].imm = 0;
  1017. }
  1018. } else if (BPF_SRC(insn->code) == BPF_K &&
  1019. (opcode == BPF_JEQ || opcode == BPF_JNE)) {
  1020. if (opcode == BPF_JEQ) {
  1021. /* detect if (R == imm) goto
  1022. * and in the target state recognize that R = imm
  1023. */
  1024. other_branch->regs[insn->dst_reg].type = CONST_IMM;
  1025. other_branch->regs[insn->dst_reg].imm = insn->imm;
  1026. } else {
  1027. /* detect if (R != imm) goto
  1028. * and in the fall-through state recognize that R = imm
  1029. */
  1030. regs[insn->dst_reg].type = CONST_IMM;
  1031. regs[insn->dst_reg].imm = insn->imm;
  1032. }
  1033. }
  1034. if (log_level)
  1035. print_verifier_state(env);
  1036. return 0;
  1037. }
  1038. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  1039. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  1040. {
  1041. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  1042. return (struct bpf_map *) (unsigned long) imm64;
  1043. }
  1044. /* verify BPF_LD_IMM64 instruction */
  1045. static int check_ld_imm(struct verifier_env *env, struct bpf_insn *insn)
  1046. {
  1047. struct reg_state *regs = env->cur_state.regs;
  1048. int err;
  1049. if (BPF_SIZE(insn->code) != BPF_DW) {
  1050. verbose("invalid BPF_LD_IMM insn\n");
  1051. return -EINVAL;
  1052. }
  1053. if (insn->off != 0) {
  1054. verbose("BPF_LD_IMM64 uses reserved fields\n");
  1055. return -EINVAL;
  1056. }
  1057. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1058. if (err)
  1059. return err;
  1060. if (insn->src_reg == 0)
  1061. /* generic move 64-bit immediate into a register */
  1062. return 0;
  1063. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  1064. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  1065. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  1066. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  1067. return 0;
  1068. }
  1069. static bool may_access_skb(enum bpf_prog_type type)
  1070. {
  1071. switch (type) {
  1072. case BPF_PROG_TYPE_SOCKET_FILTER:
  1073. case BPF_PROG_TYPE_SCHED_CLS:
  1074. case BPF_PROG_TYPE_SCHED_ACT:
  1075. return true;
  1076. default:
  1077. return false;
  1078. }
  1079. }
  1080. /* verify safety of LD_ABS|LD_IND instructions:
  1081. * - they can only appear in the programs where ctx == skb
  1082. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  1083. * preserve R6-R9, and store return value into R0
  1084. *
  1085. * Implicit input:
  1086. * ctx == skb == R6 == CTX
  1087. *
  1088. * Explicit input:
  1089. * SRC == any register
  1090. * IMM == 32-bit immediate
  1091. *
  1092. * Output:
  1093. * R0 - 8/16/32-bit skb data converted to cpu endianness
  1094. */
  1095. static int check_ld_abs(struct verifier_env *env, struct bpf_insn *insn)
  1096. {
  1097. struct reg_state *regs = env->cur_state.regs;
  1098. u8 mode = BPF_MODE(insn->code);
  1099. struct reg_state *reg;
  1100. int i, err;
  1101. if (!may_access_skb(env->prog->type)) {
  1102. verbose("BPF_LD_ABS|IND instructions not allowed for this program type\n");
  1103. return -EINVAL;
  1104. }
  1105. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  1106. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  1107. verbose("BPF_LD_ABS uses reserved fields\n");
  1108. return -EINVAL;
  1109. }
  1110. /* check whether implicit source operand (register R6) is readable */
  1111. err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
  1112. if (err)
  1113. return err;
  1114. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  1115. verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  1116. return -EINVAL;
  1117. }
  1118. if (mode == BPF_IND) {
  1119. /* check explicit source operand */
  1120. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1121. if (err)
  1122. return err;
  1123. }
  1124. /* reset caller saved regs to unreadable */
  1125. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  1126. reg = regs + caller_saved[i];
  1127. reg->type = NOT_INIT;
  1128. reg->imm = 0;
  1129. }
  1130. /* mark destination R0 register as readable, since it contains
  1131. * the value fetched from the packet
  1132. */
  1133. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  1134. return 0;
  1135. }
  1136. /* non-recursive DFS pseudo code
  1137. * 1 procedure DFS-iterative(G,v):
  1138. * 2 label v as discovered
  1139. * 3 let S be a stack
  1140. * 4 S.push(v)
  1141. * 5 while S is not empty
  1142. * 6 t <- S.pop()
  1143. * 7 if t is what we're looking for:
  1144. * 8 return t
  1145. * 9 for all edges e in G.adjacentEdges(t) do
  1146. * 10 if edge e is already labelled
  1147. * 11 continue with the next edge
  1148. * 12 w <- G.adjacentVertex(t,e)
  1149. * 13 if vertex w is not discovered and not explored
  1150. * 14 label e as tree-edge
  1151. * 15 label w as discovered
  1152. * 16 S.push(w)
  1153. * 17 continue at 5
  1154. * 18 else if vertex w is discovered
  1155. * 19 label e as back-edge
  1156. * 20 else
  1157. * 21 // vertex w is explored
  1158. * 22 label e as forward- or cross-edge
  1159. * 23 label t as explored
  1160. * 24 S.pop()
  1161. *
  1162. * convention:
  1163. * 0x10 - discovered
  1164. * 0x11 - discovered and fall-through edge labelled
  1165. * 0x12 - discovered and fall-through and branch edges labelled
  1166. * 0x20 - explored
  1167. */
  1168. enum {
  1169. DISCOVERED = 0x10,
  1170. EXPLORED = 0x20,
  1171. FALLTHROUGH = 1,
  1172. BRANCH = 2,
  1173. };
  1174. #define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
  1175. static int *insn_stack; /* stack of insns to process */
  1176. static int cur_stack; /* current stack index */
  1177. static int *insn_state;
  1178. /* t, w, e - match pseudo-code above:
  1179. * t - index of current instruction
  1180. * w - next instruction
  1181. * e - edge
  1182. */
  1183. static int push_insn(int t, int w, int e, struct verifier_env *env)
  1184. {
  1185. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  1186. return 0;
  1187. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  1188. return 0;
  1189. if (w < 0 || w >= env->prog->len) {
  1190. verbose("jump out of range from insn %d to %d\n", t, w);
  1191. return -EINVAL;
  1192. }
  1193. if (e == BRANCH)
  1194. /* mark branch target for state pruning */
  1195. env->explored_states[w] = STATE_LIST_MARK;
  1196. if (insn_state[w] == 0) {
  1197. /* tree-edge */
  1198. insn_state[t] = DISCOVERED | e;
  1199. insn_state[w] = DISCOVERED;
  1200. if (cur_stack >= env->prog->len)
  1201. return -E2BIG;
  1202. insn_stack[cur_stack++] = w;
  1203. return 1;
  1204. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  1205. verbose("back-edge from insn %d to %d\n", t, w);
  1206. return -EINVAL;
  1207. } else if (insn_state[w] == EXPLORED) {
  1208. /* forward- or cross-edge */
  1209. insn_state[t] = DISCOVERED | e;
  1210. } else {
  1211. verbose("insn state internal bug\n");
  1212. return -EFAULT;
  1213. }
  1214. return 0;
  1215. }
  1216. /* non-recursive depth-first-search to detect loops in BPF program
  1217. * loop == back-edge in directed graph
  1218. */
  1219. static int check_cfg(struct verifier_env *env)
  1220. {
  1221. struct bpf_insn *insns = env->prog->insnsi;
  1222. int insn_cnt = env->prog->len;
  1223. int ret = 0;
  1224. int i, t;
  1225. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1226. if (!insn_state)
  1227. return -ENOMEM;
  1228. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1229. if (!insn_stack) {
  1230. kfree(insn_state);
  1231. return -ENOMEM;
  1232. }
  1233. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  1234. insn_stack[0] = 0; /* 0 is the first instruction */
  1235. cur_stack = 1;
  1236. peek_stack:
  1237. if (cur_stack == 0)
  1238. goto check_state;
  1239. t = insn_stack[cur_stack - 1];
  1240. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  1241. u8 opcode = BPF_OP(insns[t].code);
  1242. if (opcode == BPF_EXIT) {
  1243. goto mark_explored;
  1244. } else if (opcode == BPF_CALL) {
  1245. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1246. if (ret == 1)
  1247. goto peek_stack;
  1248. else if (ret < 0)
  1249. goto err_free;
  1250. } else if (opcode == BPF_JA) {
  1251. if (BPF_SRC(insns[t].code) != BPF_K) {
  1252. ret = -EINVAL;
  1253. goto err_free;
  1254. }
  1255. /* unconditional jump with single edge */
  1256. ret = push_insn(t, t + insns[t].off + 1,
  1257. FALLTHROUGH, env);
  1258. if (ret == 1)
  1259. goto peek_stack;
  1260. else if (ret < 0)
  1261. goto err_free;
  1262. /* tell verifier to check for equivalent states
  1263. * after every call and jump
  1264. */
  1265. if (t + 1 < insn_cnt)
  1266. env->explored_states[t + 1] = STATE_LIST_MARK;
  1267. } else {
  1268. /* conditional jump with two edges */
  1269. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1270. if (ret == 1)
  1271. goto peek_stack;
  1272. else if (ret < 0)
  1273. goto err_free;
  1274. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  1275. if (ret == 1)
  1276. goto peek_stack;
  1277. else if (ret < 0)
  1278. goto err_free;
  1279. }
  1280. } else {
  1281. /* all other non-branch instructions with single
  1282. * fall-through edge
  1283. */
  1284. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1285. if (ret == 1)
  1286. goto peek_stack;
  1287. else if (ret < 0)
  1288. goto err_free;
  1289. }
  1290. mark_explored:
  1291. insn_state[t] = EXPLORED;
  1292. if (cur_stack-- <= 0) {
  1293. verbose("pop stack internal bug\n");
  1294. ret = -EFAULT;
  1295. goto err_free;
  1296. }
  1297. goto peek_stack;
  1298. check_state:
  1299. for (i = 0; i < insn_cnt; i++) {
  1300. if (insn_state[i] != EXPLORED) {
  1301. verbose("unreachable insn %d\n", i);
  1302. ret = -EINVAL;
  1303. goto err_free;
  1304. }
  1305. }
  1306. ret = 0; /* cfg looks good */
  1307. err_free:
  1308. kfree(insn_state);
  1309. kfree(insn_stack);
  1310. return ret;
  1311. }
  1312. /* compare two verifier states
  1313. *
  1314. * all states stored in state_list are known to be valid, since
  1315. * verifier reached 'bpf_exit' instruction through them
  1316. *
  1317. * this function is called when verifier exploring different branches of
  1318. * execution popped from the state stack. If it sees an old state that has
  1319. * more strict register state and more strict stack state then this execution
  1320. * branch doesn't need to be explored further, since verifier already
  1321. * concluded that more strict state leads to valid finish.
  1322. *
  1323. * Therefore two states are equivalent if register state is more conservative
  1324. * and explored stack state is more conservative than the current one.
  1325. * Example:
  1326. * explored current
  1327. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  1328. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  1329. *
  1330. * In other words if current stack state (one being explored) has more
  1331. * valid slots than old one that already passed validation, it means
  1332. * the verifier can stop exploring and conclude that current state is valid too
  1333. *
  1334. * Similarly with registers. If explored state has register type as invalid
  1335. * whereas register type in current state is meaningful, it means that
  1336. * the current state will reach 'bpf_exit' instruction safely
  1337. */
  1338. static bool states_equal(struct verifier_state *old, struct verifier_state *cur)
  1339. {
  1340. int i;
  1341. for (i = 0; i < MAX_BPF_REG; i++) {
  1342. if (memcmp(&old->regs[i], &cur->regs[i],
  1343. sizeof(old->regs[0])) != 0) {
  1344. if (old->regs[i].type == NOT_INIT ||
  1345. (old->regs[i].type == UNKNOWN_VALUE &&
  1346. cur->regs[i].type != NOT_INIT))
  1347. continue;
  1348. return false;
  1349. }
  1350. }
  1351. for (i = 0; i < MAX_BPF_STACK; i++) {
  1352. if (old->stack_slot_type[i] == STACK_INVALID)
  1353. continue;
  1354. if (old->stack_slot_type[i] != cur->stack_slot_type[i])
  1355. /* Ex: old explored (safe) state has STACK_SPILL in
  1356. * this stack slot, but current has has STACK_MISC ->
  1357. * this verifier states are not equivalent,
  1358. * return false to continue verification of this path
  1359. */
  1360. return false;
  1361. if (i % BPF_REG_SIZE)
  1362. continue;
  1363. if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
  1364. &cur->spilled_regs[i / BPF_REG_SIZE],
  1365. sizeof(old->spilled_regs[0])))
  1366. /* when explored and current stack slot types are
  1367. * the same, check that stored pointers types
  1368. * are the same as well.
  1369. * Ex: explored safe path could have stored
  1370. * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8}
  1371. * but current path has stored:
  1372. * (struct reg_state) {.type = PTR_TO_STACK, .imm = -16}
  1373. * such verifier states are not equivalent.
  1374. * return false to continue verification of this path
  1375. */
  1376. return false;
  1377. else
  1378. continue;
  1379. }
  1380. return true;
  1381. }
  1382. static int is_state_visited(struct verifier_env *env, int insn_idx)
  1383. {
  1384. struct verifier_state_list *new_sl;
  1385. struct verifier_state_list *sl;
  1386. sl = env->explored_states[insn_idx];
  1387. if (!sl)
  1388. /* this 'insn_idx' instruction wasn't marked, so we will not
  1389. * be doing state search here
  1390. */
  1391. return 0;
  1392. while (sl != STATE_LIST_MARK) {
  1393. if (states_equal(&sl->state, &env->cur_state))
  1394. /* reached equivalent register/stack state,
  1395. * prune the search
  1396. */
  1397. return 1;
  1398. sl = sl->next;
  1399. }
  1400. /* there were no equivalent states, remember current one.
  1401. * technically the current state is not proven to be safe yet,
  1402. * but it will either reach bpf_exit (which means it's safe) or
  1403. * it will be rejected. Since there are no loops, we won't be
  1404. * seeing this 'insn_idx' instruction again on the way to bpf_exit
  1405. */
  1406. new_sl = kmalloc(sizeof(struct verifier_state_list), GFP_USER);
  1407. if (!new_sl)
  1408. return -ENOMEM;
  1409. /* add new state to the head of linked list */
  1410. memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
  1411. new_sl->next = env->explored_states[insn_idx];
  1412. env->explored_states[insn_idx] = new_sl;
  1413. return 0;
  1414. }
  1415. static int do_check(struct verifier_env *env)
  1416. {
  1417. struct verifier_state *state = &env->cur_state;
  1418. struct bpf_insn *insns = env->prog->insnsi;
  1419. struct reg_state *regs = state->regs;
  1420. int insn_cnt = env->prog->len;
  1421. int insn_idx, prev_insn_idx = 0;
  1422. int insn_processed = 0;
  1423. bool do_print_state = false;
  1424. init_reg_state(regs);
  1425. insn_idx = 0;
  1426. for (;;) {
  1427. struct bpf_insn *insn;
  1428. u8 class;
  1429. int err;
  1430. if (insn_idx >= insn_cnt) {
  1431. verbose("invalid insn idx %d insn_cnt %d\n",
  1432. insn_idx, insn_cnt);
  1433. return -EFAULT;
  1434. }
  1435. insn = &insns[insn_idx];
  1436. class = BPF_CLASS(insn->code);
  1437. if (++insn_processed > 32768) {
  1438. verbose("BPF program is too large. Proccessed %d insn\n",
  1439. insn_processed);
  1440. return -E2BIG;
  1441. }
  1442. err = is_state_visited(env, insn_idx);
  1443. if (err < 0)
  1444. return err;
  1445. if (err == 1) {
  1446. /* found equivalent state, can prune the search */
  1447. if (log_level) {
  1448. if (do_print_state)
  1449. verbose("\nfrom %d to %d: safe\n",
  1450. prev_insn_idx, insn_idx);
  1451. else
  1452. verbose("%d: safe\n", insn_idx);
  1453. }
  1454. goto process_bpf_exit;
  1455. }
  1456. if (log_level && do_print_state) {
  1457. verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
  1458. print_verifier_state(env);
  1459. do_print_state = false;
  1460. }
  1461. if (log_level) {
  1462. verbose("%d: ", insn_idx);
  1463. print_bpf_insn(insn);
  1464. }
  1465. if (class == BPF_ALU || class == BPF_ALU64) {
  1466. err = check_alu_op(regs, insn);
  1467. if (err)
  1468. return err;
  1469. } else if (class == BPF_LDX) {
  1470. enum bpf_reg_type src_reg_type;
  1471. /* check for reserved fields is already done */
  1472. /* check src operand */
  1473. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1474. if (err)
  1475. return err;
  1476. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  1477. if (err)
  1478. return err;
  1479. src_reg_type = regs[insn->src_reg].type;
  1480. /* check that memory (src_reg + off) is readable,
  1481. * the state of dst_reg will be updated by this func
  1482. */
  1483. err = check_mem_access(env, insn->src_reg, insn->off,
  1484. BPF_SIZE(insn->code), BPF_READ,
  1485. insn->dst_reg);
  1486. if (err)
  1487. return err;
  1488. if (BPF_SIZE(insn->code) != BPF_W) {
  1489. insn_idx++;
  1490. continue;
  1491. }
  1492. if (insn->imm == 0) {
  1493. /* saw a valid insn
  1494. * dst_reg = *(u32 *)(src_reg + off)
  1495. * use reserved 'imm' field to mark this insn
  1496. */
  1497. insn->imm = src_reg_type;
  1498. } else if (src_reg_type != insn->imm &&
  1499. (src_reg_type == PTR_TO_CTX ||
  1500. insn->imm == PTR_TO_CTX)) {
  1501. /* ABuser program is trying to use the same insn
  1502. * dst_reg = *(u32*) (src_reg + off)
  1503. * with different pointer types:
  1504. * src_reg == ctx in one branch and
  1505. * src_reg == stack|map in some other branch.
  1506. * Reject it.
  1507. */
  1508. verbose("same insn cannot be used with different pointers\n");
  1509. return -EINVAL;
  1510. }
  1511. } else if (class == BPF_STX) {
  1512. enum bpf_reg_type dst_reg_type;
  1513. if (BPF_MODE(insn->code) == BPF_XADD) {
  1514. err = check_xadd(env, insn);
  1515. if (err)
  1516. return err;
  1517. insn_idx++;
  1518. continue;
  1519. }
  1520. /* check src1 operand */
  1521. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1522. if (err)
  1523. return err;
  1524. /* check src2 operand */
  1525. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1526. if (err)
  1527. return err;
  1528. dst_reg_type = regs[insn->dst_reg].type;
  1529. /* check that memory (dst_reg + off) is writeable */
  1530. err = check_mem_access(env, insn->dst_reg, insn->off,
  1531. BPF_SIZE(insn->code), BPF_WRITE,
  1532. insn->src_reg);
  1533. if (err)
  1534. return err;
  1535. if (insn->imm == 0) {
  1536. insn->imm = dst_reg_type;
  1537. } else if (dst_reg_type != insn->imm &&
  1538. (dst_reg_type == PTR_TO_CTX ||
  1539. insn->imm == PTR_TO_CTX)) {
  1540. verbose("same insn cannot be used with different pointers\n");
  1541. return -EINVAL;
  1542. }
  1543. } else if (class == BPF_ST) {
  1544. if (BPF_MODE(insn->code) != BPF_MEM ||
  1545. insn->src_reg != BPF_REG_0) {
  1546. verbose("BPF_ST uses reserved fields\n");
  1547. return -EINVAL;
  1548. }
  1549. /* check src operand */
  1550. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1551. if (err)
  1552. return err;
  1553. /* check that memory (dst_reg + off) is writeable */
  1554. err = check_mem_access(env, insn->dst_reg, insn->off,
  1555. BPF_SIZE(insn->code), BPF_WRITE,
  1556. -1);
  1557. if (err)
  1558. return err;
  1559. } else if (class == BPF_JMP) {
  1560. u8 opcode = BPF_OP(insn->code);
  1561. if (opcode == BPF_CALL) {
  1562. if (BPF_SRC(insn->code) != BPF_K ||
  1563. insn->off != 0 ||
  1564. insn->src_reg != BPF_REG_0 ||
  1565. insn->dst_reg != BPF_REG_0) {
  1566. verbose("BPF_CALL uses reserved fields\n");
  1567. return -EINVAL;
  1568. }
  1569. err = check_call(env, insn->imm);
  1570. if (err)
  1571. return err;
  1572. } else if (opcode == BPF_JA) {
  1573. if (BPF_SRC(insn->code) != BPF_K ||
  1574. insn->imm != 0 ||
  1575. insn->src_reg != BPF_REG_0 ||
  1576. insn->dst_reg != BPF_REG_0) {
  1577. verbose("BPF_JA uses reserved fields\n");
  1578. return -EINVAL;
  1579. }
  1580. insn_idx += insn->off + 1;
  1581. continue;
  1582. } else if (opcode == BPF_EXIT) {
  1583. if (BPF_SRC(insn->code) != BPF_K ||
  1584. insn->imm != 0 ||
  1585. insn->src_reg != BPF_REG_0 ||
  1586. insn->dst_reg != BPF_REG_0) {
  1587. verbose("BPF_EXIT uses reserved fields\n");
  1588. return -EINVAL;
  1589. }
  1590. /* eBPF calling convetion is such that R0 is used
  1591. * to return the value from eBPF program.
  1592. * Make sure that it's readable at this time
  1593. * of bpf_exit, which means that program wrote
  1594. * something into it earlier
  1595. */
  1596. err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
  1597. if (err)
  1598. return err;
  1599. process_bpf_exit:
  1600. insn_idx = pop_stack(env, &prev_insn_idx);
  1601. if (insn_idx < 0) {
  1602. break;
  1603. } else {
  1604. do_print_state = true;
  1605. continue;
  1606. }
  1607. } else {
  1608. err = check_cond_jmp_op(env, insn, &insn_idx);
  1609. if (err)
  1610. return err;
  1611. }
  1612. } else if (class == BPF_LD) {
  1613. u8 mode = BPF_MODE(insn->code);
  1614. if (mode == BPF_ABS || mode == BPF_IND) {
  1615. err = check_ld_abs(env, insn);
  1616. if (err)
  1617. return err;
  1618. } else if (mode == BPF_IMM) {
  1619. err = check_ld_imm(env, insn);
  1620. if (err)
  1621. return err;
  1622. insn_idx++;
  1623. } else {
  1624. verbose("invalid BPF_LD mode\n");
  1625. return -EINVAL;
  1626. }
  1627. } else {
  1628. verbose("unknown insn class %d\n", class);
  1629. return -EINVAL;
  1630. }
  1631. insn_idx++;
  1632. }
  1633. return 0;
  1634. }
  1635. /* look for pseudo eBPF instructions that access map FDs and
  1636. * replace them with actual map pointers
  1637. */
  1638. static int replace_map_fd_with_map_ptr(struct verifier_env *env)
  1639. {
  1640. struct bpf_insn *insn = env->prog->insnsi;
  1641. int insn_cnt = env->prog->len;
  1642. int i, j;
  1643. for (i = 0; i < insn_cnt; i++, insn++) {
  1644. if (BPF_CLASS(insn->code) == BPF_LDX &&
  1645. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  1646. verbose("BPF_LDX uses reserved fields\n");
  1647. return -EINVAL;
  1648. }
  1649. if (BPF_CLASS(insn->code) == BPF_STX &&
  1650. ((BPF_MODE(insn->code) != BPF_MEM &&
  1651. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  1652. verbose("BPF_STX uses reserved fields\n");
  1653. return -EINVAL;
  1654. }
  1655. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  1656. struct bpf_map *map;
  1657. struct fd f;
  1658. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  1659. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  1660. insn[1].off != 0) {
  1661. verbose("invalid bpf_ld_imm64 insn\n");
  1662. return -EINVAL;
  1663. }
  1664. if (insn->src_reg == 0)
  1665. /* valid generic load 64-bit imm */
  1666. goto next_insn;
  1667. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  1668. verbose("unrecognized bpf_ld_imm64 insn\n");
  1669. return -EINVAL;
  1670. }
  1671. f = fdget(insn->imm);
  1672. map = bpf_map_get(f);
  1673. if (IS_ERR(map)) {
  1674. verbose("fd %d is not pointing to valid bpf_map\n",
  1675. insn->imm);
  1676. fdput(f);
  1677. return PTR_ERR(map);
  1678. }
  1679. /* store map pointer inside BPF_LD_IMM64 instruction */
  1680. insn[0].imm = (u32) (unsigned long) map;
  1681. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  1682. /* check whether we recorded this map already */
  1683. for (j = 0; j < env->used_map_cnt; j++)
  1684. if (env->used_maps[j] == map) {
  1685. fdput(f);
  1686. goto next_insn;
  1687. }
  1688. if (env->used_map_cnt >= MAX_USED_MAPS) {
  1689. fdput(f);
  1690. return -E2BIG;
  1691. }
  1692. /* remember this map */
  1693. env->used_maps[env->used_map_cnt++] = map;
  1694. /* hold the map. If the program is rejected by verifier,
  1695. * the map will be released by release_maps() or it
  1696. * will be used by the valid program until it's unloaded
  1697. * and all maps are released in free_bpf_prog_info()
  1698. */
  1699. atomic_inc(&map->refcnt);
  1700. fdput(f);
  1701. next_insn:
  1702. insn++;
  1703. i++;
  1704. }
  1705. }
  1706. /* now all pseudo BPF_LD_IMM64 instructions load valid
  1707. * 'struct bpf_map *' into a register instead of user map_fd.
  1708. * These pointers will be used later by verifier to validate map access.
  1709. */
  1710. return 0;
  1711. }
  1712. /* drop refcnt of maps used by the rejected program */
  1713. static void release_maps(struct verifier_env *env)
  1714. {
  1715. int i;
  1716. for (i = 0; i < env->used_map_cnt; i++)
  1717. bpf_map_put(env->used_maps[i]);
  1718. }
  1719. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  1720. static void convert_pseudo_ld_imm64(struct verifier_env *env)
  1721. {
  1722. struct bpf_insn *insn = env->prog->insnsi;
  1723. int insn_cnt = env->prog->len;
  1724. int i;
  1725. for (i = 0; i < insn_cnt; i++, insn++)
  1726. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  1727. insn->src_reg = 0;
  1728. }
  1729. static void adjust_branches(struct bpf_prog *prog, int pos, int delta)
  1730. {
  1731. struct bpf_insn *insn = prog->insnsi;
  1732. int insn_cnt = prog->len;
  1733. int i;
  1734. for (i = 0; i < insn_cnt; i++, insn++) {
  1735. if (BPF_CLASS(insn->code) != BPF_JMP ||
  1736. BPF_OP(insn->code) == BPF_CALL ||
  1737. BPF_OP(insn->code) == BPF_EXIT)
  1738. continue;
  1739. /* adjust offset of jmps if necessary */
  1740. if (i < pos && i + insn->off + 1 > pos)
  1741. insn->off += delta;
  1742. else if (i > pos && i + insn->off + 1 < pos)
  1743. insn->off -= delta;
  1744. }
  1745. }
  1746. /* convert load instructions that access fields of 'struct __sk_buff'
  1747. * into sequence of instructions that access fields of 'struct sk_buff'
  1748. */
  1749. static int convert_ctx_accesses(struct verifier_env *env)
  1750. {
  1751. struct bpf_insn *insn = env->prog->insnsi;
  1752. int insn_cnt = env->prog->len;
  1753. struct bpf_insn insn_buf[16];
  1754. struct bpf_prog *new_prog;
  1755. u32 cnt;
  1756. int i;
  1757. enum bpf_access_type type;
  1758. if (!env->prog->aux->ops->convert_ctx_access)
  1759. return 0;
  1760. for (i = 0; i < insn_cnt; i++, insn++) {
  1761. if (insn->code == (BPF_LDX | BPF_MEM | BPF_W))
  1762. type = BPF_READ;
  1763. else if (insn->code == (BPF_STX | BPF_MEM | BPF_W))
  1764. type = BPF_WRITE;
  1765. else
  1766. continue;
  1767. if (insn->imm != PTR_TO_CTX) {
  1768. /* clear internal mark */
  1769. insn->imm = 0;
  1770. continue;
  1771. }
  1772. cnt = env->prog->aux->ops->
  1773. convert_ctx_access(type, insn->dst_reg, insn->src_reg,
  1774. insn->off, insn_buf);
  1775. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  1776. verbose("bpf verifier is misconfigured\n");
  1777. return -EINVAL;
  1778. }
  1779. if (cnt == 1) {
  1780. memcpy(insn, insn_buf, sizeof(*insn));
  1781. continue;
  1782. }
  1783. /* several new insns need to be inserted. Make room for them */
  1784. insn_cnt += cnt - 1;
  1785. new_prog = bpf_prog_realloc(env->prog,
  1786. bpf_prog_size(insn_cnt),
  1787. GFP_USER);
  1788. if (!new_prog)
  1789. return -ENOMEM;
  1790. new_prog->len = insn_cnt;
  1791. memmove(new_prog->insnsi + i + cnt, new_prog->insns + i + 1,
  1792. sizeof(*insn) * (insn_cnt - i - cnt));
  1793. /* copy substitute insns in place of load instruction */
  1794. memcpy(new_prog->insnsi + i, insn_buf, sizeof(*insn) * cnt);
  1795. /* adjust branches in the whole program */
  1796. adjust_branches(new_prog, i, cnt - 1);
  1797. /* keep walking new program and skip insns we just inserted */
  1798. env->prog = new_prog;
  1799. insn = new_prog->insnsi + i + cnt - 1;
  1800. i += cnt - 1;
  1801. }
  1802. return 0;
  1803. }
  1804. static void free_states(struct verifier_env *env)
  1805. {
  1806. struct verifier_state_list *sl, *sln;
  1807. int i;
  1808. if (!env->explored_states)
  1809. return;
  1810. for (i = 0; i < env->prog->len; i++) {
  1811. sl = env->explored_states[i];
  1812. if (sl)
  1813. while (sl != STATE_LIST_MARK) {
  1814. sln = sl->next;
  1815. kfree(sl);
  1816. sl = sln;
  1817. }
  1818. }
  1819. kfree(env->explored_states);
  1820. }
  1821. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  1822. {
  1823. char __user *log_ubuf = NULL;
  1824. struct verifier_env *env;
  1825. int ret = -EINVAL;
  1826. if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
  1827. return -E2BIG;
  1828. /* 'struct verifier_env' can be global, but since it's not small,
  1829. * allocate/free it every time bpf_check() is called
  1830. */
  1831. env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL);
  1832. if (!env)
  1833. return -ENOMEM;
  1834. env->prog = *prog;
  1835. /* grab the mutex to protect few globals used by verifier */
  1836. mutex_lock(&bpf_verifier_lock);
  1837. if (attr->log_level || attr->log_buf || attr->log_size) {
  1838. /* user requested verbose verifier output
  1839. * and supplied buffer to store the verification trace
  1840. */
  1841. log_level = attr->log_level;
  1842. log_ubuf = (char __user *) (unsigned long) attr->log_buf;
  1843. log_size = attr->log_size;
  1844. log_len = 0;
  1845. ret = -EINVAL;
  1846. /* log_* values have to be sane */
  1847. if (log_size < 128 || log_size > UINT_MAX >> 8 ||
  1848. log_level == 0 || log_ubuf == NULL)
  1849. goto free_env;
  1850. ret = -ENOMEM;
  1851. log_buf = vmalloc(log_size);
  1852. if (!log_buf)
  1853. goto free_env;
  1854. } else {
  1855. log_level = 0;
  1856. }
  1857. ret = replace_map_fd_with_map_ptr(env);
  1858. if (ret < 0)
  1859. goto skip_full_check;
  1860. env->explored_states = kcalloc(env->prog->len,
  1861. sizeof(struct verifier_state_list *),
  1862. GFP_USER);
  1863. ret = -ENOMEM;
  1864. if (!env->explored_states)
  1865. goto skip_full_check;
  1866. ret = check_cfg(env);
  1867. if (ret < 0)
  1868. goto skip_full_check;
  1869. ret = do_check(env);
  1870. skip_full_check:
  1871. while (pop_stack(env, NULL) >= 0);
  1872. free_states(env);
  1873. if (ret == 0)
  1874. /* program is valid, convert *(u32*)(ctx + off) accesses */
  1875. ret = convert_ctx_accesses(env);
  1876. if (log_level && log_len >= log_size - 1) {
  1877. BUG_ON(log_len >= log_size);
  1878. /* verifier log exceeded user supplied buffer */
  1879. ret = -ENOSPC;
  1880. /* fall through to return what was recorded */
  1881. }
  1882. /* copy verifier log back to user space including trailing zero */
  1883. if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
  1884. ret = -EFAULT;
  1885. goto free_log_buf;
  1886. }
  1887. if (ret == 0 && env->used_map_cnt) {
  1888. /* if program passed verifier, update used_maps in bpf_prog_info */
  1889. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  1890. sizeof(env->used_maps[0]),
  1891. GFP_KERNEL);
  1892. if (!env->prog->aux->used_maps) {
  1893. ret = -ENOMEM;
  1894. goto free_log_buf;
  1895. }
  1896. memcpy(env->prog->aux->used_maps, env->used_maps,
  1897. sizeof(env->used_maps[0]) * env->used_map_cnt);
  1898. env->prog->aux->used_map_cnt = env->used_map_cnt;
  1899. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  1900. * bpf_ld_imm64 instructions
  1901. */
  1902. convert_pseudo_ld_imm64(env);
  1903. }
  1904. free_log_buf:
  1905. if (log_level)
  1906. vfree(log_buf);
  1907. free_env:
  1908. if (!env->prog->aux->used_maps)
  1909. /* if we didn't copy map pointers into bpf_prog_info, release
  1910. * them now. Otherwise free_bpf_prog_info() will release them.
  1911. */
  1912. release_maps(env);
  1913. *prog = env->prog;
  1914. kfree(env);
  1915. mutex_unlock(&bpf_verifier_lock);
  1916. return ret;
  1917. }