verifier.c 63 KB

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