verifier.c 60 KB

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