verifier.c 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846
  1. /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  2. * Copyright (c) 2016 Facebook
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of version 2 of the GNU General Public
  6. * License as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful, but
  9. * WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * General Public License for more details.
  12. */
  13. #include <linux/kernel.h>
  14. #include <linux/types.h>
  15. #include <linux/slab.h>
  16. #include <linux/bpf.h>
  17. #include <linux/filter.h>
  18. #include <net/netlink.h>
  19. #include <linux/file.h>
  20. #include <linux/vmalloc.h>
  21. /* bpf_check() is a static code analyzer that walks eBPF program
  22. * instruction by instruction and updates register/stack state.
  23. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  24. *
  25. * The first pass is depth-first-search to check that the program is a DAG.
  26. * It rejects the following programs:
  27. * - larger than BPF_MAXINSNS insns
  28. * - if loop is present (detected via back-edge)
  29. * - unreachable insns exist (shouldn't be a forest. program = one function)
  30. * - out of bounds or malformed jumps
  31. * The second pass is all possible path descent from the 1st insn.
  32. * Since it's analyzing all pathes through the program, the length of the
  33. * analysis is limited to 32k insn, which may be hit even if total number of
  34. * insn is less then 4K, but there are too many branches that change stack/regs.
  35. * Number of 'branches to be analyzed' is limited to 1k
  36. *
  37. * On entry to each instruction, each register has a type, and the instruction
  38. * changes the types of the registers depending on instruction semantics.
  39. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  40. * copied to R1.
  41. *
  42. * All registers are 64-bit.
  43. * R0 - return register
  44. * R1-R5 argument passing registers
  45. * R6-R9 callee saved registers
  46. * R10 - frame pointer read-only
  47. *
  48. * At the start of BPF program the register R1 contains a pointer to bpf_context
  49. * and has type PTR_TO_CTX.
  50. *
  51. * Verifier tracks arithmetic operations on pointers in case:
  52. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  53. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  54. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  55. * and 2nd arithmetic instruction is pattern matched to recognize
  56. * that it wants to construct a pointer to some element within stack.
  57. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  58. * (and -20 constant is saved for further stack bounds checking).
  59. * Meaning that this reg is a pointer to stack plus known immediate constant.
  60. *
  61. * Most of the time the registers have UNKNOWN_VALUE type, which
  62. * means the register has some value, but it's not a valid pointer.
  63. * (like pointer plus pointer becomes UNKNOWN_VALUE type)
  64. *
  65. * When verifier sees load or store instructions the type of base register
  66. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
  67. * types recognized by check_mem_access() function.
  68. *
  69. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  70. * and the range of [ptr, ptr + map's value_size) is accessible.
  71. *
  72. * registers used to pass values to function calls are checked against
  73. * function argument constraints.
  74. *
  75. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  76. * It means that the register type passed to this function must be
  77. * PTR_TO_STACK and it will be used inside the function as
  78. * 'pointer to map element key'
  79. *
  80. * For example the argument constraints for bpf_map_lookup_elem():
  81. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  82. * .arg1_type = ARG_CONST_MAP_PTR,
  83. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  84. *
  85. * ret_type says that this function returns 'pointer to map elem value or null'
  86. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  87. * 2nd argument should be a pointer to stack, which will be used inside
  88. * the helper function as a pointer to map element key.
  89. *
  90. * On the kernel side the helper function looks like:
  91. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  92. * {
  93. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  94. * void *key = (void *) (unsigned long) r2;
  95. * void *value;
  96. *
  97. * here kernel can access 'key' and 'map' pointers safely, knowing that
  98. * [key, key + map->key_size) bytes are valid and were initialized on
  99. * the stack of eBPF program.
  100. * }
  101. *
  102. * Corresponding eBPF program may look like:
  103. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  104. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  105. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  106. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  107. * here verifier looks at prototype of map_lookup_elem() and sees:
  108. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  109. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  110. *
  111. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  112. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  113. * and were initialized prior to this call.
  114. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  115. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  116. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  117. * returns ether pointer to map value or NULL.
  118. *
  119. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  120. * insn, the register holding that pointer in the true branch changes state to
  121. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  122. * branch. See check_cond_jmp_op().
  123. *
  124. * After the call R0 is set to return type of the function and registers R1-R5
  125. * are set to NOT_INIT to indicate that they are no longer readable.
  126. */
  127. struct reg_state {
  128. enum bpf_reg_type type;
  129. union {
  130. /* valid when type == CONST_IMM | PTR_TO_STACK | UNKNOWN_VALUE */
  131. s64 imm;
  132. /* valid when type == PTR_TO_PACKET* */
  133. struct {
  134. u32 id;
  135. u16 off;
  136. u16 range;
  137. };
  138. /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
  139. * PTR_TO_MAP_VALUE_OR_NULL
  140. */
  141. struct bpf_map *map_ptr;
  142. };
  143. };
  144. enum bpf_stack_slot_type {
  145. STACK_INVALID, /* nothing was stored in this stack slot */
  146. STACK_SPILL, /* register spilled into stack */
  147. STACK_MISC /* BPF program wrote some data into this slot */
  148. };
  149. #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */
  150. /* state of the program:
  151. * type of all registers and stack info
  152. */
  153. struct verifier_state {
  154. struct reg_state regs[MAX_BPF_REG];
  155. u8 stack_slot_type[MAX_BPF_STACK];
  156. struct reg_state spilled_regs[MAX_BPF_STACK / BPF_REG_SIZE];
  157. };
  158. /* linked list of verifier states used to prune search */
  159. struct verifier_state_list {
  160. struct verifier_state state;
  161. struct verifier_state_list *next;
  162. };
  163. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  164. struct verifier_stack_elem {
  165. /* verifer state is 'st'
  166. * before processing instruction 'insn_idx'
  167. * and after processing instruction 'prev_insn_idx'
  168. */
  169. struct verifier_state st;
  170. int insn_idx;
  171. int prev_insn_idx;
  172. struct verifier_stack_elem *next;
  173. };
  174. #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
  175. /* single container for all structs
  176. * one verifier_env per bpf_check() call
  177. */
  178. struct verifier_env {
  179. struct bpf_prog *prog; /* eBPF program being verified */
  180. struct verifier_stack_elem *head; /* stack of verifier states to be processed */
  181. int stack_size; /* number of states to be processed */
  182. struct verifier_state cur_state; /* current verifier state */
  183. struct verifier_state_list **explored_states; /* search pruning optimization */
  184. struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
  185. u32 used_map_cnt; /* number of used maps */
  186. u32 id_gen; /* used to generate unique reg IDs */
  187. bool allow_ptr_leaks;
  188. };
  189. #define BPF_COMPLEXITY_LIMIT_INSNS 65536
  190. #define BPF_COMPLEXITY_LIMIT_STACK 1024
  191. struct bpf_call_arg_meta {
  192. struct bpf_map *map_ptr;
  193. bool raw_mode;
  194. int regno;
  195. int access_size;
  196. };
  197. /* verbose verifier prints what it's seeing
  198. * bpf_check() is called under lock, so no race to access these global vars
  199. */
  200. static u32 log_level, log_size, log_len;
  201. static char *log_buf;
  202. static DEFINE_MUTEX(bpf_verifier_lock);
  203. /* log_level controls verbosity level of eBPF verifier.
  204. * verbose() is used to dump the verification trace to the log, so the user
  205. * can figure out what's wrong with the program
  206. */
  207. static __printf(1, 2) void verbose(const char *fmt, ...)
  208. {
  209. va_list args;
  210. if (log_level == 0 || log_len >= log_size - 1)
  211. return;
  212. va_start(args, fmt);
  213. log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
  214. va_end(args);
  215. }
  216. /* string representation of 'enum bpf_reg_type' */
  217. static const char * const reg_type_str[] = {
  218. [NOT_INIT] = "?",
  219. [UNKNOWN_VALUE] = "inv",
  220. [PTR_TO_CTX] = "ctx",
  221. [CONST_PTR_TO_MAP] = "map_ptr",
  222. [PTR_TO_MAP_VALUE] = "map_value",
  223. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  224. [FRAME_PTR] = "fp",
  225. [PTR_TO_STACK] = "fp",
  226. [CONST_IMM] = "imm",
  227. [PTR_TO_PACKET] = "pkt",
  228. [PTR_TO_PACKET_END] = "pkt_end",
  229. };
  230. static void print_verifier_state(struct verifier_state *state)
  231. {
  232. struct reg_state *reg;
  233. enum bpf_reg_type t;
  234. int i;
  235. for (i = 0; i < MAX_BPF_REG; i++) {
  236. reg = &state->regs[i];
  237. t = reg->type;
  238. if (t == NOT_INIT)
  239. continue;
  240. verbose(" R%d=%s", i, reg_type_str[t]);
  241. if (t == CONST_IMM || t == PTR_TO_STACK)
  242. verbose("%lld", reg->imm);
  243. else if (t == PTR_TO_PACKET)
  244. verbose("(id=%d,off=%d,r=%d)",
  245. reg->id, reg->off, reg->range);
  246. else if (t == UNKNOWN_VALUE && reg->imm)
  247. verbose("%lld", reg->imm);
  248. else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
  249. t == PTR_TO_MAP_VALUE_OR_NULL)
  250. verbose("(ks=%d,vs=%d)",
  251. reg->map_ptr->key_size,
  252. reg->map_ptr->value_size);
  253. }
  254. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  255. if (state->stack_slot_type[i] == STACK_SPILL)
  256. verbose(" fp%d=%s", -MAX_BPF_STACK + i,
  257. reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
  258. }
  259. verbose("\n");
  260. }
  261. static const char *const bpf_class_string[] = {
  262. [BPF_LD] = "ld",
  263. [BPF_LDX] = "ldx",
  264. [BPF_ST] = "st",
  265. [BPF_STX] = "stx",
  266. [BPF_ALU] = "alu",
  267. [BPF_JMP] = "jmp",
  268. [BPF_RET] = "BUG",
  269. [BPF_ALU64] = "alu64",
  270. };
  271. static const char *const bpf_alu_string[16] = {
  272. [BPF_ADD >> 4] = "+=",
  273. [BPF_SUB >> 4] = "-=",
  274. [BPF_MUL >> 4] = "*=",
  275. [BPF_DIV >> 4] = "/=",
  276. [BPF_OR >> 4] = "|=",
  277. [BPF_AND >> 4] = "&=",
  278. [BPF_LSH >> 4] = "<<=",
  279. [BPF_RSH >> 4] = ">>=",
  280. [BPF_NEG >> 4] = "neg",
  281. [BPF_MOD >> 4] = "%=",
  282. [BPF_XOR >> 4] = "^=",
  283. [BPF_MOV >> 4] = "=",
  284. [BPF_ARSH >> 4] = "s>>=",
  285. [BPF_END >> 4] = "endian",
  286. };
  287. static const char *const bpf_ldst_string[] = {
  288. [BPF_W >> 3] = "u32",
  289. [BPF_H >> 3] = "u16",
  290. [BPF_B >> 3] = "u8",
  291. [BPF_DW >> 3] = "u64",
  292. };
  293. static const char *const bpf_jmp_string[16] = {
  294. [BPF_JA >> 4] = "jmp",
  295. [BPF_JEQ >> 4] = "==",
  296. [BPF_JGT >> 4] = ">",
  297. [BPF_JGE >> 4] = ">=",
  298. [BPF_JSET >> 4] = "&",
  299. [BPF_JNE >> 4] = "!=",
  300. [BPF_JSGT >> 4] = "s>",
  301. [BPF_JSGE >> 4] = "s>=",
  302. [BPF_CALL >> 4] = "call",
  303. [BPF_EXIT >> 4] = "exit",
  304. };
  305. static void print_bpf_insn(struct bpf_insn *insn)
  306. {
  307. u8 class = BPF_CLASS(insn->code);
  308. if (class == BPF_ALU || class == BPF_ALU64) {
  309. if (BPF_SRC(insn->code) == BPF_X)
  310. verbose("(%02x) %sr%d %s %sr%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->src_reg);
  316. else
  317. verbose("(%02x) %sr%d %s %s%d\n",
  318. insn->code, class == BPF_ALU ? "(u32) " : "",
  319. insn->dst_reg,
  320. bpf_alu_string[BPF_OP(insn->code) >> 4],
  321. class == BPF_ALU ? "(u32) " : "",
  322. insn->imm);
  323. } else if (class == BPF_STX) {
  324. if (BPF_MODE(insn->code) == BPF_MEM)
  325. verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
  326. insn->code,
  327. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  328. insn->dst_reg,
  329. insn->off, insn->src_reg);
  330. else if (BPF_MODE(insn->code) == BPF_XADD)
  331. verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
  332. insn->code,
  333. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  334. insn->dst_reg, insn->off,
  335. insn->src_reg);
  336. else
  337. verbose("BUG_%02x\n", insn->code);
  338. } else if (class == BPF_ST) {
  339. if (BPF_MODE(insn->code) != BPF_MEM) {
  340. verbose("BUG_st_%02x\n", insn->code);
  341. return;
  342. }
  343. verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
  344. insn->code,
  345. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  346. insn->dst_reg,
  347. insn->off, insn->imm);
  348. } else if (class == BPF_LDX) {
  349. if (BPF_MODE(insn->code) != BPF_MEM) {
  350. verbose("BUG_ldx_%02x\n", insn->code);
  351. return;
  352. }
  353. verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
  354. insn->code, insn->dst_reg,
  355. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  356. insn->src_reg, insn->off);
  357. } else if (class == BPF_LD) {
  358. if (BPF_MODE(insn->code) == BPF_ABS) {
  359. verbose("(%02x) r0 = *(%s *)skb[%d]\n",
  360. insn->code,
  361. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  362. insn->imm);
  363. } else if (BPF_MODE(insn->code) == BPF_IND) {
  364. verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
  365. insn->code,
  366. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  367. insn->src_reg, insn->imm);
  368. } else if (BPF_MODE(insn->code) == BPF_IMM) {
  369. verbose("(%02x) r%d = 0x%x\n",
  370. insn->code, insn->dst_reg, insn->imm);
  371. } else {
  372. verbose("BUG_ld_%02x\n", insn->code);
  373. return;
  374. }
  375. } else if (class == BPF_JMP) {
  376. u8 opcode = BPF_OP(insn->code);
  377. if (opcode == BPF_CALL) {
  378. verbose("(%02x) call %d\n", insn->code, insn->imm);
  379. } else if (insn->code == (BPF_JMP | BPF_JA)) {
  380. verbose("(%02x) goto pc%+d\n",
  381. insn->code, insn->off);
  382. } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
  383. verbose("(%02x) exit\n", insn->code);
  384. } else if (BPF_SRC(insn->code) == BPF_X) {
  385. verbose("(%02x) if r%d %s r%d goto pc%+d\n",
  386. insn->code, insn->dst_reg,
  387. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  388. insn->src_reg, insn->off);
  389. } else {
  390. verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
  391. insn->code, insn->dst_reg,
  392. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  393. insn->imm, insn->off);
  394. }
  395. } else {
  396. verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
  397. }
  398. }
  399. static int pop_stack(struct verifier_env *env, int *prev_insn_idx)
  400. {
  401. struct verifier_stack_elem *elem;
  402. int insn_idx;
  403. if (env->head == NULL)
  404. return -1;
  405. memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
  406. insn_idx = env->head->insn_idx;
  407. if (prev_insn_idx)
  408. *prev_insn_idx = env->head->prev_insn_idx;
  409. elem = env->head->next;
  410. kfree(env->head);
  411. env->head = elem;
  412. env->stack_size--;
  413. return insn_idx;
  414. }
  415. static struct verifier_state *push_stack(struct verifier_env *env, int insn_idx,
  416. int prev_insn_idx)
  417. {
  418. struct verifier_stack_elem *elem;
  419. elem = kmalloc(sizeof(struct verifier_stack_elem), GFP_KERNEL);
  420. if (!elem)
  421. goto err;
  422. memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
  423. elem->insn_idx = insn_idx;
  424. elem->prev_insn_idx = prev_insn_idx;
  425. elem->next = env->head;
  426. env->head = elem;
  427. env->stack_size++;
  428. if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
  429. verbose("BPF program is too complex\n");
  430. goto err;
  431. }
  432. return &elem->st;
  433. err:
  434. /* pop all elements and return */
  435. while (pop_stack(env, NULL) >= 0);
  436. return NULL;
  437. }
  438. #define CALLER_SAVED_REGS 6
  439. static const int caller_saved[CALLER_SAVED_REGS] = {
  440. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  441. };
  442. static void init_reg_state(struct reg_state *regs)
  443. {
  444. int i;
  445. for (i = 0; i < MAX_BPF_REG; i++) {
  446. regs[i].type = NOT_INIT;
  447. regs[i].imm = 0;
  448. }
  449. /* frame pointer */
  450. regs[BPF_REG_FP].type = FRAME_PTR;
  451. /* 1st arg to a function */
  452. regs[BPF_REG_1].type = PTR_TO_CTX;
  453. }
  454. static void mark_reg_unknown_value(struct reg_state *regs, u32 regno)
  455. {
  456. BUG_ON(regno >= MAX_BPF_REG);
  457. regs[regno].type = UNKNOWN_VALUE;
  458. regs[regno].imm = 0;
  459. }
  460. enum reg_arg_type {
  461. SRC_OP, /* register is used as source operand */
  462. DST_OP, /* register is used as destination operand */
  463. DST_OP_NO_MARK /* same as above, check only, don't mark */
  464. };
  465. static int check_reg_arg(struct reg_state *regs, u32 regno,
  466. enum reg_arg_type t)
  467. {
  468. if (regno >= MAX_BPF_REG) {
  469. verbose("R%d is invalid\n", regno);
  470. return -EINVAL;
  471. }
  472. if (t == SRC_OP) {
  473. /* check whether register used as source operand can be read */
  474. if (regs[regno].type == NOT_INIT) {
  475. verbose("R%d !read_ok\n", regno);
  476. return -EACCES;
  477. }
  478. } else {
  479. /* check whether register used as dest operand can be written to */
  480. if (regno == BPF_REG_FP) {
  481. verbose("frame pointer is read only\n");
  482. return -EACCES;
  483. }
  484. if (t == DST_OP)
  485. mark_reg_unknown_value(regs, regno);
  486. }
  487. return 0;
  488. }
  489. static int bpf_size_to_bytes(int bpf_size)
  490. {
  491. if (bpf_size == BPF_W)
  492. return 4;
  493. else if (bpf_size == BPF_H)
  494. return 2;
  495. else if (bpf_size == BPF_B)
  496. return 1;
  497. else if (bpf_size == BPF_DW)
  498. return 8;
  499. else
  500. return -EINVAL;
  501. }
  502. static bool is_spillable_regtype(enum bpf_reg_type type)
  503. {
  504. switch (type) {
  505. case PTR_TO_MAP_VALUE:
  506. case PTR_TO_MAP_VALUE_OR_NULL:
  507. case PTR_TO_STACK:
  508. case PTR_TO_CTX:
  509. case PTR_TO_PACKET:
  510. case PTR_TO_PACKET_END:
  511. case FRAME_PTR:
  512. case CONST_PTR_TO_MAP:
  513. return true;
  514. default:
  515. return false;
  516. }
  517. }
  518. /* check_stack_read/write functions track spill/fill of registers,
  519. * stack boundary and alignment are checked in check_mem_access()
  520. */
  521. static int check_stack_write(struct verifier_state *state, int off, int size,
  522. int value_regno)
  523. {
  524. int i;
  525. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  526. * so it's aligned access and [off, off + size) are within stack limits
  527. */
  528. if (value_regno >= 0 &&
  529. is_spillable_regtype(state->regs[value_regno].type)) {
  530. /* register containing pointer is being spilled into stack */
  531. if (size != BPF_REG_SIZE) {
  532. verbose("invalid size of register spill\n");
  533. return -EACCES;
  534. }
  535. /* save register state */
  536. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
  537. state->regs[value_regno];
  538. for (i = 0; i < BPF_REG_SIZE; i++)
  539. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
  540. } else {
  541. /* regular write of data into stack */
  542. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
  543. (struct reg_state) {};
  544. for (i = 0; i < size; i++)
  545. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
  546. }
  547. return 0;
  548. }
  549. static int check_stack_read(struct verifier_state *state, int off, int size,
  550. int value_regno)
  551. {
  552. u8 *slot_type;
  553. int i;
  554. slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
  555. if (slot_type[0] == STACK_SPILL) {
  556. if (size != BPF_REG_SIZE) {
  557. verbose("invalid size of register spill\n");
  558. return -EACCES;
  559. }
  560. for (i = 1; i < BPF_REG_SIZE; i++) {
  561. if (slot_type[i] != STACK_SPILL) {
  562. verbose("corrupted spill memory\n");
  563. return -EACCES;
  564. }
  565. }
  566. if (value_regno >= 0)
  567. /* restore register state from stack */
  568. state->regs[value_regno] =
  569. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
  570. return 0;
  571. } else {
  572. for (i = 0; i < size; i++) {
  573. if (slot_type[i] != STACK_MISC) {
  574. verbose("invalid read from stack off %d+%d size %d\n",
  575. off, i, size);
  576. return -EACCES;
  577. }
  578. }
  579. if (value_regno >= 0)
  580. /* have read misc data from the stack */
  581. mark_reg_unknown_value(state->regs, value_regno);
  582. return 0;
  583. }
  584. }
  585. /* check read/write into map element returned by bpf_map_lookup_elem() */
  586. static int check_map_access(struct verifier_env *env, u32 regno, int off,
  587. int size)
  588. {
  589. struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
  590. if (off < 0 || off + size > map->value_size) {
  591. verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
  592. map->value_size, off, size);
  593. return -EACCES;
  594. }
  595. return 0;
  596. }
  597. #define MAX_PACKET_OFF 0xffff
  598. static bool may_write_pkt_data(enum bpf_prog_type type)
  599. {
  600. switch (type) {
  601. case BPF_PROG_TYPE_XDP:
  602. return true;
  603. default:
  604. return false;
  605. }
  606. }
  607. static int check_packet_access(struct verifier_env *env, u32 regno, int off,
  608. int size)
  609. {
  610. struct reg_state *regs = env->cur_state.regs;
  611. struct reg_state *reg = &regs[regno];
  612. off += reg->off;
  613. if (off < 0 || off + size > reg->range) {
  614. verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
  615. off, size, regno, reg->id, reg->off, reg->range);
  616. return -EACCES;
  617. }
  618. return 0;
  619. }
  620. /* check access to 'struct bpf_context' fields */
  621. static int check_ctx_access(struct verifier_env *env, int off, int size,
  622. enum bpf_access_type t, enum bpf_reg_type *reg_type)
  623. {
  624. if (env->prog->aux->ops->is_valid_access &&
  625. env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
  626. /* remember the offset of last byte accessed in ctx */
  627. if (env->prog->aux->max_ctx_offset < off + size)
  628. env->prog->aux->max_ctx_offset = off + size;
  629. return 0;
  630. }
  631. verbose("invalid bpf_context access off=%d size=%d\n", off, size);
  632. return -EACCES;
  633. }
  634. static bool is_pointer_value(struct verifier_env *env, int regno)
  635. {
  636. if (env->allow_ptr_leaks)
  637. return false;
  638. switch (env->cur_state.regs[regno].type) {
  639. case UNKNOWN_VALUE:
  640. case CONST_IMM:
  641. return false;
  642. default:
  643. return true;
  644. }
  645. }
  646. static int check_ptr_alignment(struct verifier_env *env, struct reg_state *reg,
  647. int off, int size)
  648. {
  649. if (reg->type != PTR_TO_PACKET) {
  650. if (off % size != 0) {
  651. verbose("misaligned access off %d size %d\n", off, size);
  652. return -EACCES;
  653. } else {
  654. return 0;
  655. }
  656. }
  657. switch (env->prog->type) {
  658. case BPF_PROG_TYPE_SCHED_CLS:
  659. case BPF_PROG_TYPE_SCHED_ACT:
  660. case BPF_PROG_TYPE_XDP:
  661. break;
  662. default:
  663. verbose("verifier is misconfigured\n");
  664. return -EACCES;
  665. }
  666. if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
  667. /* misaligned access to packet is ok on x86,arm,arm64 */
  668. return 0;
  669. if (reg->id && size != 1) {
  670. verbose("Unknown packet alignment. Only byte-sized access allowed\n");
  671. return -EACCES;
  672. }
  673. /* skb->data is NET_IP_ALIGN-ed */
  674. if ((NET_IP_ALIGN + reg->off + off) % size != 0) {
  675. verbose("misaligned packet access off %d+%d+%d size %d\n",
  676. NET_IP_ALIGN, reg->off, off, size);
  677. return -EACCES;
  678. }
  679. return 0;
  680. }
  681. /* check whether memory at (regno + off) is accessible for t = (read | write)
  682. * if t==write, value_regno is a register which value is stored into memory
  683. * if t==read, value_regno is a register which will receive the value from memory
  684. * if t==write && value_regno==-1, some unknown value is stored into memory
  685. * if t==read && value_regno==-1, don't care what we read from memory
  686. */
  687. static int check_mem_access(struct verifier_env *env, u32 regno, int off,
  688. int bpf_size, enum bpf_access_type t,
  689. int value_regno)
  690. {
  691. struct verifier_state *state = &env->cur_state;
  692. struct reg_state *reg = &state->regs[regno];
  693. int size, err = 0;
  694. if (reg->type == PTR_TO_STACK)
  695. off += reg->imm;
  696. size = bpf_size_to_bytes(bpf_size);
  697. if (size < 0)
  698. return size;
  699. err = check_ptr_alignment(env, reg, off, size);
  700. if (err)
  701. return err;
  702. if (reg->type == PTR_TO_MAP_VALUE) {
  703. if (t == BPF_WRITE && value_regno >= 0 &&
  704. is_pointer_value(env, value_regno)) {
  705. verbose("R%d leaks addr into map\n", value_regno);
  706. return -EACCES;
  707. }
  708. err = check_map_access(env, regno, off, size);
  709. if (!err && t == BPF_READ && value_regno >= 0)
  710. mark_reg_unknown_value(state->regs, value_regno);
  711. } else if (reg->type == PTR_TO_CTX) {
  712. enum bpf_reg_type reg_type = UNKNOWN_VALUE;
  713. if (t == BPF_WRITE && value_regno >= 0 &&
  714. is_pointer_value(env, value_regno)) {
  715. verbose("R%d leaks addr into ctx\n", value_regno);
  716. return -EACCES;
  717. }
  718. err = check_ctx_access(env, off, size, t, &reg_type);
  719. if (!err && t == BPF_READ && value_regno >= 0) {
  720. mark_reg_unknown_value(state->regs, value_regno);
  721. if (env->allow_ptr_leaks)
  722. /* note that reg.[id|off|range] == 0 */
  723. state->regs[value_regno].type = reg_type;
  724. }
  725. } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
  726. if (off >= 0 || off < -MAX_BPF_STACK) {
  727. verbose("invalid stack off=%d size=%d\n", off, size);
  728. return -EACCES;
  729. }
  730. if (t == BPF_WRITE) {
  731. if (!env->allow_ptr_leaks &&
  732. state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
  733. size != BPF_REG_SIZE) {
  734. verbose("attempt to corrupt spilled pointer on stack\n");
  735. return -EACCES;
  736. }
  737. err = check_stack_write(state, off, size, value_regno);
  738. } else {
  739. err = check_stack_read(state, off, size, value_regno);
  740. }
  741. } else if (state->regs[regno].type == PTR_TO_PACKET) {
  742. if (t == BPF_WRITE && !may_write_pkt_data(env->prog->type)) {
  743. verbose("cannot write into packet\n");
  744. return -EACCES;
  745. }
  746. if (t == BPF_WRITE && value_regno >= 0 &&
  747. is_pointer_value(env, value_regno)) {
  748. verbose("R%d leaks addr into packet\n", value_regno);
  749. return -EACCES;
  750. }
  751. err = check_packet_access(env, regno, off, size);
  752. if (!err && t == BPF_READ && value_regno >= 0)
  753. mark_reg_unknown_value(state->regs, value_regno);
  754. } else {
  755. verbose("R%d invalid mem access '%s'\n",
  756. regno, reg_type_str[reg->type]);
  757. return -EACCES;
  758. }
  759. if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
  760. state->regs[value_regno].type == UNKNOWN_VALUE) {
  761. /* 1 or 2 byte load zero-extends, determine the number of
  762. * zero upper bits. Not doing it fo 4 byte load, since
  763. * such values cannot be added to ptr_to_packet anyway.
  764. */
  765. state->regs[value_regno].imm = 64 - size * 8;
  766. }
  767. return err;
  768. }
  769. static int check_xadd(struct verifier_env *env, struct bpf_insn *insn)
  770. {
  771. struct reg_state *regs = env->cur_state.regs;
  772. int err;
  773. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  774. insn->imm != 0) {
  775. verbose("BPF_XADD uses reserved fields\n");
  776. return -EINVAL;
  777. }
  778. /* check src1 operand */
  779. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  780. if (err)
  781. return err;
  782. /* check src2 operand */
  783. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  784. if (err)
  785. return err;
  786. /* check whether atomic_add can read the memory */
  787. err = check_mem_access(env, insn->dst_reg, insn->off,
  788. BPF_SIZE(insn->code), BPF_READ, -1);
  789. if (err)
  790. return err;
  791. /* check whether atomic_add can write into the same memory */
  792. return check_mem_access(env, insn->dst_reg, insn->off,
  793. BPF_SIZE(insn->code), BPF_WRITE, -1);
  794. }
  795. /* when register 'regno' is passed into function that will read 'access_size'
  796. * bytes from that pointer, make sure that it's within stack boundary
  797. * and all elements of stack are initialized
  798. */
  799. static int check_stack_boundary(struct verifier_env *env, int regno,
  800. int access_size, bool zero_size_allowed,
  801. struct bpf_call_arg_meta *meta)
  802. {
  803. struct verifier_state *state = &env->cur_state;
  804. struct reg_state *regs = state->regs;
  805. int off, i;
  806. if (regs[regno].type != PTR_TO_STACK) {
  807. if (zero_size_allowed && access_size == 0 &&
  808. regs[regno].type == CONST_IMM &&
  809. regs[regno].imm == 0)
  810. return 0;
  811. verbose("R%d type=%s expected=%s\n", regno,
  812. reg_type_str[regs[regno].type],
  813. reg_type_str[PTR_TO_STACK]);
  814. return -EACCES;
  815. }
  816. off = regs[regno].imm;
  817. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  818. access_size <= 0) {
  819. verbose("invalid stack type R%d off=%d access_size=%d\n",
  820. regno, off, access_size);
  821. return -EACCES;
  822. }
  823. if (meta && meta->raw_mode) {
  824. meta->access_size = access_size;
  825. meta->regno = regno;
  826. return 0;
  827. }
  828. for (i = 0; i < access_size; i++) {
  829. if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
  830. verbose("invalid indirect read from stack off %d+%d size %d\n",
  831. off, i, access_size);
  832. return -EACCES;
  833. }
  834. }
  835. return 0;
  836. }
  837. static int check_func_arg(struct verifier_env *env, u32 regno,
  838. enum bpf_arg_type arg_type,
  839. struct bpf_call_arg_meta *meta)
  840. {
  841. struct reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
  842. enum bpf_reg_type expected_type, type = reg->type;
  843. int err = 0;
  844. if (arg_type == ARG_DONTCARE)
  845. return 0;
  846. if (type == NOT_INIT) {
  847. verbose("R%d !read_ok\n", regno);
  848. return -EACCES;
  849. }
  850. if (arg_type == ARG_ANYTHING) {
  851. if (is_pointer_value(env, regno)) {
  852. verbose("R%d leaks addr into helper function\n", regno);
  853. return -EACCES;
  854. }
  855. return 0;
  856. }
  857. if (type == PTR_TO_PACKET && !may_write_pkt_data(env->prog->type)) {
  858. verbose("helper access to the packet is not allowed for clsact\n");
  859. return -EACCES;
  860. }
  861. if (arg_type == ARG_PTR_TO_MAP_KEY ||
  862. arg_type == ARG_PTR_TO_MAP_VALUE) {
  863. expected_type = PTR_TO_STACK;
  864. if (type != PTR_TO_PACKET && type != expected_type)
  865. goto err_type;
  866. } else if (arg_type == ARG_CONST_STACK_SIZE ||
  867. arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
  868. expected_type = CONST_IMM;
  869. if (type != expected_type)
  870. goto err_type;
  871. } else if (arg_type == ARG_CONST_MAP_PTR) {
  872. expected_type = CONST_PTR_TO_MAP;
  873. if (type != expected_type)
  874. goto err_type;
  875. } else if (arg_type == ARG_PTR_TO_CTX) {
  876. expected_type = PTR_TO_CTX;
  877. if (type != expected_type)
  878. goto err_type;
  879. } else if (arg_type == ARG_PTR_TO_STACK ||
  880. arg_type == ARG_PTR_TO_RAW_STACK) {
  881. expected_type = PTR_TO_STACK;
  882. /* One exception here. In case function allows for NULL to be
  883. * passed in as argument, it's a CONST_IMM type. Final test
  884. * happens during stack boundary checking.
  885. */
  886. if (type == CONST_IMM && reg->imm == 0)
  887. /* final test in check_stack_boundary() */;
  888. else if (type != PTR_TO_PACKET && type != expected_type)
  889. goto err_type;
  890. meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
  891. } else {
  892. verbose("unsupported arg_type %d\n", arg_type);
  893. return -EFAULT;
  894. }
  895. if (arg_type == ARG_CONST_MAP_PTR) {
  896. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  897. meta->map_ptr = reg->map_ptr;
  898. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  899. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  900. * check that [key, key + map->key_size) are within
  901. * stack limits and initialized
  902. */
  903. if (!meta->map_ptr) {
  904. /* in function declaration map_ptr must come before
  905. * map_key, so that it's verified and known before
  906. * we have to check map_key here. Otherwise it means
  907. * that kernel subsystem misconfigured verifier
  908. */
  909. verbose("invalid map_ptr to access map->key\n");
  910. return -EACCES;
  911. }
  912. if (type == PTR_TO_PACKET)
  913. err = check_packet_access(env, regno, 0,
  914. meta->map_ptr->key_size);
  915. else
  916. err = check_stack_boundary(env, regno,
  917. meta->map_ptr->key_size,
  918. false, NULL);
  919. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  920. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  921. * check [value, value + map->value_size) validity
  922. */
  923. if (!meta->map_ptr) {
  924. /* kernel subsystem misconfigured verifier */
  925. verbose("invalid map_ptr to access map->value\n");
  926. return -EACCES;
  927. }
  928. if (type == PTR_TO_PACKET)
  929. err = check_packet_access(env, regno, 0,
  930. meta->map_ptr->value_size);
  931. else
  932. err = check_stack_boundary(env, regno,
  933. meta->map_ptr->value_size,
  934. false, NULL);
  935. } else if (arg_type == ARG_CONST_STACK_SIZE ||
  936. arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
  937. bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
  938. /* bpf_xxx(..., buf, len) call will access 'len' bytes
  939. * from stack pointer 'buf'. Check it
  940. * note: regno == len, regno - 1 == buf
  941. */
  942. if (regno == 0) {
  943. /* kernel subsystem misconfigured verifier */
  944. verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
  945. return -EACCES;
  946. }
  947. if (regs[regno - 1].type == PTR_TO_PACKET)
  948. err = check_packet_access(env, regno - 1, 0, reg->imm);
  949. else
  950. err = check_stack_boundary(env, regno - 1, reg->imm,
  951. zero_size_allowed, meta);
  952. }
  953. return err;
  954. err_type:
  955. verbose("R%d type=%s expected=%s\n", regno,
  956. reg_type_str[type], reg_type_str[expected_type]);
  957. return -EACCES;
  958. }
  959. static int check_map_func_compatibility(struct bpf_map *map, int func_id)
  960. {
  961. if (!map)
  962. return 0;
  963. /* We need a two way check, first is from map perspective ... */
  964. switch (map->map_type) {
  965. case BPF_MAP_TYPE_PROG_ARRAY:
  966. if (func_id != BPF_FUNC_tail_call)
  967. goto error;
  968. break;
  969. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  970. if (func_id != BPF_FUNC_perf_event_read &&
  971. func_id != BPF_FUNC_perf_event_output)
  972. goto error;
  973. break;
  974. case BPF_MAP_TYPE_STACK_TRACE:
  975. if (func_id != BPF_FUNC_get_stackid)
  976. goto error;
  977. break;
  978. case BPF_MAP_TYPE_CGROUP_ARRAY:
  979. if (func_id != BPF_FUNC_skb_under_cgroup &&
  980. func_id != BPF_FUNC_current_task_under_cgroup)
  981. goto error;
  982. break;
  983. default:
  984. break;
  985. }
  986. /* ... and second from the function itself. */
  987. switch (func_id) {
  988. case BPF_FUNC_tail_call:
  989. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  990. goto error;
  991. break;
  992. case BPF_FUNC_perf_event_read:
  993. case BPF_FUNC_perf_event_output:
  994. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  995. goto error;
  996. break;
  997. case BPF_FUNC_get_stackid:
  998. if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
  999. goto error;
  1000. break;
  1001. case BPF_FUNC_current_task_under_cgroup:
  1002. case BPF_FUNC_skb_under_cgroup:
  1003. if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
  1004. goto error;
  1005. break;
  1006. default:
  1007. break;
  1008. }
  1009. return 0;
  1010. error:
  1011. verbose("cannot pass map_type %d into func %d\n",
  1012. map->map_type, func_id);
  1013. return -EINVAL;
  1014. }
  1015. static int check_raw_mode(const struct bpf_func_proto *fn)
  1016. {
  1017. int count = 0;
  1018. if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
  1019. count++;
  1020. if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
  1021. count++;
  1022. if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
  1023. count++;
  1024. if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
  1025. count++;
  1026. if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
  1027. count++;
  1028. return count > 1 ? -EINVAL : 0;
  1029. }
  1030. static void clear_all_pkt_pointers(struct verifier_env *env)
  1031. {
  1032. struct verifier_state *state = &env->cur_state;
  1033. struct reg_state *regs = state->regs, *reg;
  1034. int i;
  1035. for (i = 0; i < MAX_BPF_REG; i++)
  1036. if (regs[i].type == PTR_TO_PACKET ||
  1037. regs[i].type == PTR_TO_PACKET_END)
  1038. mark_reg_unknown_value(regs, i);
  1039. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  1040. if (state->stack_slot_type[i] != STACK_SPILL)
  1041. continue;
  1042. reg = &state->spilled_regs[i / BPF_REG_SIZE];
  1043. if (reg->type != PTR_TO_PACKET &&
  1044. reg->type != PTR_TO_PACKET_END)
  1045. continue;
  1046. reg->type = UNKNOWN_VALUE;
  1047. reg->imm = 0;
  1048. }
  1049. }
  1050. static int check_call(struct verifier_env *env, int func_id)
  1051. {
  1052. struct verifier_state *state = &env->cur_state;
  1053. const struct bpf_func_proto *fn = NULL;
  1054. struct reg_state *regs = state->regs;
  1055. struct reg_state *reg;
  1056. struct bpf_call_arg_meta meta;
  1057. bool changes_data;
  1058. int i, err;
  1059. /* find function prototype */
  1060. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  1061. verbose("invalid func %d\n", func_id);
  1062. return -EINVAL;
  1063. }
  1064. if (env->prog->aux->ops->get_func_proto)
  1065. fn = env->prog->aux->ops->get_func_proto(func_id);
  1066. if (!fn) {
  1067. verbose("unknown func %d\n", func_id);
  1068. return -EINVAL;
  1069. }
  1070. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  1071. if (!env->prog->gpl_compatible && fn->gpl_only) {
  1072. verbose("cannot call GPL only function from proprietary program\n");
  1073. return -EINVAL;
  1074. }
  1075. changes_data = bpf_helper_changes_skb_data(fn->func);
  1076. memset(&meta, 0, sizeof(meta));
  1077. /* We only support one arg being in raw mode at the moment, which
  1078. * is sufficient for the helper functions we have right now.
  1079. */
  1080. err = check_raw_mode(fn);
  1081. if (err) {
  1082. verbose("kernel subsystem misconfigured func %d\n", func_id);
  1083. return err;
  1084. }
  1085. /* check args */
  1086. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
  1087. if (err)
  1088. return err;
  1089. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
  1090. if (err)
  1091. return err;
  1092. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
  1093. if (err)
  1094. return err;
  1095. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
  1096. if (err)
  1097. return err;
  1098. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
  1099. if (err)
  1100. return err;
  1101. /* Mark slots with STACK_MISC in case of raw mode, stack offset
  1102. * is inferred from register state.
  1103. */
  1104. for (i = 0; i < meta.access_size; i++) {
  1105. err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
  1106. if (err)
  1107. return err;
  1108. }
  1109. /* reset caller saved regs */
  1110. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  1111. reg = regs + caller_saved[i];
  1112. reg->type = NOT_INIT;
  1113. reg->imm = 0;
  1114. }
  1115. /* update return register */
  1116. if (fn->ret_type == RET_INTEGER) {
  1117. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  1118. } else if (fn->ret_type == RET_VOID) {
  1119. regs[BPF_REG_0].type = NOT_INIT;
  1120. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  1121. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  1122. /* remember map_ptr, so that check_map_access()
  1123. * can check 'value_size' boundary of memory access
  1124. * to map element returned from bpf_map_lookup_elem()
  1125. */
  1126. if (meta.map_ptr == NULL) {
  1127. verbose("kernel subsystem misconfigured verifier\n");
  1128. return -EINVAL;
  1129. }
  1130. regs[BPF_REG_0].map_ptr = meta.map_ptr;
  1131. } else {
  1132. verbose("unknown return type %d of func %d\n",
  1133. fn->ret_type, func_id);
  1134. return -EINVAL;
  1135. }
  1136. err = check_map_func_compatibility(meta.map_ptr, func_id);
  1137. if (err)
  1138. return err;
  1139. if (changes_data)
  1140. clear_all_pkt_pointers(env);
  1141. return 0;
  1142. }
  1143. static int check_packet_ptr_add(struct verifier_env *env, struct bpf_insn *insn)
  1144. {
  1145. struct reg_state *regs = env->cur_state.regs;
  1146. struct reg_state *dst_reg = &regs[insn->dst_reg];
  1147. struct reg_state *src_reg = &regs[insn->src_reg];
  1148. struct reg_state tmp_reg;
  1149. s32 imm;
  1150. if (BPF_SRC(insn->code) == BPF_K) {
  1151. /* pkt_ptr += imm */
  1152. imm = insn->imm;
  1153. add_imm:
  1154. if (imm <= 0) {
  1155. verbose("addition of negative constant to packet pointer is not allowed\n");
  1156. return -EACCES;
  1157. }
  1158. if (imm >= MAX_PACKET_OFF ||
  1159. imm + dst_reg->off >= MAX_PACKET_OFF) {
  1160. verbose("constant %d is too large to add to packet pointer\n",
  1161. imm);
  1162. return -EACCES;
  1163. }
  1164. /* a constant was added to pkt_ptr.
  1165. * Remember it while keeping the same 'id'
  1166. */
  1167. dst_reg->off += imm;
  1168. } else {
  1169. if (src_reg->type == PTR_TO_PACKET) {
  1170. /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
  1171. tmp_reg = *dst_reg; /* save r7 state */
  1172. *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
  1173. src_reg = &tmp_reg; /* pretend it's src_reg state */
  1174. /* if the checks below reject it, the copy won't matter,
  1175. * since we're rejecting the whole program. If all ok,
  1176. * then imm22 state will be added to r7
  1177. * and r7 will be pkt(id=0,off=22,r=62) while
  1178. * r6 will stay as pkt(id=0,off=0,r=62)
  1179. */
  1180. }
  1181. if (src_reg->type == CONST_IMM) {
  1182. /* pkt_ptr += reg where reg is known constant */
  1183. imm = src_reg->imm;
  1184. goto add_imm;
  1185. }
  1186. /* disallow pkt_ptr += reg
  1187. * if reg is not uknown_value with guaranteed zero upper bits
  1188. * otherwise pkt_ptr may overflow and addition will become
  1189. * subtraction which is not allowed
  1190. */
  1191. if (src_reg->type != UNKNOWN_VALUE) {
  1192. verbose("cannot add '%s' to ptr_to_packet\n",
  1193. reg_type_str[src_reg->type]);
  1194. return -EACCES;
  1195. }
  1196. if (src_reg->imm < 48) {
  1197. verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
  1198. src_reg->imm);
  1199. return -EACCES;
  1200. }
  1201. /* dst_reg stays as pkt_ptr type and since some positive
  1202. * integer value was added to the pointer, increment its 'id'
  1203. */
  1204. dst_reg->id = ++env->id_gen;
  1205. /* something was added to pkt_ptr, set range and off to zero */
  1206. dst_reg->off = 0;
  1207. dst_reg->range = 0;
  1208. }
  1209. return 0;
  1210. }
  1211. static int evaluate_reg_alu(struct verifier_env *env, struct bpf_insn *insn)
  1212. {
  1213. struct reg_state *regs = env->cur_state.regs;
  1214. struct reg_state *dst_reg = &regs[insn->dst_reg];
  1215. u8 opcode = BPF_OP(insn->code);
  1216. s64 imm_log2;
  1217. /* for type == UNKNOWN_VALUE:
  1218. * imm > 0 -> number of zero upper bits
  1219. * imm == 0 -> don't track which is the same as all bits can be non-zero
  1220. */
  1221. if (BPF_SRC(insn->code) == BPF_X) {
  1222. struct reg_state *src_reg = &regs[insn->src_reg];
  1223. if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
  1224. dst_reg->imm && opcode == BPF_ADD) {
  1225. /* dreg += sreg
  1226. * where both have zero upper bits. Adding them
  1227. * can only result making one more bit non-zero
  1228. * in the larger value.
  1229. * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
  1230. * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
  1231. */
  1232. dst_reg->imm = min(dst_reg->imm, src_reg->imm);
  1233. dst_reg->imm--;
  1234. return 0;
  1235. }
  1236. if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
  1237. dst_reg->imm && opcode == BPF_ADD) {
  1238. /* dreg += sreg
  1239. * where dreg has zero upper bits and sreg is const.
  1240. * Adding them can only result making one more bit
  1241. * non-zero in the larger value.
  1242. */
  1243. imm_log2 = __ilog2_u64((long long)src_reg->imm);
  1244. dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
  1245. dst_reg->imm--;
  1246. return 0;
  1247. }
  1248. /* all other cases non supported yet, just mark dst_reg */
  1249. dst_reg->imm = 0;
  1250. return 0;
  1251. }
  1252. /* sign extend 32-bit imm into 64-bit to make sure that
  1253. * negative values occupy bit 63. Note ilog2() would have
  1254. * been incorrect, since sizeof(insn->imm) == 4
  1255. */
  1256. imm_log2 = __ilog2_u64((long long)insn->imm);
  1257. if (dst_reg->imm && opcode == BPF_LSH) {
  1258. /* reg <<= imm
  1259. * if reg was a result of 2 byte load, then its imm == 48
  1260. * which means that upper 48 bits are zero and shifting this reg
  1261. * left by 4 would mean that upper 44 bits are still zero
  1262. */
  1263. dst_reg->imm -= insn->imm;
  1264. } else if (dst_reg->imm && opcode == BPF_MUL) {
  1265. /* reg *= imm
  1266. * if multiplying by 14 subtract 4
  1267. * This is conservative calculation of upper zero bits.
  1268. * It's not trying to special case insn->imm == 1 or 0 cases
  1269. */
  1270. dst_reg->imm -= imm_log2 + 1;
  1271. } else if (opcode == BPF_AND) {
  1272. /* reg &= imm */
  1273. dst_reg->imm = 63 - imm_log2;
  1274. } else if (dst_reg->imm && opcode == BPF_ADD) {
  1275. /* reg += imm */
  1276. dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
  1277. dst_reg->imm--;
  1278. } else if (opcode == BPF_RSH) {
  1279. /* reg >>= imm
  1280. * which means that after right shift, upper bits will be zero
  1281. * note that verifier already checked that
  1282. * 0 <= imm < 64 for shift insn
  1283. */
  1284. dst_reg->imm += insn->imm;
  1285. if (unlikely(dst_reg->imm > 64))
  1286. /* some dumb code did:
  1287. * r2 = *(u32 *)mem;
  1288. * r2 >>= 32;
  1289. * and all bits are zero now */
  1290. dst_reg->imm = 64;
  1291. } else {
  1292. /* all other alu ops, means that we don't know what will
  1293. * happen to the value, mark it with unknown number of zero bits
  1294. */
  1295. dst_reg->imm = 0;
  1296. }
  1297. if (dst_reg->imm < 0) {
  1298. /* all 64 bits of the register can contain non-zero bits
  1299. * and such value cannot be added to ptr_to_packet, since it
  1300. * may overflow, mark it as unknown to avoid further eval
  1301. */
  1302. dst_reg->imm = 0;
  1303. }
  1304. return 0;
  1305. }
  1306. static int evaluate_reg_imm_alu(struct verifier_env *env, struct bpf_insn *insn)
  1307. {
  1308. struct reg_state *regs = env->cur_state.regs;
  1309. struct reg_state *dst_reg = &regs[insn->dst_reg];
  1310. struct reg_state *src_reg = &regs[insn->src_reg];
  1311. u8 opcode = BPF_OP(insn->code);
  1312. /* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
  1313. * Don't care about overflow or negative values, just add them
  1314. */
  1315. if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
  1316. dst_reg->imm += insn->imm;
  1317. else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
  1318. src_reg->type == CONST_IMM)
  1319. dst_reg->imm += src_reg->imm;
  1320. else
  1321. mark_reg_unknown_value(regs, insn->dst_reg);
  1322. return 0;
  1323. }
  1324. /* check validity of 32-bit and 64-bit arithmetic operations */
  1325. static int check_alu_op(struct verifier_env *env, struct bpf_insn *insn)
  1326. {
  1327. struct reg_state *regs = env->cur_state.regs, *dst_reg;
  1328. u8 opcode = BPF_OP(insn->code);
  1329. int err;
  1330. if (opcode == BPF_END || opcode == BPF_NEG) {
  1331. if (opcode == BPF_NEG) {
  1332. if (BPF_SRC(insn->code) != 0 ||
  1333. insn->src_reg != BPF_REG_0 ||
  1334. insn->off != 0 || insn->imm != 0) {
  1335. verbose("BPF_NEG uses reserved fields\n");
  1336. return -EINVAL;
  1337. }
  1338. } else {
  1339. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  1340. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
  1341. verbose("BPF_END uses reserved fields\n");
  1342. return -EINVAL;
  1343. }
  1344. }
  1345. /* check src operand */
  1346. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1347. if (err)
  1348. return err;
  1349. if (is_pointer_value(env, insn->dst_reg)) {
  1350. verbose("R%d pointer arithmetic prohibited\n",
  1351. insn->dst_reg);
  1352. return -EACCES;
  1353. }
  1354. /* check dest operand */
  1355. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1356. if (err)
  1357. return err;
  1358. } else if (opcode == BPF_MOV) {
  1359. if (BPF_SRC(insn->code) == BPF_X) {
  1360. if (insn->imm != 0 || insn->off != 0) {
  1361. verbose("BPF_MOV uses reserved fields\n");
  1362. return -EINVAL;
  1363. }
  1364. /* check src operand */
  1365. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1366. if (err)
  1367. return err;
  1368. } else {
  1369. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  1370. verbose("BPF_MOV uses reserved fields\n");
  1371. return -EINVAL;
  1372. }
  1373. }
  1374. /* check dest operand */
  1375. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1376. if (err)
  1377. return err;
  1378. if (BPF_SRC(insn->code) == BPF_X) {
  1379. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  1380. /* case: R1 = R2
  1381. * copy register state to dest reg
  1382. */
  1383. regs[insn->dst_reg] = regs[insn->src_reg];
  1384. } else {
  1385. if (is_pointer_value(env, insn->src_reg)) {
  1386. verbose("R%d partial copy of pointer\n",
  1387. insn->src_reg);
  1388. return -EACCES;
  1389. }
  1390. regs[insn->dst_reg].type = UNKNOWN_VALUE;
  1391. regs[insn->dst_reg].map_ptr = NULL;
  1392. }
  1393. } else {
  1394. /* case: R = imm
  1395. * remember the value we stored into this reg
  1396. */
  1397. regs[insn->dst_reg].type = CONST_IMM;
  1398. regs[insn->dst_reg].imm = insn->imm;
  1399. }
  1400. } else if (opcode > BPF_END) {
  1401. verbose("invalid BPF_ALU opcode %x\n", opcode);
  1402. return -EINVAL;
  1403. } else { /* all other ALU ops: and, sub, xor, add, ... */
  1404. if (BPF_SRC(insn->code) == BPF_X) {
  1405. if (insn->imm != 0 || insn->off != 0) {
  1406. verbose("BPF_ALU uses reserved fields\n");
  1407. return -EINVAL;
  1408. }
  1409. /* check src1 operand */
  1410. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1411. if (err)
  1412. return err;
  1413. } else {
  1414. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  1415. verbose("BPF_ALU uses reserved fields\n");
  1416. return -EINVAL;
  1417. }
  1418. }
  1419. /* check src2 operand */
  1420. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1421. if (err)
  1422. return err;
  1423. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  1424. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  1425. verbose("div by zero\n");
  1426. return -EINVAL;
  1427. }
  1428. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  1429. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  1430. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  1431. if (insn->imm < 0 || insn->imm >= size) {
  1432. verbose("invalid shift %d\n", insn->imm);
  1433. return -EINVAL;
  1434. }
  1435. }
  1436. /* check dest operand */
  1437. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  1438. if (err)
  1439. return err;
  1440. dst_reg = &regs[insn->dst_reg];
  1441. /* pattern match 'bpf_add Rx, imm' instruction */
  1442. if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
  1443. dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
  1444. dst_reg->type = PTR_TO_STACK;
  1445. dst_reg->imm = insn->imm;
  1446. return 0;
  1447. } else if (opcode == BPF_ADD &&
  1448. BPF_CLASS(insn->code) == BPF_ALU64 &&
  1449. (dst_reg->type == PTR_TO_PACKET ||
  1450. (BPF_SRC(insn->code) == BPF_X &&
  1451. regs[insn->src_reg].type == PTR_TO_PACKET))) {
  1452. /* ptr_to_packet += K|X */
  1453. return check_packet_ptr_add(env, insn);
  1454. } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
  1455. dst_reg->type == UNKNOWN_VALUE &&
  1456. env->allow_ptr_leaks) {
  1457. /* unknown += K|X */
  1458. return evaluate_reg_alu(env, insn);
  1459. } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
  1460. dst_reg->type == CONST_IMM &&
  1461. env->allow_ptr_leaks) {
  1462. /* reg_imm += K|X */
  1463. return evaluate_reg_imm_alu(env, insn);
  1464. } else if (is_pointer_value(env, insn->dst_reg)) {
  1465. verbose("R%d pointer arithmetic prohibited\n",
  1466. insn->dst_reg);
  1467. return -EACCES;
  1468. } else if (BPF_SRC(insn->code) == BPF_X &&
  1469. is_pointer_value(env, insn->src_reg)) {
  1470. verbose("R%d pointer arithmetic prohibited\n",
  1471. insn->src_reg);
  1472. return -EACCES;
  1473. }
  1474. /* mark dest operand */
  1475. mark_reg_unknown_value(regs, insn->dst_reg);
  1476. }
  1477. return 0;
  1478. }
  1479. static void find_good_pkt_pointers(struct verifier_env *env,
  1480. struct reg_state *dst_reg)
  1481. {
  1482. struct verifier_state *state = &env->cur_state;
  1483. struct reg_state *regs = state->regs, *reg;
  1484. int i;
  1485. /* r2 = r3;
  1486. * r2 += 8
  1487. * if (r2 > pkt_end) goto somewhere
  1488. * r2 == dst_reg, pkt_end == src_reg,
  1489. * r2=pkt(id=n,off=8,r=0)
  1490. * r3=pkt(id=n,off=0,r=0)
  1491. * find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
  1492. * so that range of bytes [r3, r3 + 8) is safe to access
  1493. */
  1494. for (i = 0; i < MAX_BPF_REG; i++)
  1495. if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
  1496. regs[i].range = dst_reg->off;
  1497. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  1498. if (state->stack_slot_type[i] != STACK_SPILL)
  1499. continue;
  1500. reg = &state->spilled_regs[i / BPF_REG_SIZE];
  1501. if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
  1502. reg->range = dst_reg->off;
  1503. }
  1504. }
  1505. static int check_cond_jmp_op(struct verifier_env *env,
  1506. struct bpf_insn *insn, int *insn_idx)
  1507. {
  1508. struct reg_state *regs = env->cur_state.regs, *dst_reg;
  1509. struct verifier_state *other_branch;
  1510. u8 opcode = BPF_OP(insn->code);
  1511. int err;
  1512. if (opcode > BPF_EXIT) {
  1513. verbose("invalid BPF_JMP opcode %x\n", opcode);
  1514. return -EINVAL;
  1515. }
  1516. if (BPF_SRC(insn->code) == BPF_X) {
  1517. if (insn->imm != 0) {
  1518. verbose("BPF_JMP uses reserved fields\n");
  1519. return -EINVAL;
  1520. }
  1521. /* check src1 operand */
  1522. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1523. if (err)
  1524. return err;
  1525. if (is_pointer_value(env, insn->src_reg)) {
  1526. verbose("R%d pointer comparison prohibited\n",
  1527. insn->src_reg);
  1528. return -EACCES;
  1529. }
  1530. } else {
  1531. if (insn->src_reg != BPF_REG_0) {
  1532. verbose("BPF_JMP uses reserved fields\n");
  1533. return -EINVAL;
  1534. }
  1535. }
  1536. /* check src2 operand */
  1537. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1538. if (err)
  1539. return err;
  1540. dst_reg = &regs[insn->dst_reg];
  1541. /* detect if R == 0 where R was initialized to zero earlier */
  1542. if (BPF_SRC(insn->code) == BPF_K &&
  1543. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  1544. dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
  1545. if (opcode == BPF_JEQ) {
  1546. /* if (imm == imm) goto pc+off;
  1547. * only follow the goto, ignore fall-through
  1548. */
  1549. *insn_idx += insn->off;
  1550. return 0;
  1551. } else {
  1552. /* if (imm != imm) goto pc+off;
  1553. * only follow fall-through branch, since
  1554. * that's where the program will go
  1555. */
  1556. return 0;
  1557. }
  1558. }
  1559. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  1560. if (!other_branch)
  1561. return -EFAULT;
  1562. /* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
  1563. if (BPF_SRC(insn->code) == BPF_K &&
  1564. insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  1565. dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  1566. if (opcode == BPF_JEQ) {
  1567. /* next fallthrough insn can access memory via
  1568. * this register
  1569. */
  1570. regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1571. /* branch targer cannot access it, since reg == 0 */
  1572. mark_reg_unknown_value(other_branch->regs,
  1573. insn->dst_reg);
  1574. } else {
  1575. other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1576. mark_reg_unknown_value(regs, insn->dst_reg);
  1577. }
  1578. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
  1579. dst_reg->type == PTR_TO_PACKET &&
  1580. regs[insn->src_reg].type == PTR_TO_PACKET_END) {
  1581. find_good_pkt_pointers(env, dst_reg);
  1582. } else if (is_pointer_value(env, insn->dst_reg)) {
  1583. verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
  1584. return -EACCES;
  1585. }
  1586. if (log_level)
  1587. print_verifier_state(&env->cur_state);
  1588. return 0;
  1589. }
  1590. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  1591. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  1592. {
  1593. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  1594. return (struct bpf_map *) (unsigned long) imm64;
  1595. }
  1596. /* verify BPF_LD_IMM64 instruction */
  1597. static int check_ld_imm(struct verifier_env *env, struct bpf_insn *insn)
  1598. {
  1599. struct reg_state *regs = env->cur_state.regs;
  1600. int err;
  1601. if (BPF_SIZE(insn->code) != BPF_DW) {
  1602. verbose("invalid BPF_LD_IMM insn\n");
  1603. return -EINVAL;
  1604. }
  1605. if (insn->off != 0) {
  1606. verbose("BPF_LD_IMM64 uses reserved fields\n");
  1607. return -EINVAL;
  1608. }
  1609. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1610. if (err)
  1611. return err;
  1612. if (insn->src_reg == 0)
  1613. /* generic move 64-bit immediate into a register */
  1614. return 0;
  1615. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  1616. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  1617. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  1618. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  1619. return 0;
  1620. }
  1621. static bool may_access_skb(enum bpf_prog_type type)
  1622. {
  1623. switch (type) {
  1624. case BPF_PROG_TYPE_SOCKET_FILTER:
  1625. case BPF_PROG_TYPE_SCHED_CLS:
  1626. case BPF_PROG_TYPE_SCHED_ACT:
  1627. return true;
  1628. default:
  1629. return false;
  1630. }
  1631. }
  1632. /* verify safety of LD_ABS|LD_IND instructions:
  1633. * - they can only appear in the programs where ctx == skb
  1634. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  1635. * preserve R6-R9, and store return value into R0
  1636. *
  1637. * Implicit input:
  1638. * ctx == skb == R6 == CTX
  1639. *
  1640. * Explicit input:
  1641. * SRC == any register
  1642. * IMM == 32-bit immediate
  1643. *
  1644. * Output:
  1645. * R0 - 8/16/32-bit skb data converted to cpu endianness
  1646. */
  1647. static int check_ld_abs(struct verifier_env *env, struct bpf_insn *insn)
  1648. {
  1649. struct reg_state *regs = env->cur_state.regs;
  1650. u8 mode = BPF_MODE(insn->code);
  1651. struct reg_state *reg;
  1652. int i, err;
  1653. if (!may_access_skb(env->prog->type)) {
  1654. verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
  1655. return -EINVAL;
  1656. }
  1657. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  1658. BPF_SIZE(insn->code) == BPF_DW ||
  1659. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  1660. verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
  1661. return -EINVAL;
  1662. }
  1663. /* check whether implicit source operand (register R6) is readable */
  1664. err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
  1665. if (err)
  1666. return err;
  1667. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  1668. verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  1669. return -EINVAL;
  1670. }
  1671. if (mode == BPF_IND) {
  1672. /* check explicit source operand */
  1673. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1674. if (err)
  1675. return err;
  1676. }
  1677. /* reset caller saved regs to unreadable */
  1678. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  1679. reg = regs + caller_saved[i];
  1680. reg->type = NOT_INIT;
  1681. reg->imm = 0;
  1682. }
  1683. /* mark destination R0 register as readable, since it contains
  1684. * the value fetched from the packet
  1685. */
  1686. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  1687. return 0;
  1688. }
  1689. /* non-recursive DFS pseudo code
  1690. * 1 procedure DFS-iterative(G,v):
  1691. * 2 label v as discovered
  1692. * 3 let S be a stack
  1693. * 4 S.push(v)
  1694. * 5 while S is not empty
  1695. * 6 t <- S.pop()
  1696. * 7 if t is what we're looking for:
  1697. * 8 return t
  1698. * 9 for all edges e in G.adjacentEdges(t) do
  1699. * 10 if edge e is already labelled
  1700. * 11 continue with the next edge
  1701. * 12 w <- G.adjacentVertex(t,e)
  1702. * 13 if vertex w is not discovered and not explored
  1703. * 14 label e as tree-edge
  1704. * 15 label w as discovered
  1705. * 16 S.push(w)
  1706. * 17 continue at 5
  1707. * 18 else if vertex w is discovered
  1708. * 19 label e as back-edge
  1709. * 20 else
  1710. * 21 // vertex w is explored
  1711. * 22 label e as forward- or cross-edge
  1712. * 23 label t as explored
  1713. * 24 S.pop()
  1714. *
  1715. * convention:
  1716. * 0x10 - discovered
  1717. * 0x11 - discovered and fall-through edge labelled
  1718. * 0x12 - discovered and fall-through and branch edges labelled
  1719. * 0x20 - explored
  1720. */
  1721. enum {
  1722. DISCOVERED = 0x10,
  1723. EXPLORED = 0x20,
  1724. FALLTHROUGH = 1,
  1725. BRANCH = 2,
  1726. };
  1727. #define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
  1728. static int *insn_stack; /* stack of insns to process */
  1729. static int cur_stack; /* current stack index */
  1730. static int *insn_state;
  1731. /* t, w, e - match pseudo-code above:
  1732. * t - index of current instruction
  1733. * w - next instruction
  1734. * e - edge
  1735. */
  1736. static int push_insn(int t, int w, int e, struct verifier_env *env)
  1737. {
  1738. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  1739. return 0;
  1740. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  1741. return 0;
  1742. if (w < 0 || w >= env->prog->len) {
  1743. verbose("jump out of range from insn %d to %d\n", t, w);
  1744. return -EINVAL;
  1745. }
  1746. if (e == BRANCH)
  1747. /* mark branch target for state pruning */
  1748. env->explored_states[w] = STATE_LIST_MARK;
  1749. if (insn_state[w] == 0) {
  1750. /* tree-edge */
  1751. insn_state[t] = DISCOVERED | e;
  1752. insn_state[w] = DISCOVERED;
  1753. if (cur_stack >= env->prog->len)
  1754. return -E2BIG;
  1755. insn_stack[cur_stack++] = w;
  1756. return 1;
  1757. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  1758. verbose("back-edge from insn %d to %d\n", t, w);
  1759. return -EINVAL;
  1760. } else if (insn_state[w] == EXPLORED) {
  1761. /* forward- or cross-edge */
  1762. insn_state[t] = DISCOVERED | e;
  1763. } else {
  1764. verbose("insn state internal bug\n");
  1765. return -EFAULT;
  1766. }
  1767. return 0;
  1768. }
  1769. /* non-recursive depth-first-search to detect loops in BPF program
  1770. * loop == back-edge in directed graph
  1771. */
  1772. static int check_cfg(struct verifier_env *env)
  1773. {
  1774. struct bpf_insn *insns = env->prog->insnsi;
  1775. int insn_cnt = env->prog->len;
  1776. int ret = 0;
  1777. int i, t;
  1778. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1779. if (!insn_state)
  1780. return -ENOMEM;
  1781. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1782. if (!insn_stack) {
  1783. kfree(insn_state);
  1784. return -ENOMEM;
  1785. }
  1786. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  1787. insn_stack[0] = 0; /* 0 is the first instruction */
  1788. cur_stack = 1;
  1789. peek_stack:
  1790. if (cur_stack == 0)
  1791. goto check_state;
  1792. t = insn_stack[cur_stack - 1];
  1793. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  1794. u8 opcode = BPF_OP(insns[t].code);
  1795. if (opcode == BPF_EXIT) {
  1796. goto mark_explored;
  1797. } else if (opcode == BPF_CALL) {
  1798. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1799. if (ret == 1)
  1800. goto peek_stack;
  1801. else if (ret < 0)
  1802. goto err_free;
  1803. if (t + 1 < insn_cnt)
  1804. env->explored_states[t + 1] = STATE_LIST_MARK;
  1805. } else if (opcode == BPF_JA) {
  1806. if (BPF_SRC(insns[t].code) != BPF_K) {
  1807. ret = -EINVAL;
  1808. goto err_free;
  1809. }
  1810. /* unconditional jump with single edge */
  1811. ret = push_insn(t, t + insns[t].off + 1,
  1812. FALLTHROUGH, env);
  1813. if (ret == 1)
  1814. goto peek_stack;
  1815. else if (ret < 0)
  1816. goto err_free;
  1817. /* tell verifier to check for equivalent states
  1818. * after every call and jump
  1819. */
  1820. if (t + 1 < insn_cnt)
  1821. env->explored_states[t + 1] = STATE_LIST_MARK;
  1822. } else {
  1823. /* conditional jump with two edges */
  1824. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1825. if (ret == 1)
  1826. goto peek_stack;
  1827. else if (ret < 0)
  1828. goto err_free;
  1829. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  1830. if (ret == 1)
  1831. goto peek_stack;
  1832. else if (ret < 0)
  1833. goto err_free;
  1834. }
  1835. } else {
  1836. /* all other non-branch instructions with single
  1837. * fall-through edge
  1838. */
  1839. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1840. if (ret == 1)
  1841. goto peek_stack;
  1842. else if (ret < 0)
  1843. goto err_free;
  1844. }
  1845. mark_explored:
  1846. insn_state[t] = EXPLORED;
  1847. if (cur_stack-- <= 0) {
  1848. verbose("pop stack internal bug\n");
  1849. ret = -EFAULT;
  1850. goto err_free;
  1851. }
  1852. goto peek_stack;
  1853. check_state:
  1854. for (i = 0; i < insn_cnt; i++) {
  1855. if (insn_state[i] != EXPLORED) {
  1856. verbose("unreachable insn %d\n", i);
  1857. ret = -EINVAL;
  1858. goto err_free;
  1859. }
  1860. }
  1861. ret = 0; /* cfg looks good */
  1862. err_free:
  1863. kfree(insn_state);
  1864. kfree(insn_stack);
  1865. return ret;
  1866. }
  1867. /* the following conditions reduce the number of explored insns
  1868. * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
  1869. */
  1870. static bool compare_ptrs_to_packet(struct reg_state *old, struct reg_state *cur)
  1871. {
  1872. if (old->id != cur->id)
  1873. return false;
  1874. /* old ptr_to_packet is more conservative, since it allows smaller
  1875. * range. Ex:
  1876. * old(off=0,r=10) is equal to cur(off=0,r=20), because
  1877. * old(off=0,r=10) means that with range=10 the verifier proceeded
  1878. * further and found no issues with the program. Now we're in the same
  1879. * spot with cur(off=0,r=20), so we're safe too, since anything further
  1880. * will only be looking at most 10 bytes after this pointer.
  1881. */
  1882. if (old->off == cur->off && old->range < cur->range)
  1883. return true;
  1884. /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
  1885. * since both cannot be used for packet access and safe(old)
  1886. * pointer has smaller off that could be used for further
  1887. * 'if (ptr > data_end)' check
  1888. * Ex:
  1889. * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
  1890. * that we cannot access the packet.
  1891. * The safe range is:
  1892. * [ptr, ptr + range - off)
  1893. * so whenever off >=range, it means no safe bytes from this pointer.
  1894. * When comparing old->off <= cur->off, it means that older code
  1895. * went with smaller offset and that offset was later
  1896. * used to figure out the safe range after 'if (ptr > data_end)' check
  1897. * Say, 'old' state was explored like:
  1898. * ... R3(off=0, r=0)
  1899. * R4 = R3 + 20
  1900. * ... now R4(off=20,r=0) <-- here
  1901. * if (R4 > data_end)
  1902. * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
  1903. * ... the code further went all the way to bpf_exit.
  1904. * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
  1905. * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
  1906. * goes further, such cur_R4 will give larger safe packet range after
  1907. * 'if (R4 > data_end)' and all further insn were already good with r=20,
  1908. * so they will be good with r=30 and we can prune the search.
  1909. */
  1910. if (old->off <= cur->off &&
  1911. old->off >= old->range && cur->off >= cur->range)
  1912. return true;
  1913. return false;
  1914. }
  1915. /* compare two verifier states
  1916. *
  1917. * all states stored in state_list are known to be valid, since
  1918. * verifier reached 'bpf_exit' instruction through them
  1919. *
  1920. * this function is called when verifier exploring different branches of
  1921. * execution popped from the state stack. If it sees an old state that has
  1922. * more strict register state and more strict stack state then this execution
  1923. * branch doesn't need to be explored further, since verifier already
  1924. * concluded that more strict state leads to valid finish.
  1925. *
  1926. * Therefore two states are equivalent if register state is more conservative
  1927. * and explored stack state is more conservative than the current one.
  1928. * Example:
  1929. * explored current
  1930. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  1931. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  1932. *
  1933. * In other words if current stack state (one being explored) has more
  1934. * valid slots than old one that already passed validation, it means
  1935. * the verifier can stop exploring and conclude that current state is valid too
  1936. *
  1937. * Similarly with registers. If explored state has register type as invalid
  1938. * whereas register type in current state is meaningful, it means that
  1939. * the current state will reach 'bpf_exit' instruction safely
  1940. */
  1941. static bool states_equal(struct verifier_state *old, struct verifier_state *cur)
  1942. {
  1943. struct reg_state *rold, *rcur;
  1944. int i;
  1945. for (i = 0; i < MAX_BPF_REG; i++) {
  1946. rold = &old->regs[i];
  1947. rcur = &cur->regs[i];
  1948. if (memcmp(rold, rcur, sizeof(*rold)) == 0)
  1949. continue;
  1950. if (rold->type == NOT_INIT ||
  1951. (rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT))
  1952. continue;
  1953. if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
  1954. compare_ptrs_to_packet(rold, rcur))
  1955. continue;
  1956. return false;
  1957. }
  1958. for (i = 0; i < MAX_BPF_STACK; i++) {
  1959. if (old->stack_slot_type[i] == STACK_INVALID)
  1960. continue;
  1961. if (old->stack_slot_type[i] != cur->stack_slot_type[i])
  1962. /* Ex: old explored (safe) state has STACK_SPILL in
  1963. * this stack slot, but current has has STACK_MISC ->
  1964. * this verifier states are not equivalent,
  1965. * return false to continue verification of this path
  1966. */
  1967. return false;
  1968. if (i % BPF_REG_SIZE)
  1969. continue;
  1970. if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
  1971. &cur->spilled_regs[i / BPF_REG_SIZE],
  1972. sizeof(old->spilled_regs[0])))
  1973. /* when explored and current stack slot types are
  1974. * the same, check that stored pointers types
  1975. * are the same as well.
  1976. * Ex: explored safe path could have stored
  1977. * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8}
  1978. * but current path has stored:
  1979. * (struct reg_state) {.type = PTR_TO_STACK, .imm = -16}
  1980. * such verifier states are not equivalent.
  1981. * return false to continue verification of this path
  1982. */
  1983. return false;
  1984. else
  1985. continue;
  1986. }
  1987. return true;
  1988. }
  1989. static int is_state_visited(struct verifier_env *env, int insn_idx)
  1990. {
  1991. struct verifier_state_list *new_sl;
  1992. struct verifier_state_list *sl;
  1993. sl = env->explored_states[insn_idx];
  1994. if (!sl)
  1995. /* this 'insn_idx' instruction wasn't marked, so we will not
  1996. * be doing state search here
  1997. */
  1998. return 0;
  1999. while (sl != STATE_LIST_MARK) {
  2000. if (states_equal(&sl->state, &env->cur_state))
  2001. /* reached equivalent register/stack state,
  2002. * prune the search
  2003. */
  2004. return 1;
  2005. sl = sl->next;
  2006. }
  2007. /* there were no equivalent states, remember current one.
  2008. * technically the current state is not proven to be safe yet,
  2009. * but it will either reach bpf_exit (which means it's safe) or
  2010. * it will be rejected. Since there are no loops, we won't be
  2011. * seeing this 'insn_idx' instruction again on the way to bpf_exit
  2012. */
  2013. new_sl = kmalloc(sizeof(struct verifier_state_list), GFP_USER);
  2014. if (!new_sl)
  2015. return -ENOMEM;
  2016. /* add new state to the head of linked list */
  2017. memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
  2018. new_sl->next = env->explored_states[insn_idx];
  2019. env->explored_states[insn_idx] = new_sl;
  2020. return 0;
  2021. }
  2022. static int do_check(struct verifier_env *env)
  2023. {
  2024. struct verifier_state *state = &env->cur_state;
  2025. struct bpf_insn *insns = env->prog->insnsi;
  2026. struct reg_state *regs = state->regs;
  2027. int insn_cnt = env->prog->len;
  2028. int insn_idx, prev_insn_idx = 0;
  2029. int insn_processed = 0;
  2030. bool do_print_state = false;
  2031. init_reg_state(regs);
  2032. insn_idx = 0;
  2033. for (;;) {
  2034. struct bpf_insn *insn;
  2035. u8 class;
  2036. int err;
  2037. if (insn_idx >= insn_cnt) {
  2038. verbose("invalid insn idx %d insn_cnt %d\n",
  2039. insn_idx, insn_cnt);
  2040. return -EFAULT;
  2041. }
  2042. insn = &insns[insn_idx];
  2043. class = BPF_CLASS(insn->code);
  2044. if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
  2045. verbose("BPF program is too large. Proccessed %d insn\n",
  2046. insn_processed);
  2047. return -E2BIG;
  2048. }
  2049. err = is_state_visited(env, insn_idx);
  2050. if (err < 0)
  2051. return err;
  2052. if (err == 1) {
  2053. /* found equivalent state, can prune the search */
  2054. if (log_level) {
  2055. if (do_print_state)
  2056. verbose("\nfrom %d to %d: safe\n",
  2057. prev_insn_idx, insn_idx);
  2058. else
  2059. verbose("%d: safe\n", insn_idx);
  2060. }
  2061. goto process_bpf_exit;
  2062. }
  2063. if (log_level && do_print_state) {
  2064. verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
  2065. print_verifier_state(&env->cur_state);
  2066. do_print_state = false;
  2067. }
  2068. if (log_level) {
  2069. verbose("%d: ", insn_idx);
  2070. print_bpf_insn(insn);
  2071. }
  2072. if (class == BPF_ALU || class == BPF_ALU64) {
  2073. err = check_alu_op(env, insn);
  2074. if (err)
  2075. return err;
  2076. } else if (class == BPF_LDX) {
  2077. enum bpf_reg_type src_reg_type;
  2078. /* check for reserved fields is already done */
  2079. /* check src operand */
  2080. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2081. if (err)
  2082. return err;
  2083. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  2084. if (err)
  2085. return err;
  2086. src_reg_type = regs[insn->src_reg].type;
  2087. /* check that memory (src_reg + off) is readable,
  2088. * the state of dst_reg will be updated by this func
  2089. */
  2090. err = check_mem_access(env, insn->src_reg, insn->off,
  2091. BPF_SIZE(insn->code), BPF_READ,
  2092. insn->dst_reg);
  2093. if (err)
  2094. return err;
  2095. if (BPF_SIZE(insn->code) != BPF_W &&
  2096. BPF_SIZE(insn->code) != BPF_DW) {
  2097. insn_idx++;
  2098. continue;
  2099. }
  2100. if (insn->imm == 0) {
  2101. /* saw a valid insn
  2102. * dst_reg = *(u32 *)(src_reg + off)
  2103. * use reserved 'imm' field to mark this insn
  2104. */
  2105. insn->imm = src_reg_type;
  2106. } else if (src_reg_type != insn->imm &&
  2107. (src_reg_type == PTR_TO_CTX ||
  2108. insn->imm == PTR_TO_CTX)) {
  2109. /* ABuser program is trying to use the same insn
  2110. * dst_reg = *(u32*) (src_reg + off)
  2111. * with different pointer types:
  2112. * src_reg == ctx in one branch and
  2113. * src_reg == stack|map in some other branch.
  2114. * Reject it.
  2115. */
  2116. verbose("same insn cannot be used with different pointers\n");
  2117. return -EINVAL;
  2118. }
  2119. } else if (class == BPF_STX) {
  2120. enum bpf_reg_type dst_reg_type;
  2121. if (BPF_MODE(insn->code) == BPF_XADD) {
  2122. err = check_xadd(env, insn);
  2123. if (err)
  2124. return err;
  2125. insn_idx++;
  2126. continue;
  2127. }
  2128. /* check src1 operand */
  2129. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2130. if (err)
  2131. return err;
  2132. /* check src2 operand */
  2133. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  2134. if (err)
  2135. return err;
  2136. dst_reg_type = regs[insn->dst_reg].type;
  2137. /* check that memory (dst_reg + off) is writeable */
  2138. err = check_mem_access(env, insn->dst_reg, insn->off,
  2139. BPF_SIZE(insn->code), BPF_WRITE,
  2140. insn->src_reg);
  2141. if (err)
  2142. return err;
  2143. if (insn->imm == 0) {
  2144. insn->imm = dst_reg_type;
  2145. } else if (dst_reg_type != insn->imm &&
  2146. (dst_reg_type == PTR_TO_CTX ||
  2147. insn->imm == PTR_TO_CTX)) {
  2148. verbose("same insn cannot be used with different pointers\n");
  2149. return -EINVAL;
  2150. }
  2151. } else if (class == BPF_ST) {
  2152. if (BPF_MODE(insn->code) != BPF_MEM ||
  2153. insn->src_reg != BPF_REG_0) {
  2154. verbose("BPF_ST uses reserved fields\n");
  2155. return -EINVAL;
  2156. }
  2157. /* check src operand */
  2158. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  2159. if (err)
  2160. return err;
  2161. /* check that memory (dst_reg + off) is writeable */
  2162. err = check_mem_access(env, insn->dst_reg, insn->off,
  2163. BPF_SIZE(insn->code), BPF_WRITE,
  2164. -1);
  2165. if (err)
  2166. return err;
  2167. } else if (class == BPF_JMP) {
  2168. u8 opcode = BPF_OP(insn->code);
  2169. if (opcode == BPF_CALL) {
  2170. if (BPF_SRC(insn->code) != BPF_K ||
  2171. insn->off != 0 ||
  2172. insn->src_reg != BPF_REG_0 ||
  2173. insn->dst_reg != BPF_REG_0) {
  2174. verbose("BPF_CALL uses reserved fields\n");
  2175. return -EINVAL;
  2176. }
  2177. err = check_call(env, insn->imm);
  2178. if (err)
  2179. return err;
  2180. } else if (opcode == BPF_JA) {
  2181. if (BPF_SRC(insn->code) != BPF_K ||
  2182. insn->imm != 0 ||
  2183. insn->src_reg != BPF_REG_0 ||
  2184. insn->dst_reg != BPF_REG_0) {
  2185. verbose("BPF_JA uses reserved fields\n");
  2186. return -EINVAL;
  2187. }
  2188. insn_idx += insn->off + 1;
  2189. continue;
  2190. } else if (opcode == BPF_EXIT) {
  2191. if (BPF_SRC(insn->code) != BPF_K ||
  2192. insn->imm != 0 ||
  2193. insn->src_reg != BPF_REG_0 ||
  2194. insn->dst_reg != BPF_REG_0) {
  2195. verbose("BPF_EXIT uses reserved fields\n");
  2196. return -EINVAL;
  2197. }
  2198. /* eBPF calling convetion is such that R0 is used
  2199. * to return the value from eBPF program.
  2200. * Make sure that it's readable at this time
  2201. * of bpf_exit, which means that program wrote
  2202. * something into it earlier
  2203. */
  2204. err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
  2205. if (err)
  2206. return err;
  2207. if (is_pointer_value(env, BPF_REG_0)) {
  2208. verbose("R0 leaks addr as return value\n");
  2209. return -EACCES;
  2210. }
  2211. process_bpf_exit:
  2212. insn_idx = pop_stack(env, &prev_insn_idx);
  2213. if (insn_idx < 0) {
  2214. break;
  2215. } else {
  2216. do_print_state = true;
  2217. continue;
  2218. }
  2219. } else {
  2220. err = check_cond_jmp_op(env, insn, &insn_idx);
  2221. if (err)
  2222. return err;
  2223. }
  2224. } else if (class == BPF_LD) {
  2225. u8 mode = BPF_MODE(insn->code);
  2226. if (mode == BPF_ABS || mode == BPF_IND) {
  2227. err = check_ld_abs(env, insn);
  2228. if (err)
  2229. return err;
  2230. } else if (mode == BPF_IMM) {
  2231. err = check_ld_imm(env, insn);
  2232. if (err)
  2233. return err;
  2234. insn_idx++;
  2235. } else {
  2236. verbose("invalid BPF_LD mode\n");
  2237. return -EINVAL;
  2238. }
  2239. } else {
  2240. verbose("unknown insn class %d\n", class);
  2241. return -EINVAL;
  2242. }
  2243. insn_idx++;
  2244. }
  2245. verbose("processed %d insns\n", insn_processed);
  2246. return 0;
  2247. }
  2248. static int check_map_prog_compatibility(struct bpf_map *map,
  2249. struct bpf_prog *prog)
  2250. {
  2251. if (prog->type == BPF_PROG_TYPE_PERF_EVENT &&
  2252. (map->map_type == BPF_MAP_TYPE_HASH ||
  2253. map->map_type == BPF_MAP_TYPE_PERCPU_HASH) &&
  2254. (map->map_flags & BPF_F_NO_PREALLOC)) {
  2255. verbose("perf_event programs can only use preallocated hash map\n");
  2256. return -EINVAL;
  2257. }
  2258. return 0;
  2259. }
  2260. /* look for pseudo eBPF instructions that access map FDs and
  2261. * replace them with actual map pointers
  2262. */
  2263. static int replace_map_fd_with_map_ptr(struct verifier_env *env)
  2264. {
  2265. struct bpf_insn *insn = env->prog->insnsi;
  2266. int insn_cnt = env->prog->len;
  2267. int i, j, err;
  2268. for (i = 0; i < insn_cnt; i++, insn++) {
  2269. if (BPF_CLASS(insn->code) == BPF_LDX &&
  2270. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  2271. verbose("BPF_LDX uses reserved fields\n");
  2272. return -EINVAL;
  2273. }
  2274. if (BPF_CLASS(insn->code) == BPF_STX &&
  2275. ((BPF_MODE(insn->code) != BPF_MEM &&
  2276. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  2277. verbose("BPF_STX uses reserved fields\n");
  2278. return -EINVAL;
  2279. }
  2280. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  2281. struct bpf_map *map;
  2282. struct fd f;
  2283. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  2284. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  2285. insn[1].off != 0) {
  2286. verbose("invalid bpf_ld_imm64 insn\n");
  2287. return -EINVAL;
  2288. }
  2289. if (insn->src_reg == 0)
  2290. /* valid generic load 64-bit imm */
  2291. goto next_insn;
  2292. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  2293. verbose("unrecognized bpf_ld_imm64 insn\n");
  2294. return -EINVAL;
  2295. }
  2296. f = fdget(insn->imm);
  2297. map = __bpf_map_get(f);
  2298. if (IS_ERR(map)) {
  2299. verbose("fd %d is not pointing to valid bpf_map\n",
  2300. insn->imm);
  2301. return PTR_ERR(map);
  2302. }
  2303. err = check_map_prog_compatibility(map, env->prog);
  2304. if (err) {
  2305. fdput(f);
  2306. return err;
  2307. }
  2308. /* store map pointer inside BPF_LD_IMM64 instruction */
  2309. insn[0].imm = (u32) (unsigned long) map;
  2310. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  2311. /* check whether we recorded this map already */
  2312. for (j = 0; j < env->used_map_cnt; j++)
  2313. if (env->used_maps[j] == map) {
  2314. fdput(f);
  2315. goto next_insn;
  2316. }
  2317. if (env->used_map_cnt >= MAX_USED_MAPS) {
  2318. fdput(f);
  2319. return -E2BIG;
  2320. }
  2321. /* hold the map. If the program is rejected by verifier,
  2322. * the map will be released by release_maps() or it
  2323. * will be used by the valid program until it's unloaded
  2324. * and all maps are released in free_bpf_prog_info()
  2325. */
  2326. map = bpf_map_inc(map, false);
  2327. if (IS_ERR(map)) {
  2328. fdput(f);
  2329. return PTR_ERR(map);
  2330. }
  2331. env->used_maps[env->used_map_cnt++] = map;
  2332. fdput(f);
  2333. next_insn:
  2334. insn++;
  2335. i++;
  2336. }
  2337. }
  2338. /* now all pseudo BPF_LD_IMM64 instructions load valid
  2339. * 'struct bpf_map *' into a register instead of user map_fd.
  2340. * These pointers will be used later by verifier to validate map access.
  2341. */
  2342. return 0;
  2343. }
  2344. /* drop refcnt of maps used by the rejected program */
  2345. static void release_maps(struct verifier_env *env)
  2346. {
  2347. int i;
  2348. for (i = 0; i < env->used_map_cnt; i++)
  2349. bpf_map_put(env->used_maps[i]);
  2350. }
  2351. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  2352. static void convert_pseudo_ld_imm64(struct verifier_env *env)
  2353. {
  2354. struct bpf_insn *insn = env->prog->insnsi;
  2355. int insn_cnt = env->prog->len;
  2356. int i;
  2357. for (i = 0; i < insn_cnt; i++, insn++)
  2358. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  2359. insn->src_reg = 0;
  2360. }
  2361. /* convert load instructions that access fields of 'struct __sk_buff'
  2362. * into sequence of instructions that access fields of 'struct sk_buff'
  2363. */
  2364. static int convert_ctx_accesses(struct verifier_env *env)
  2365. {
  2366. struct bpf_insn *insn = env->prog->insnsi;
  2367. int insn_cnt = env->prog->len;
  2368. struct bpf_insn insn_buf[16];
  2369. struct bpf_prog *new_prog;
  2370. enum bpf_access_type type;
  2371. int i;
  2372. if (!env->prog->aux->ops->convert_ctx_access)
  2373. return 0;
  2374. for (i = 0; i < insn_cnt; i++, insn++) {
  2375. u32 insn_delta, cnt;
  2376. if (insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  2377. insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
  2378. type = BPF_READ;
  2379. else if (insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  2380. insn->code == (BPF_STX | BPF_MEM | BPF_DW))
  2381. type = BPF_WRITE;
  2382. else
  2383. continue;
  2384. if (insn->imm != PTR_TO_CTX) {
  2385. /* clear internal mark */
  2386. insn->imm = 0;
  2387. continue;
  2388. }
  2389. cnt = env->prog->aux->ops->
  2390. convert_ctx_access(type, insn->dst_reg, insn->src_reg,
  2391. insn->off, insn_buf, env->prog);
  2392. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  2393. verbose("bpf verifier is misconfigured\n");
  2394. return -EINVAL;
  2395. }
  2396. new_prog = bpf_patch_insn_single(env->prog, i, insn_buf, cnt);
  2397. if (!new_prog)
  2398. return -ENOMEM;
  2399. insn_delta = cnt - 1;
  2400. /* keep walking new program and skip insns we just inserted */
  2401. env->prog = new_prog;
  2402. insn = new_prog->insnsi + i + insn_delta;
  2403. insn_cnt += insn_delta;
  2404. i += insn_delta;
  2405. }
  2406. return 0;
  2407. }
  2408. static void free_states(struct verifier_env *env)
  2409. {
  2410. struct verifier_state_list *sl, *sln;
  2411. int i;
  2412. if (!env->explored_states)
  2413. return;
  2414. for (i = 0; i < env->prog->len; i++) {
  2415. sl = env->explored_states[i];
  2416. if (sl)
  2417. while (sl != STATE_LIST_MARK) {
  2418. sln = sl->next;
  2419. kfree(sl);
  2420. sl = sln;
  2421. }
  2422. }
  2423. kfree(env->explored_states);
  2424. }
  2425. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  2426. {
  2427. char __user *log_ubuf = NULL;
  2428. struct verifier_env *env;
  2429. int ret = -EINVAL;
  2430. if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
  2431. return -E2BIG;
  2432. /* 'struct verifier_env' can be global, but since it's not small,
  2433. * allocate/free it every time bpf_check() is called
  2434. */
  2435. env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL);
  2436. if (!env)
  2437. return -ENOMEM;
  2438. env->prog = *prog;
  2439. /* grab the mutex to protect few globals used by verifier */
  2440. mutex_lock(&bpf_verifier_lock);
  2441. if (attr->log_level || attr->log_buf || attr->log_size) {
  2442. /* user requested verbose verifier output
  2443. * and supplied buffer to store the verification trace
  2444. */
  2445. log_level = attr->log_level;
  2446. log_ubuf = (char __user *) (unsigned long) attr->log_buf;
  2447. log_size = attr->log_size;
  2448. log_len = 0;
  2449. ret = -EINVAL;
  2450. /* log_* values have to be sane */
  2451. if (log_size < 128 || log_size > UINT_MAX >> 8 ||
  2452. log_level == 0 || log_ubuf == NULL)
  2453. goto free_env;
  2454. ret = -ENOMEM;
  2455. log_buf = vmalloc(log_size);
  2456. if (!log_buf)
  2457. goto free_env;
  2458. } else {
  2459. log_level = 0;
  2460. }
  2461. ret = replace_map_fd_with_map_ptr(env);
  2462. if (ret < 0)
  2463. goto skip_full_check;
  2464. env->explored_states = kcalloc(env->prog->len,
  2465. sizeof(struct verifier_state_list *),
  2466. GFP_USER);
  2467. ret = -ENOMEM;
  2468. if (!env->explored_states)
  2469. goto skip_full_check;
  2470. ret = check_cfg(env);
  2471. if (ret < 0)
  2472. goto skip_full_check;
  2473. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  2474. ret = do_check(env);
  2475. skip_full_check:
  2476. while (pop_stack(env, NULL) >= 0);
  2477. free_states(env);
  2478. if (ret == 0)
  2479. /* program is valid, convert *(u32*)(ctx + off) accesses */
  2480. ret = convert_ctx_accesses(env);
  2481. if (log_level && log_len >= log_size - 1) {
  2482. BUG_ON(log_len >= log_size);
  2483. /* verifier log exceeded user supplied buffer */
  2484. ret = -ENOSPC;
  2485. /* fall through to return what was recorded */
  2486. }
  2487. /* copy verifier log back to user space including trailing zero */
  2488. if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
  2489. ret = -EFAULT;
  2490. goto free_log_buf;
  2491. }
  2492. if (ret == 0 && env->used_map_cnt) {
  2493. /* if program passed verifier, update used_maps in bpf_prog_info */
  2494. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  2495. sizeof(env->used_maps[0]),
  2496. GFP_KERNEL);
  2497. if (!env->prog->aux->used_maps) {
  2498. ret = -ENOMEM;
  2499. goto free_log_buf;
  2500. }
  2501. memcpy(env->prog->aux->used_maps, env->used_maps,
  2502. sizeof(env->used_maps[0]) * env->used_map_cnt);
  2503. env->prog->aux->used_map_cnt = env->used_map_cnt;
  2504. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  2505. * bpf_ld_imm64 instructions
  2506. */
  2507. convert_pseudo_ld_imm64(env);
  2508. }
  2509. free_log_buf:
  2510. if (log_level)
  2511. vfree(log_buf);
  2512. free_env:
  2513. if (!env->prog->aux->used_maps)
  2514. /* if we didn't copy map pointers into bpf_prog_info, release
  2515. * them now. Otherwise free_bpf_prog_info() will release them.
  2516. */
  2517. release_maps(env);
  2518. *prog = env->prog;
  2519. kfree(env);
  2520. mutex_unlock(&bpf_verifier_lock);
  2521. return ret;
  2522. }