verifier.c 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749
  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/bpf_verifier.h>
  18. #include <linux/filter.h>
  19. #include <net/netlink.h>
  20. #include <linux/file.h>
  21. #include <linux/vmalloc.h>
  22. /* bpf_check() is a static code analyzer that walks eBPF program
  23. * instruction by instruction and updates register/stack state.
  24. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  25. *
  26. * The first pass is depth-first-search to check that the program is a DAG.
  27. * It rejects the following programs:
  28. * - larger than BPF_MAXINSNS insns
  29. * - if loop is present (detected via back-edge)
  30. * - unreachable insns exist (shouldn't be a forest. program = one function)
  31. * - out of bounds or malformed jumps
  32. * The second pass is all possible path descent from the 1st insn.
  33. * Since it's analyzing all pathes through the program, the length of the
  34. * analysis is limited to 32k insn, which may be hit even if total number of
  35. * insn is less then 4K, but there are too many branches that change stack/regs.
  36. * Number of 'branches to be analyzed' is limited to 1k
  37. *
  38. * On entry to each instruction, each register has a type, and the instruction
  39. * changes the types of the registers depending on instruction semantics.
  40. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  41. * copied to R1.
  42. *
  43. * All registers are 64-bit.
  44. * R0 - return register
  45. * R1-R5 argument passing registers
  46. * R6-R9 callee saved registers
  47. * R10 - frame pointer read-only
  48. *
  49. * At the start of BPF program the register R1 contains a pointer to bpf_context
  50. * and has type PTR_TO_CTX.
  51. *
  52. * Verifier tracks arithmetic operations on pointers in case:
  53. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  54. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  55. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  56. * and 2nd arithmetic instruction is pattern matched to recognize
  57. * that it wants to construct a pointer to some element within stack.
  58. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  59. * (and -20 constant is saved for further stack bounds checking).
  60. * Meaning that this reg is a pointer to stack plus known immediate constant.
  61. *
  62. * Most of the time the registers have UNKNOWN_VALUE type, which
  63. * means the register has some value, but it's not a valid pointer.
  64. * (like pointer plus pointer becomes UNKNOWN_VALUE type)
  65. *
  66. * When verifier sees load or store instructions the type of base register
  67. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
  68. * types recognized by check_mem_access() function.
  69. *
  70. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  71. * and the range of [ptr, ptr + map's value_size) is accessible.
  72. *
  73. * registers used to pass values to function calls are checked against
  74. * function argument constraints.
  75. *
  76. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  77. * It means that the register type passed to this function must be
  78. * PTR_TO_STACK and it will be used inside the function as
  79. * 'pointer to map element key'
  80. *
  81. * For example the argument constraints for bpf_map_lookup_elem():
  82. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  83. * .arg1_type = ARG_CONST_MAP_PTR,
  84. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  85. *
  86. * ret_type says that this function returns 'pointer to map elem value or null'
  87. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  88. * 2nd argument should be a pointer to stack, which will be used inside
  89. * the helper function as a pointer to map element key.
  90. *
  91. * On the kernel side the helper function looks like:
  92. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  93. * {
  94. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  95. * void *key = (void *) (unsigned long) r2;
  96. * void *value;
  97. *
  98. * here kernel can access 'key' and 'map' pointers safely, knowing that
  99. * [key, key + map->key_size) bytes are valid and were initialized on
  100. * the stack of eBPF program.
  101. * }
  102. *
  103. * Corresponding eBPF program may look like:
  104. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  105. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  106. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  107. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  108. * here verifier looks at prototype of map_lookup_elem() and sees:
  109. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  110. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  111. *
  112. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  113. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  114. * and were initialized prior to this call.
  115. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  116. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  117. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  118. * returns ether pointer to map value or NULL.
  119. *
  120. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  121. * insn, the register holding that pointer in the true branch changes state to
  122. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  123. * branch. See check_cond_jmp_op().
  124. *
  125. * After the call R0 is set to return type of the function and registers R1-R5
  126. * are set to NOT_INIT to indicate that they are no longer readable.
  127. */
  128. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  129. struct bpf_verifier_stack_elem {
  130. /* verifer state is 'st'
  131. * before processing instruction 'insn_idx'
  132. * and after processing instruction 'prev_insn_idx'
  133. */
  134. struct bpf_verifier_state st;
  135. int insn_idx;
  136. int prev_insn_idx;
  137. struct bpf_verifier_stack_elem *next;
  138. };
  139. #define BPF_COMPLEXITY_LIMIT_INSNS 98304
  140. #define BPF_COMPLEXITY_LIMIT_STACK 1024
  141. struct bpf_call_arg_meta {
  142. struct bpf_map *map_ptr;
  143. bool raw_mode;
  144. bool pkt_access;
  145. int regno;
  146. int access_size;
  147. };
  148. /* verbose verifier prints what it's seeing
  149. * bpf_check() is called under lock, so no race to access these global vars
  150. */
  151. static u32 log_level, log_size, log_len;
  152. static char *log_buf;
  153. static DEFINE_MUTEX(bpf_verifier_lock);
  154. /* log_level controls verbosity level of eBPF verifier.
  155. * verbose() is used to dump the verification trace to the log, so the user
  156. * can figure out what's wrong with the program
  157. */
  158. static __printf(1, 2) void verbose(const char *fmt, ...)
  159. {
  160. va_list args;
  161. if (log_level == 0 || log_len >= log_size - 1)
  162. return;
  163. va_start(args, fmt);
  164. log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
  165. va_end(args);
  166. }
  167. /* string representation of 'enum bpf_reg_type' */
  168. static const char * const reg_type_str[] = {
  169. [NOT_INIT] = "?",
  170. [UNKNOWN_VALUE] = "inv",
  171. [PTR_TO_CTX] = "ctx",
  172. [CONST_PTR_TO_MAP] = "map_ptr",
  173. [PTR_TO_MAP_VALUE] = "map_value",
  174. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  175. [PTR_TO_MAP_VALUE_ADJ] = "map_value_adj",
  176. [FRAME_PTR] = "fp",
  177. [PTR_TO_STACK] = "fp",
  178. [CONST_IMM] = "imm",
  179. [PTR_TO_PACKET] = "pkt",
  180. [PTR_TO_PACKET_END] = "pkt_end",
  181. };
  182. static void print_verifier_state(struct bpf_verifier_state *state)
  183. {
  184. struct bpf_reg_state *reg;
  185. enum bpf_reg_type t;
  186. int i;
  187. for (i = 0; i < MAX_BPF_REG; i++) {
  188. reg = &state->regs[i];
  189. t = reg->type;
  190. if (t == NOT_INIT)
  191. continue;
  192. verbose(" R%d=%s", i, reg_type_str[t]);
  193. if (t == CONST_IMM || t == PTR_TO_STACK)
  194. verbose("%lld", reg->imm);
  195. else if (t == PTR_TO_PACKET)
  196. verbose("(id=%d,off=%d,r=%d)",
  197. reg->id, reg->off, reg->range);
  198. else if (t == UNKNOWN_VALUE && reg->imm)
  199. verbose("%lld", reg->imm);
  200. else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
  201. t == PTR_TO_MAP_VALUE_OR_NULL ||
  202. t == PTR_TO_MAP_VALUE_ADJ)
  203. verbose("(ks=%d,vs=%d,id=%u)",
  204. reg->map_ptr->key_size,
  205. reg->map_ptr->value_size,
  206. reg->id);
  207. if (reg->min_value != BPF_REGISTER_MIN_RANGE)
  208. verbose(",min_value=%lld",
  209. (long long)reg->min_value);
  210. if (reg->max_value != BPF_REGISTER_MAX_RANGE)
  211. verbose(",max_value=%llu",
  212. (unsigned long long)reg->max_value);
  213. }
  214. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  215. if (state->stack_slot_type[i] == STACK_SPILL)
  216. verbose(" fp%d=%s", -MAX_BPF_STACK + i,
  217. reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
  218. }
  219. verbose("\n");
  220. }
  221. static const char *const bpf_class_string[] = {
  222. [BPF_LD] = "ld",
  223. [BPF_LDX] = "ldx",
  224. [BPF_ST] = "st",
  225. [BPF_STX] = "stx",
  226. [BPF_ALU] = "alu",
  227. [BPF_JMP] = "jmp",
  228. [BPF_RET] = "BUG",
  229. [BPF_ALU64] = "alu64",
  230. };
  231. static const char *const bpf_alu_string[16] = {
  232. [BPF_ADD >> 4] = "+=",
  233. [BPF_SUB >> 4] = "-=",
  234. [BPF_MUL >> 4] = "*=",
  235. [BPF_DIV >> 4] = "/=",
  236. [BPF_OR >> 4] = "|=",
  237. [BPF_AND >> 4] = "&=",
  238. [BPF_LSH >> 4] = "<<=",
  239. [BPF_RSH >> 4] = ">>=",
  240. [BPF_NEG >> 4] = "neg",
  241. [BPF_MOD >> 4] = "%=",
  242. [BPF_XOR >> 4] = "^=",
  243. [BPF_MOV >> 4] = "=",
  244. [BPF_ARSH >> 4] = "s>>=",
  245. [BPF_END >> 4] = "endian",
  246. };
  247. static const char *const bpf_ldst_string[] = {
  248. [BPF_W >> 3] = "u32",
  249. [BPF_H >> 3] = "u16",
  250. [BPF_B >> 3] = "u8",
  251. [BPF_DW >> 3] = "u64",
  252. };
  253. static const char *const bpf_jmp_string[16] = {
  254. [BPF_JA >> 4] = "jmp",
  255. [BPF_JEQ >> 4] = "==",
  256. [BPF_JGT >> 4] = ">",
  257. [BPF_JGE >> 4] = ">=",
  258. [BPF_JSET >> 4] = "&",
  259. [BPF_JNE >> 4] = "!=",
  260. [BPF_JSGT >> 4] = "s>",
  261. [BPF_JSGE >> 4] = "s>=",
  262. [BPF_CALL >> 4] = "call",
  263. [BPF_EXIT >> 4] = "exit",
  264. };
  265. static void print_bpf_insn(const struct bpf_verifier_env *env,
  266. const struct bpf_insn *insn)
  267. {
  268. u8 class = BPF_CLASS(insn->code);
  269. if (class == BPF_ALU || class == BPF_ALU64) {
  270. if (BPF_SRC(insn->code) == BPF_X)
  271. verbose("(%02x) %sr%d %s %sr%d\n",
  272. insn->code, class == BPF_ALU ? "(u32) " : "",
  273. insn->dst_reg,
  274. bpf_alu_string[BPF_OP(insn->code) >> 4],
  275. class == BPF_ALU ? "(u32) " : "",
  276. insn->src_reg);
  277. else
  278. verbose("(%02x) %sr%d %s %s%d\n",
  279. insn->code, class == BPF_ALU ? "(u32) " : "",
  280. insn->dst_reg,
  281. bpf_alu_string[BPF_OP(insn->code) >> 4],
  282. class == BPF_ALU ? "(u32) " : "",
  283. insn->imm);
  284. } else if (class == BPF_STX) {
  285. if (BPF_MODE(insn->code) == BPF_MEM)
  286. verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
  287. insn->code,
  288. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  289. insn->dst_reg,
  290. insn->off, insn->src_reg);
  291. else if (BPF_MODE(insn->code) == BPF_XADD)
  292. verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
  293. insn->code,
  294. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  295. insn->dst_reg, insn->off,
  296. insn->src_reg);
  297. else
  298. verbose("BUG_%02x\n", insn->code);
  299. } else if (class == BPF_ST) {
  300. if (BPF_MODE(insn->code) != BPF_MEM) {
  301. verbose("BUG_st_%02x\n", insn->code);
  302. return;
  303. }
  304. verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
  305. insn->code,
  306. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  307. insn->dst_reg,
  308. insn->off, insn->imm);
  309. } else if (class == BPF_LDX) {
  310. if (BPF_MODE(insn->code) != BPF_MEM) {
  311. verbose("BUG_ldx_%02x\n", insn->code);
  312. return;
  313. }
  314. verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
  315. insn->code, insn->dst_reg,
  316. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  317. insn->src_reg, insn->off);
  318. } else if (class == BPF_LD) {
  319. if (BPF_MODE(insn->code) == BPF_ABS) {
  320. verbose("(%02x) r0 = *(%s *)skb[%d]\n",
  321. insn->code,
  322. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  323. insn->imm);
  324. } else if (BPF_MODE(insn->code) == BPF_IND) {
  325. verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
  326. insn->code,
  327. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  328. insn->src_reg, insn->imm);
  329. } else if (BPF_MODE(insn->code) == BPF_IMM &&
  330. BPF_SIZE(insn->code) == BPF_DW) {
  331. /* At this point, we already made sure that the second
  332. * part of the ldimm64 insn is accessible.
  333. */
  334. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  335. bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
  336. if (map_ptr && !env->allow_ptr_leaks)
  337. imm = 0;
  338. verbose("(%02x) r%d = 0x%llx\n", insn->code,
  339. insn->dst_reg, (unsigned long long)imm);
  340. } else {
  341. verbose("BUG_ld_%02x\n", insn->code);
  342. return;
  343. }
  344. } else if (class == BPF_JMP) {
  345. u8 opcode = BPF_OP(insn->code);
  346. if (opcode == BPF_CALL) {
  347. verbose("(%02x) call %d\n", insn->code, insn->imm);
  348. } else if (insn->code == (BPF_JMP | BPF_JA)) {
  349. verbose("(%02x) goto pc%+d\n",
  350. insn->code, insn->off);
  351. } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
  352. verbose("(%02x) exit\n", insn->code);
  353. } else if (BPF_SRC(insn->code) == BPF_X) {
  354. verbose("(%02x) if r%d %s r%d goto pc%+d\n",
  355. insn->code, insn->dst_reg,
  356. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  357. insn->src_reg, insn->off);
  358. } else {
  359. verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
  360. insn->code, insn->dst_reg,
  361. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  362. insn->imm, insn->off);
  363. }
  364. } else {
  365. verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
  366. }
  367. }
  368. static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
  369. {
  370. struct bpf_verifier_stack_elem *elem;
  371. int insn_idx;
  372. if (env->head == NULL)
  373. return -1;
  374. memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
  375. insn_idx = env->head->insn_idx;
  376. if (prev_insn_idx)
  377. *prev_insn_idx = env->head->prev_insn_idx;
  378. elem = env->head->next;
  379. kfree(env->head);
  380. env->head = elem;
  381. env->stack_size--;
  382. return insn_idx;
  383. }
  384. static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
  385. int insn_idx, int prev_insn_idx)
  386. {
  387. struct bpf_verifier_stack_elem *elem;
  388. elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
  389. if (!elem)
  390. goto err;
  391. memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
  392. elem->insn_idx = insn_idx;
  393. elem->prev_insn_idx = prev_insn_idx;
  394. elem->next = env->head;
  395. env->head = elem;
  396. env->stack_size++;
  397. if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
  398. verbose("BPF program is too complex\n");
  399. goto err;
  400. }
  401. return &elem->st;
  402. err:
  403. /* pop all elements and return */
  404. while (pop_stack(env, NULL) >= 0);
  405. return NULL;
  406. }
  407. #define CALLER_SAVED_REGS 6
  408. static const int caller_saved[CALLER_SAVED_REGS] = {
  409. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  410. };
  411. static void init_reg_state(struct bpf_reg_state *regs)
  412. {
  413. int i;
  414. for (i = 0; i < MAX_BPF_REG; i++) {
  415. regs[i].type = NOT_INIT;
  416. regs[i].imm = 0;
  417. regs[i].min_value = BPF_REGISTER_MIN_RANGE;
  418. regs[i].max_value = BPF_REGISTER_MAX_RANGE;
  419. }
  420. /* frame pointer */
  421. regs[BPF_REG_FP].type = FRAME_PTR;
  422. /* 1st arg to a function */
  423. regs[BPF_REG_1].type = PTR_TO_CTX;
  424. }
  425. static void __mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
  426. {
  427. regs[regno].type = UNKNOWN_VALUE;
  428. regs[regno].id = 0;
  429. regs[regno].imm = 0;
  430. }
  431. static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
  432. {
  433. BUG_ON(regno >= MAX_BPF_REG);
  434. __mark_reg_unknown_value(regs, regno);
  435. }
  436. static void reset_reg_range_values(struct bpf_reg_state *regs, u32 regno)
  437. {
  438. regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
  439. regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
  440. }
  441. enum reg_arg_type {
  442. SRC_OP, /* register is used as source operand */
  443. DST_OP, /* register is used as destination operand */
  444. DST_OP_NO_MARK /* same as above, check only, don't mark */
  445. };
  446. static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
  447. enum reg_arg_type t)
  448. {
  449. if (regno >= MAX_BPF_REG) {
  450. verbose("R%d is invalid\n", regno);
  451. return -EINVAL;
  452. }
  453. if (t == SRC_OP) {
  454. /* check whether register used as source operand can be read */
  455. if (regs[regno].type == NOT_INIT) {
  456. verbose("R%d !read_ok\n", regno);
  457. return -EACCES;
  458. }
  459. } else {
  460. /* check whether register used as dest operand can be written to */
  461. if (regno == BPF_REG_FP) {
  462. verbose("frame pointer is read only\n");
  463. return -EACCES;
  464. }
  465. if (t == DST_OP)
  466. mark_reg_unknown_value(regs, regno);
  467. }
  468. return 0;
  469. }
  470. static int bpf_size_to_bytes(int bpf_size)
  471. {
  472. if (bpf_size == BPF_W)
  473. return 4;
  474. else if (bpf_size == BPF_H)
  475. return 2;
  476. else if (bpf_size == BPF_B)
  477. return 1;
  478. else if (bpf_size == BPF_DW)
  479. return 8;
  480. else
  481. return -EINVAL;
  482. }
  483. static bool is_spillable_regtype(enum bpf_reg_type type)
  484. {
  485. switch (type) {
  486. case PTR_TO_MAP_VALUE:
  487. case PTR_TO_MAP_VALUE_OR_NULL:
  488. case PTR_TO_STACK:
  489. case PTR_TO_CTX:
  490. case PTR_TO_PACKET:
  491. case PTR_TO_PACKET_END:
  492. case FRAME_PTR:
  493. case CONST_PTR_TO_MAP:
  494. return true;
  495. default:
  496. return false;
  497. }
  498. }
  499. /* check_stack_read/write functions track spill/fill of registers,
  500. * stack boundary and alignment are checked in check_mem_access()
  501. */
  502. static int check_stack_write(struct bpf_verifier_env *env,
  503. struct bpf_verifier_state *state, int off,
  504. int size, int value_regno, int insn_idx)
  505. {
  506. int i, spi = (MAX_BPF_STACK + off) / BPF_REG_SIZE;
  507. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  508. * so it's aligned access and [off, off + size) are within stack limits
  509. */
  510. if (value_regno >= 0 &&
  511. is_spillable_regtype(state->regs[value_regno].type)) {
  512. /* register containing pointer is being spilled into stack */
  513. if (size != BPF_REG_SIZE) {
  514. verbose("invalid size of register spill\n");
  515. return -EACCES;
  516. }
  517. /* save register state */
  518. state->spilled_regs[spi] = state->regs[value_regno];
  519. for (i = 0; i < BPF_REG_SIZE; i++) {
  520. if (state->stack_slot_type[MAX_BPF_STACK + off + i] == STACK_MISC &&
  521. !env->allow_ptr_leaks) {
  522. int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
  523. int soff = (-spi - 1) * BPF_REG_SIZE;
  524. /* detected reuse of integer stack slot with a pointer
  525. * which means either llvm is reusing stack slot or
  526. * an attacker is trying to exploit CVE-2018-3639
  527. * (speculative store bypass)
  528. * Have to sanitize that slot with preemptive
  529. * store of zero.
  530. */
  531. if (*poff && *poff != soff) {
  532. /* disallow programs where single insn stores
  533. * into two different stack slots, since verifier
  534. * cannot sanitize them
  535. */
  536. verbose("insn %d cannot access two stack slots fp%d and fp%d",
  537. insn_idx, *poff, soff);
  538. return -EINVAL;
  539. }
  540. *poff = soff;
  541. }
  542. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
  543. }
  544. } else {
  545. /* regular write of data into stack */
  546. state->spilled_regs[spi] = (struct bpf_reg_state) {};
  547. for (i = 0; i < size; i++)
  548. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
  549. }
  550. return 0;
  551. }
  552. static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
  553. int value_regno)
  554. {
  555. u8 *slot_type;
  556. int i;
  557. slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
  558. if (slot_type[0] == STACK_SPILL) {
  559. if (size != BPF_REG_SIZE) {
  560. verbose("invalid size of register spill\n");
  561. return -EACCES;
  562. }
  563. for (i = 1; i < BPF_REG_SIZE; i++) {
  564. if (slot_type[i] != STACK_SPILL) {
  565. verbose("corrupted spill memory\n");
  566. return -EACCES;
  567. }
  568. }
  569. if (value_regno >= 0)
  570. /* restore register state from stack */
  571. state->regs[value_regno] =
  572. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
  573. return 0;
  574. } else {
  575. for (i = 0; i < size; i++) {
  576. if (slot_type[i] != STACK_MISC) {
  577. verbose("invalid read from stack off %d+%d size %d\n",
  578. off, i, size);
  579. return -EACCES;
  580. }
  581. }
  582. if (value_regno >= 0)
  583. /* have read misc data from the stack */
  584. mark_reg_unknown_value(state->regs, value_regno);
  585. return 0;
  586. }
  587. }
  588. /* check read/write into map element returned by bpf_map_lookup_elem() */
  589. static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
  590. int size)
  591. {
  592. struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
  593. if (off < 0 || off + size > map->value_size) {
  594. verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
  595. map->value_size, off, size);
  596. return -EACCES;
  597. }
  598. return 0;
  599. }
  600. #define MAX_PACKET_OFF 0xffff
  601. static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
  602. const struct bpf_call_arg_meta *meta)
  603. {
  604. switch (env->prog->type) {
  605. case BPF_PROG_TYPE_SCHED_CLS:
  606. case BPF_PROG_TYPE_SCHED_ACT:
  607. case BPF_PROG_TYPE_XDP:
  608. if (meta)
  609. return meta->pkt_access;
  610. env->seen_direct_write = true;
  611. return true;
  612. default:
  613. return false;
  614. }
  615. }
  616. static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
  617. int size)
  618. {
  619. struct bpf_reg_state *regs = env->cur_state.regs;
  620. struct bpf_reg_state *reg = &regs[regno];
  621. off += reg->off;
  622. if (off < 0 || size <= 0 || off + size > reg->range) {
  623. verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
  624. off, size, regno, reg->id, reg->off, reg->range);
  625. return -EACCES;
  626. }
  627. return 0;
  628. }
  629. /* check access to 'struct bpf_context' fields */
  630. static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
  631. enum bpf_access_type t, enum bpf_reg_type *reg_type)
  632. {
  633. /* for analyzer ctx accesses are already validated and converted */
  634. if (env->analyzer_ops)
  635. return 0;
  636. if (env->prog->aux->ops->is_valid_access &&
  637. env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
  638. /* remember the offset of last byte accessed in ctx */
  639. if (env->prog->aux->max_ctx_offset < off + size)
  640. env->prog->aux->max_ctx_offset = off + size;
  641. return 0;
  642. }
  643. verbose("invalid bpf_context access off=%d size=%d\n", off, size);
  644. return -EACCES;
  645. }
  646. static bool __is_pointer_value(bool allow_ptr_leaks,
  647. const struct bpf_reg_state *reg)
  648. {
  649. if (allow_ptr_leaks)
  650. return false;
  651. switch (reg->type) {
  652. case UNKNOWN_VALUE:
  653. case CONST_IMM:
  654. return false;
  655. default:
  656. return true;
  657. }
  658. }
  659. static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
  660. {
  661. return __is_pointer_value(env->allow_ptr_leaks, &env->cur_state.regs[regno]);
  662. }
  663. static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
  664. {
  665. const struct bpf_reg_state *reg = &env->cur_state.regs[regno];
  666. return reg->type == PTR_TO_CTX;
  667. }
  668. static int check_ptr_alignment(struct bpf_verifier_env *env,
  669. struct bpf_reg_state *reg, int off, int size)
  670. {
  671. if (reg->type != PTR_TO_PACKET && reg->type != PTR_TO_MAP_VALUE_ADJ) {
  672. if (off % size != 0) {
  673. verbose("misaligned access off %d size %d\n",
  674. off, size);
  675. return -EACCES;
  676. } else {
  677. return 0;
  678. }
  679. }
  680. if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
  681. /* misaligned access to packet is ok on x86,arm,arm64 */
  682. return 0;
  683. if (reg->id && size != 1) {
  684. verbose("Unknown packet alignment. Only byte-sized access allowed\n");
  685. return -EACCES;
  686. }
  687. /* skb->data is NET_IP_ALIGN-ed */
  688. if (reg->type == PTR_TO_PACKET &&
  689. (NET_IP_ALIGN + reg->off + off) % size != 0) {
  690. verbose("misaligned packet access off %d+%d+%d size %d\n",
  691. NET_IP_ALIGN, reg->off, off, size);
  692. return -EACCES;
  693. }
  694. return 0;
  695. }
  696. /* check whether memory at (regno + off) is accessible for t = (read | write)
  697. * if t==write, value_regno is a register which value is stored into memory
  698. * if t==read, value_regno is a register which will receive the value from memory
  699. * if t==write && value_regno==-1, some unknown value is stored into memory
  700. * if t==read && value_regno==-1, don't care what we read from memory
  701. */
  702. static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
  703. int bpf_size, enum bpf_access_type t,
  704. int value_regno)
  705. {
  706. struct bpf_verifier_state *state = &env->cur_state;
  707. struct bpf_reg_state *reg = &state->regs[regno];
  708. int size, err = 0;
  709. if (reg->type == PTR_TO_STACK)
  710. off += reg->imm;
  711. size = bpf_size_to_bytes(bpf_size);
  712. if (size < 0)
  713. return size;
  714. err = check_ptr_alignment(env, reg, off, size);
  715. if (err)
  716. return err;
  717. if (reg->type == PTR_TO_MAP_VALUE ||
  718. reg->type == PTR_TO_MAP_VALUE_ADJ) {
  719. if (t == BPF_WRITE && value_regno >= 0 &&
  720. is_pointer_value(env, value_regno)) {
  721. verbose("R%d leaks addr into map\n", value_regno);
  722. return -EACCES;
  723. }
  724. /* If we adjusted the register to this map value at all then we
  725. * need to change off and size to min_value and max_value
  726. * respectively to make sure our theoretical access will be
  727. * safe.
  728. */
  729. if (reg->type == PTR_TO_MAP_VALUE_ADJ) {
  730. if (log_level)
  731. print_verifier_state(state);
  732. env->varlen_map_value_access = true;
  733. /* The minimum value is only important with signed
  734. * comparisons where we can't assume the floor of a
  735. * value is 0. If we are using signed variables for our
  736. * index'es we need to make sure that whatever we use
  737. * will have a set floor within our range.
  738. */
  739. if (reg->min_value < 0) {
  740. verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  741. regno);
  742. return -EACCES;
  743. }
  744. err = check_map_access(env, regno, reg->min_value + off,
  745. size);
  746. if (err) {
  747. verbose("R%d min value is outside of the array range\n",
  748. regno);
  749. return err;
  750. }
  751. /* If we haven't set a max value then we need to bail
  752. * since we can't be sure we won't do bad things.
  753. */
  754. if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
  755. verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
  756. regno);
  757. return -EACCES;
  758. }
  759. off += reg->max_value;
  760. }
  761. err = check_map_access(env, regno, off, size);
  762. if (!err && t == BPF_READ && value_regno >= 0)
  763. mark_reg_unknown_value(state->regs, value_regno);
  764. } else if (reg->type == PTR_TO_CTX) {
  765. enum bpf_reg_type reg_type = UNKNOWN_VALUE;
  766. if (t == BPF_WRITE && value_regno >= 0 &&
  767. is_pointer_value(env, value_regno)) {
  768. verbose("R%d leaks addr into ctx\n", value_regno);
  769. return -EACCES;
  770. }
  771. err = check_ctx_access(env, off, size, t, &reg_type);
  772. if (!err && t == BPF_READ && value_regno >= 0) {
  773. mark_reg_unknown_value(state->regs, value_regno);
  774. /* note that reg.[id|off|range] == 0 */
  775. state->regs[value_regno].type = reg_type;
  776. }
  777. } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
  778. if (off >= 0 || off < -MAX_BPF_STACK) {
  779. verbose("invalid stack off=%d size=%d\n", off, size);
  780. return -EACCES;
  781. }
  782. if (t == BPF_WRITE) {
  783. if (!env->allow_ptr_leaks &&
  784. state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
  785. size != BPF_REG_SIZE) {
  786. verbose("attempt to corrupt spilled pointer on stack\n");
  787. return -EACCES;
  788. }
  789. err = check_stack_write(env, state, off, size,
  790. value_regno, insn_idx);
  791. } else {
  792. err = check_stack_read(state, off, size, value_regno);
  793. }
  794. } else if (state->regs[regno].type == PTR_TO_PACKET) {
  795. if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL)) {
  796. verbose("cannot write into packet\n");
  797. return -EACCES;
  798. }
  799. if (t == BPF_WRITE && value_regno >= 0 &&
  800. is_pointer_value(env, value_regno)) {
  801. verbose("R%d leaks addr into packet\n", value_regno);
  802. return -EACCES;
  803. }
  804. err = check_packet_access(env, regno, off, size);
  805. if (!err && t == BPF_READ && value_regno >= 0)
  806. mark_reg_unknown_value(state->regs, value_regno);
  807. } else {
  808. verbose("R%d invalid mem access '%s'\n",
  809. regno, reg_type_str[reg->type]);
  810. return -EACCES;
  811. }
  812. if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
  813. state->regs[value_regno].type == UNKNOWN_VALUE) {
  814. /* 1 or 2 byte load zero-extends, determine the number of
  815. * zero upper bits. Not doing it fo 4 byte load, since
  816. * such values cannot be added to ptr_to_packet anyway.
  817. */
  818. state->regs[value_regno].imm = 64 - size * 8;
  819. }
  820. return err;
  821. }
  822. static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
  823. {
  824. struct bpf_reg_state *regs = env->cur_state.regs;
  825. int err;
  826. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  827. insn->imm != 0) {
  828. verbose("BPF_XADD uses reserved fields\n");
  829. return -EINVAL;
  830. }
  831. /* check src1 operand */
  832. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  833. if (err)
  834. return err;
  835. /* check src2 operand */
  836. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  837. if (err)
  838. return err;
  839. if (is_pointer_value(env, insn->src_reg)) {
  840. verbose("R%d leaks addr into mem\n", insn->src_reg);
  841. return -EACCES;
  842. }
  843. if (is_ctx_reg(env, insn->dst_reg)) {
  844. verbose("BPF_XADD stores into R%d context is not allowed\n",
  845. insn->dst_reg);
  846. return -EACCES;
  847. }
  848. /* check whether atomic_add can read the memory */
  849. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  850. BPF_SIZE(insn->code), BPF_READ, -1);
  851. if (err)
  852. return err;
  853. /* check whether atomic_add can write into the same memory */
  854. return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  855. BPF_SIZE(insn->code), BPF_WRITE, -1);
  856. }
  857. /* when register 'regno' is passed into function that will read 'access_size'
  858. * bytes from that pointer, make sure that it's within stack boundary
  859. * and all elements of stack are initialized
  860. */
  861. static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
  862. int access_size, bool zero_size_allowed,
  863. struct bpf_call_arg_meta *meta)
  864. {
  865. struct bpf_verifier_state *state = &env->cur_state;
  866. struct bpf_reg_state *regs = state->regs;
  867. int off, i;
  868. if (regs[regno].type != PTR_TO_STACK) {
  869. if (zero_size_allowed && access_size == 0 &&
  870. regs[regno].type == CONST_IMM &&
  871. regs[regno].imm == 0)
  872. return 0;
  873. verbose("R%d type=%s expected=%s\n", regno,
  874. reg_type_str[regs[regno].type],
  875. reg_type_str[PTR_TO_STACK]);
  876. return -EACCES;
  877. }
  878. off = regs[regno].imm;
  879. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  880. access_size <= 0) {
  881. verbose("invalid stack type R%d off=%d access_size=%d\n",
  882. regno, off, access_size);
  883. return -EACCES;
  884. }
  885. if (meta && meta->raw_mode) {
  886. meta->access_size = access_size;
  887. meta->regno = regno;
  888. return 0;
  889. }
  890. for (i = 0; i < access_size; i++) {
  891. if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
  892. verbose("invalid indirect read from stack off %d+%d size %d\n",
  893. off, i, access_size);
  894. return -EACCES;
  895. }
  896. }
  897. return 0;
  898. }
  899. static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
  900. enum bpf_arg_type arg_type,
  901. struct bpf_call_arg_meta *meta)
  902. {
  903. struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
  904. enum bpf_reg_type expected_type, type = reg->type;
  905. int err = 0;
  906. if (arg_type == ARG_DONTCARE)
  907. return 0;
  908. if (type == NOT_INIT) {
  909. verbose("R%d !read_ok\n", regno);
  910. return -EACCES;
  911. }
  912. if (arg_type == ARG_ANYTHING) {
  913. if (is_pointer_value(env, regno)) {
  914. verbose("R%d leaks addr into helper function\n", regno);
  915. return -EACCES;
  916. }
  917. return 0;
  918. }
  919. if (type == PTR_TO_PACKET && !may_access_direct_pkt_data(env, meta)) {
  920. verbose("helper access to the packet is not allowed\n");
  921. return -EACCES;
  922. }
  923. if (arg_type == ARG_PTR_TO_MAP_KEY ||
  924. arg_type == ARG_PTR_TO_MAP_VALUE) {
  925. expected_type = PTR_TO_STACK;
  926. if (type != PTR_TO_PACKET && type != expected_type)
  927. goto err_type;
  928. } else if (arg_type == ARG_CONST_STACK_SIZE ||
  929. arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
  930. expected_type = CONST_IMM;
  931. if (type != expected_type)
  932. goto err_type;
  933. } else if (arg_type == ARG_CONST_MAP_PTR) {
  934. expected_type = CONST_PTR_TO_MAP;
  935. if (type != expected_type)
  936. goto err_type;
  937. } else if (arg_type == ARG_PTR_TO_CTX) {
  938. expected_type = PTR_TO_CTX;
  939. if (type != expected_type)
  940. goto err_type;
  941. } else if (arg_type == ARG_PTR_TO_STACK ||
  942. arg_type == ARG_PTR_TO_RAW_STACK) {
  943. expected_type = PTR_TO_STACK;
  944. /* One exception here. In case function allows for NULL to be
  945. * passed in as argument, it's a CONST_IMM type. Final test
  946. * happens during stack boundary checking.
  947. */
  948. if (type == CONST_IMM && reg->imm == 0)
  949. /* final test in check_stack_boundary() */;
  950. else if (type != PTR_TO_PACKET && type != expected_type)
  951. goto err_type;
  952. meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
  953. } else {
  954. verbose("unsupported arg_type %d\n", arg_type);
  955. return -EFAULT;
  956. }
  957. if (arg_type == ARG_CONST_MAP_PTR) {
  958. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  959. meta->map_ptr = reg->map_ptr;
  960. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  961. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  962. * check that [key, key + map->key_size) are within
  963. * stack limits and initialized
  964. */
  965. if (!meta->map_ptr) {
  966. /* in function declaration map_ptr must come before
  967. * map_key, so that it's verified and known before
  968. * we have to check map_key here. Otherwise it means
  969. * that kernel subsystem misconfigured verifier
  970. */
  971. verbose("invalid map_ptr to access map->key\n");
  972. return -EACCES;
  973. }
  974. if (type == PTR_TO_PACKET)
  975. err = check_packet_access(env, regno, 0,
  976. meta->map_ptr->key_size);
  977. else
  978. err = check_stack_boundary(env, regno,
  979. meta->map_ptr->key_size,
  980. false, NULL);
  981. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  982. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  983. * check [value, value + map->value_size) validity
  984. */
  985. if (!meta->map_ptr) {
  986. /* kernel subsystem misconfigured verifier */
  987. verbose("invalid map_ptr to access map->value\n");
  988. return -EACCES;
  989. }
  990. if (type == PTR_TO_PACKET)
  991. err = check_packet_access(env, regno, 0,
  992. meta->map_ptr->value_size);
  993. else
  994. err = check_stack_boundary(env, regno,
  995. meta->map_ptr->value_size,
  996. false, NULL);
  997. } else if (arg_type == ARG_CONST_STACK_SIZE ||
  998. arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
  999. bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
  1000. /* bpf_xxx(..., buf, len) call will access 'len' bytes
  1001. * from stack pointer 'buf'. Check it
  1002. * note: regno == len, regno - 1 == buf
  1003. */
  1004. if (regno == 0) {
  1005. /* kernel subsystem misconfigured verifier */
  1006. verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
  1007. return -EACCES;
  1008. }
  1009. if (regs[regno - 1].type == PTR_TO_PACKET)
  1010. err = check_packet_access(env, regno - 1, 0, reg->imm);
  1011. else
  1012. err = check_stack_boundary(env, regno - 1, reg->imm,
  1013. zero_size_allowed, meta);
  1014. }
  1015. return err;
  1016. err_type:
  1017. verbose("R%d type=%s expected=%s\n", regno,
  1018. reg_type_str[type], reg_type_str[expected_type]);
  1019. return -EACCES;
  1020. }
  1021. static int check_map_func_compatibility(struct bpf_map *map, int func_id)
  1022. {
  1023. if (!map)
  1024. return 0;
  1025. /* We need a two way check, first is from map perspective ... */
  1026. switch (map->map_type) {
  1027. case BPF_MAP_TYPE_PROG_ARRAY:
  1028. if (func_id != BPF_FUNC_tail_call)
  1029. goto error;
  1030. break;
  1031. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  1032. if (func_id != BPF_FUNC_perf_event_read &&
  1033. func_id != BPF_FUNC_perf_event_output)
  1034. goto error;
  1035. break;
  1036. case BPF_MAP_TYPE_STACK_TRACE:
  1037. if (func_id != BPF_FUNC_get_stackid)
  1038. goto error;
  1039. break;
  1040. case BPF_MAP_TYPE_CGROUP_ARRAY:
  1041. if (func_id != BPF_FUNC_skb_under_cgroup &&
  1042. func_id != BPF_FUNC_current_task_under_cgroup)
  1043. goto error;
  1044. break;
  1045. default:
  1046. break;
  1047. }
  1048. /* ... and second from the function itself. */
  1049. switch (func_id) {
  1050. case BPF_FUNC_tail_call:
  1051. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  1052. goto error;
  1053. break;
  1054. case BPF_FUNC_perf_event_read:
  1055. case BPF_FUNC_perf_event_output:
  1056. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  1057. goto error;
  1058. break;
  1059. case BPF_FUNC_get_stackid:
  1060. if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
  1061. goto error;
  1062. break;
  1063. case BPF_FUNC_current_task_under_cgroup:
  1064. case BPF_FUNC_skb_under_cgroup:
  1065. if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
  1066. goto error;
  1067. break;
  1068. default:
  1069. break;
  1070. }
  1071. return 0;
  1072. error:
  1073. verbose("cannot pass map_type %d into func %d\n",
  1074. map->map_type, func_id);
  1075. return -EINVAL;
  1076. }
  1077. static int check_raw_mode(const struct bpf_func_proto *fn)
  1078. {
  1079. int count = 0;
  1080. if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
  1081. count++;
  1082. if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
  1083. count++;
  1084. if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
  1085. count++;
  1086. if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
  1087. count++;
  1088. if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
  1089. count++;
  1090. return count > 1 ? -EINVAL : 0;
  1091. }
  1092. static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
  1093. {
  1094. struct bpf_verifier_state *state = &env->cur_state;
  1095. struct bpf_reg_state *regs = state->regs, *reg;
  1096. int i;
  1097. for (i = 0; i < MAX_BPF_REG; i++)
  1098. if (regs[i].type == PTR_TO_PACKET ||
  1099. regs[i].type == PTR_TO_PACKET_END)
  1100. mark_reg_unknown_value(regs, i);
  1101. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  1102. if (state->stack_slot_type[i] != STACK_SPILL)
  1103. continue;
  1104. reg = &state->spilled_regs[i / BPF_REG_SIZE];
  1105. if (reg->type != PTR_TO_PACKET &&
  1106. reg->type != PTR_TO_PACKET_END)
  1107. continue;
  1108. reg->type = UNKNOWN_VALUE;
  1109. reg->imm = 0;
  1110. }
  1111. }
  1112. static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
  1113. {
  1114. struct bpf_verifier_state *state = &env->cur_state;
  1115. const struct bpf_func_proto *fn = NULL;
  1116. struct bpf_reg_state *regs = state->regs;
  1117. struct bpf_reg_state *reg;
  1118. struct bpf_call_arg_meta meta;
  1119. bool changes_data;
  1120. int i, err;
  1121. /* find function prototype */
  1122. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  1123. verbose("invalid func %d\n", func_id);
  1124. return -EINVAL;
  1125. }
  1126. if (env->prog->aux->ops->get_func_proto)
  1127. fn = env->prog->aux->ops->get_func_proto(func_id);
  1128. if (!fn) {
  1129. verbose("unknown func %d\n", func_id);
  1130. return -EINVAL;
  1131. }
  1132. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  1133. if (!env->prog->gpl_compatible && fn->gpl_only) {
  1134. verbose("cannot call GPL only function from proprietary program\n");
  1135. return -EINVAL;
  1136. }
  1137. changes_data = bpf_helper_changes_skb_data(fn->func);
  1138. memset(&meta, 0, sizeof(meta));
  1139. meta.pkt_access = fn->pkt_access;
  1140. /* We only support one arg being in raw mode at the moment, which
  1141. * is sufficient for the helper functions we have right now.
  1142. */
  1143. err = check_raw_mode(fn);
  1144. if (err) {
  1145. verbose("kernel subsystem misconfigured func %d\n", func_id);
  1146. return err;
  1147. }
  1148. /* check args */
  1149. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
  1150. if (err)
  1151. return err;
  1152. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
  1153. if (err)
  1154. return err;
  1155. if (func_id == BPF_FUNC_tail_call) {
  1156. if (meta.map_ptr == NULL) {
  1157. verbose("verifier bug\n");
  1158. return -EINVAL;
  1159. }
  1160. env->insn_aux_data[insn_idx].map_ptr = meta.map_ptr;
  1161. }
  1162. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
  1163. if (err)
  1164. return err;
  1165. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
  1166. if (err)
  1167. return err;
  1168. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
  1169. if (err)
  1170. return err;
  1171. /* Mark slots with STACK_MISC in case of raw mode, stack offset
  1172. * is inferred from register state.
  1173. */
  1174. for (i = 0; i < meta.access_size; i++) {
  1175. err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
  1176. if (err)
  1177. return err;
  1178. }
  1179. /* reset caller saved regs */
  1180. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  1181. reg = regs + caller_saved[i];
  1182. reg->type = NOT_INIT;
  1183. reg->imm = 0;
  1184. }
  1185. /* update return register */
  1186. if (fn->ret_type == RET_INTEGER) {
  1187. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  1188. } else if (fn->ret_type == RET_VOID) {
  1189. regs[BPF_REG_0].type = NOT_INIT;
  1190. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  1191. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  1192. regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0;
  1193. /* remember map_ptr, so that check_map_access()
  1194. * can check 'value_size' boundary of memory access
  1195. * to map element returned from bpf_map_lookup_elem()
  1196. */
  1197. if (meta.map_ptr == NULL) {
  1198. verbose("kernel subsystem misconfigured verifier\n");
  1199. return -EINVAL;
  1200. }
  1201. regs[BPF_REG_0].map_ptr = meta.map_ptr;
  1202. regs[BPF_REG_0].id = ++env->id_gen;
  1203. } else {
  1204. verbose("unknown return type %d of func %d\n",
  1205. fn->ret_type, func_id);
  1206. return -EINVAL;
  1207. }
  1208. err = check_map_func_compatibility(meta.map_ptr, func_id);
  1209. if (err)
  1210. return err;
  1211. if (changes_data)
  1212. clear_all_pkt_pointers(env);
  1213. return 0;
  1214. }
  1215. static int check_packet_ptr_add(struct bpf_verifier_env *env,
  1216. struct bpf_insn *insn)
  1217. {
  1218. struct bpf_reg_state *regs = env->cur_state.regs;
  1219. struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
  1220. struct bpf_reg_state *src_reg = &regs[insn->src_reg];
  1221. struct bpf_reg_state tmp_reg;
  1222. s32 imm;
  1223. if (BPF_SRC(insn->code) == BPF_K) {
  1224. /* pkt_ptr += imm */
  1225. imm = insn->imm;
  1226. add_imm:
  1227. if (imm <= 0) {
  1228. verbose("addition of negative constant to packet pointer is not allowed\n");
  1229. return -EACCES;
  1230. }
  1231. if (imm >= MAX_PACKET_OFF ||
  1232. imm + dst_reg->off >= MAX_PACKET_OFF) {
  1233. verbose("constant %d is too large to add to packet pointer\n",
  1234. imm);
  1235. return -EACCES;
  1236. }
  1237. /* a constant was added to pkt_ptr.
  1238. * Remember it while keeping the same 'id'
  1239. */
  1240. dst_reg->off += imm;
  1241. } else {
  1242. if (src_reg->type == PTR_TO_PACKET) {
  1243. /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
  1244. tmp_reg = *dst_reg; /* save r7 state */
  1245. *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
  1246. src_reg = &tmp_reg; /* pretend it's src_reg state */
  1247. /* if the checks below reject it, the copy won't matter,
  1248. * since we're rejecting the whole program. If all ok,
  1249. * then imm22 state will be added to r7
  1250. * and r7 will be pkt(id=0,off=22,r=62) while
  1251. * r6 will stay as pkt(id=0,off=0,r=62)
  1252. */
  1253. }
  1254. if (src_reg->type == CONST_IMM) {
  1255. /* pkt_ptr += reg where reg is known constant */
  1256. imm = src_reg->imm;
  1257. goto add_imm;
  1258. }
  1259. /* disallow pkt_ptr += reg
  1260. * if reg is not uknown_value with guaranteed zero upper bits
  1261. * otherwise pkt_ptr may overflow and addition will become
  1262. * subtraction which is not allowed
  1263. */
  1264. if (src_reg->type != UNKNOWN_VALUE) {
  1265. verbose("cannot add '%s' to ptr_to_packet\n",
  1266. reg_type_str[src_reg->type]);
  1267. return -EACCES;
  1268. }
  1269. if (src_reg->imm < 48) {
  1270. verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
  1271. src_reg->imm);
  1272. return -EACCES;
  1273. }
  1274. /* dst_reg stays as pkt_ptr type and since some positive
  1275. * integer value was added to the pointer, increment its 'id'
  1276. */
  1277. dst_reg->id = ++env->id_gen;
  1278. /* something was added to pkt_ptr, set range and off to zero */
  1279. dst_reg->off = 0;
  1280. dst_reg->range = 0;
  1281. }
  1282. return 0;
  1283. }
  1284. static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
  1285. {
  1286. struct bpf_reg_state *regs = env->cur_state.regs;
  1287. struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
  1288. u8 opcode = BPF_OP(insn->code);
  1289. s64 imm_log2;
  1290. /* for type == UNKNOWN_VALUE:
  1291. * imm > 0 -> number of zero upper bits
  1292. * imm == 0 -> don't track which is the same as all bits can be non-zero
  1293. */
  1294. if (BPF_SRC(insn->code) == BPF_X) {
  1295. struct bpf_reg_state *src_reg = &regs[insn->src_reg];
  1296. if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
  1297. dst_reg->imm && opcode == BPF_ADD) {
  1298. /* dreg += sreg
  1299. * where both have zero upper bits. Adding them
  1300. * can only result making one more bit non-zero
  1301. * in the larger value.
  1302. * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
  1303. * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
  1304. */
  1305. dst_reg->imm = min(dst_reg->imm, src_reg->imm);
  1306. dst_reg->imm--;
  1307. return 0;
  1308. }
  1309. if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
  1310. dst_reg->imm && opcode == BPF_ADD) {
  1311. /* dreg += sreg
  1312. * where dreg has zero upper bits and sreg is const.
  1313. * Adding them can only result making one more bit
  1314. * non-zero in the larger value.
  1315. */
  1316. imm_log2 = __ilog2_u64((long long)src_reg->imm);
  1317. dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
  1318. dst_reg->imm--;
  1319. return 0;
  1320. }
  1321. /* all other cases non supported yet, just mark dst_reg */
  1322. dst_reg->imm = 0;
  1323. return 0;
  1324. }
  1325. /* sign extend 32-bit imm into 64-bit to make sure that
  1326. * negative values occupy bit 63. Note ilog2() would have
  1327. * been incorrect, since sizeof(insn->imm) == 4
  1328. */
  1329. imm_log2 = __ilog2_u64((long long)insn->imm);
  1330. if (dst_reg->imm && opcode == BPF_LSH) {
  1331. /* reg <<= imm
  1332. * if reg was a result of 2 byte load, then its imm == 48
  1333. * which means that upper 48 bits are zero and shifting this reg
  1334. * left by 4 would mean that upper 44 bits are still zero
  1335. */
  1336. dst_reg->imm -= insn->imm;
  1337. } else if (dst_reg->imm && opcode == BPF_MUL) {
  1338. /* reg *= imm
  1339. * if multiplying by 14 subtract 4
  1340. * This is conservative calculation of upper zero bits.
  1341. * It's not trying to special case insn->imm == 1 or 0 cases
  1342. */
  1343. dst_reg->imm -= imm_log2 + 1;
  1344. } else if (opcode == BPF_AND) {
  1345. /* reg &= imm */
  1346. dst_reg->imm = 63 - imm_log2;
  1347. } else if (dst_reg->imm && opcode == BPF_ADD) {
  1348. /* reg += imm */
  1349. dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
  1350. dst_reg->imm--;
  1351. } else if (opcode == BPF_RSH) {
  1352. /* reg >>= imm
  1353. * which means that after right shift, upper bits will be zero
  1354. * note that verifier already checked that
  1355. * 0 <= imm < 64 for shift insn
  1356. */
  1357. dst_reg->imm += insn->imm;
  1358. if (unlikely(dst_reg->imm > 64))
  1359. /* some dumb code did:
  1360. * r2 = *(u32 *)mem;
  1361. * r2 >>= 32;
  1362. * and all bits are zero now */
  1363. dst_reg->imm = 64;
  1364. } else {
  1365. /* all other alu ops, means that we don't know what will
  1366. * happen to the value, mark it with unknown number of zero bits
  1367. */
  1368. dst_reg->imm = 0;
  1369. }
  1370. if (dst_reg->imm < 0) {
  1371. /* all 64 bits of the register can contain non-zero bits
  1372. * and such value cannot be added to ptr_to_packet, since it
  1373. * may overflow, mark it as unknown to avoid further eval
  1374. */
  1375. dst_reg->imm = 0;
  1376. }
  1377. return 0;
  1378. }
  1379. static int evaluate_reg_imm_alu_unknown(struct bpf_verifier_env *env,
  1380. struct bpf_insn *insn)
  1381. {
  1382. struct bpf_reg_state *regs = env->cur_state.regs;
  1383. struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
  1384. struct bpf_reg_state *src_reg = &regs[insn->src_reg];
  1385. u8 opcode = BPF_OP(insn->code);
  1386. s64 imm_log2 = __ilog2_u64((long long)dst_reg->imm);
  1387. /* BPF_X code with src_reg->type UNKNOWN_VALUE here. */
  1388. if (src_reg->imm > 0 && dst_reg->imm) {
  1389. switch (opcode) {
  1390. case BPF_ADD:
  1391. /* dreg += sreg
  1392. * where both have zero upper bits. Adding them
  1393. * can only result making one more bit non-zero
  1394. * in the larger value.
  1395. * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
  1396. * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
  1397. */
  1398. dst_reg->imm = min(src_reg->imm, 63 - imm_log2);
  1399. dst_reg->imm--;
  1400. break;
  1401. case BPF_AND:
  1402. /* dreg &= sreg
  1403. * AND can not extend zero bits only shrink
  1404. * Ex. 0x00..00ffffff
  1405. * & 0x0f..ffffffff
  1406. * ----------------
  1407. * 0x00..00ffffff
  1408. */
  1409. dst_reg->imm = max(src_reg->imm, 63 - imm_log2);
  1410. break;
  1411. case BPF_OR:
  1412. /* dreg |= sreg
  1413. * OR can only extend zero bits
  1414. * Ex. 0x00..00ffffff
  1415. * | 0x0f..ffffffff
  1416. * ----------------
  1417. * 0x0f..00ffffff
  1418. */
  1419. dst_reg->imm = min(src_reg->imm, 63 - imm_log2);
  1420. break;
  1421. case BPF_SUB:
  1422. case BPF_MUL:
  1423. case BPF_RSH:
  1424. case BPF_LSH:
  1425. /* These may be flushed out later */
  1426. default:
  1427. mark_reg_unknown_value(regs, insn->dst_reg);
  1428. }
  1429. } else {
  1430. mark_reg_unknown_value(regs, insn->dst_reg);
  1431. }
  1432. dst_reg->type = UNKNOWN_VALUE;
  1433. return 0;
  1434. }
  1435. static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
  1436. struct bpf_insn *insn)
  1437. {
  1438. struct bpf_reg_state *regs = env->cur_state.regs;
  1439. struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
  1440. struct bpf_reg_state *src_reg = &regs[insn->src_reg];
  1441. u8 opcode = BPF_OP(insn->code);
  1442. if (BPF_SRC(insn->code) == BPF_X && src_reg->type == UNKNOWN_VALUE)
  1443. return evaluate_reg_imm_alu_unknown(env, insn);
  1444. /* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
  1445. * Don't care about overflow or negative values, just add them
  1446. */
  1447. if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
  1448. dst_reg->imm += insn->imm;
  1449. else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
  1450. src_reg->type == CONST_IMM)
  1451. dst_reg->imm += src_reg->imm;
  1452. else
  1453. mark_reg_unknown_value(regs, insn->dst_reg);
  1454. return 0;
  1455. }
  1456. static void check_reg_overflow(struct bpf_reg_state *reg)
  1457. {
  1458. if (reg->max_value > BPF_REGISTER_MAX_RANGE)
  1459. reg->max_value = BPF_REGISTER_MAX_RANGE;
  1460. if (reg->min_value < BPF_REGISTER_MIN_RANGE ||
  1461. reg->min_value > BPF_REGISTER_MAX_RANGE)
  1462. reg->min_value = BPF_REGISTER_MIN_RANGE;
  1463. }
  1464. static void adjust_reg_min_max_vals(struct bpf_verifier_env *env,
  1465. struct bpf_insn *insn)
  1466. {
  1467. struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
  1468. s64 min_val = BPF_REGISTER_MIN_RANGE;
  1469. u64 max_val = BPF_REGISTER_MAX_RANGE;
  1470. bool min_set = false, max_set = false;
  1471. u8 opcode = BPF_OP(insn->code);
  1472. dst_reg = &regs[insn->dst_reg];
  1473. if (BPF_SRC(insn->code) == BPF_X) {
  1474. check_reg_overflow(&regs[insn->src_reg]);
  1475. min_val = regs[insn->src_reg].min_value;
  1476. max_val = regs[insn->src_reg].max_value;
  1477. /* If the source register is a random pointer then the
  1478. * min_value/max_value values represent the range of the known
  1479. * accesses into that value, not the actual min/max value of the
  1480. * register itself. In this case we have to reset the reg range
  1481. * values so we know it is not safe to look at.
  1482. */
  1483. if (regs[insn->src_reg].type != CONST_IMM &&
  1484. regs[insn->src_reg].type != UNKNOWN_VALUE) {
  1485. min_val = BPF_REGISTER_MIN_RANGE;
  1486. max_val = BPF_REGISTER_MAX_RANGE;
  1487. }
  1488. } else if (insn->imm < BPF_REGISTER_MAX_RANGE &&
  1489. (s64)insn->imm > BPF_REGISTER_MIN_RANGE) {
  1490. min_val = max_val = insn->imm;
  1491. min_set = max_set = true;
  1492. }
  1493. /* We don't know anything about what was done to this register, mark it
  1494. * as unknown. Also, if both derived bounds came from signed/unsigned
  1495. * mixed compares and one side is unbounded, we cannot really do anything
  1496. * with them as boundaries cannot be trusted. Thus, arithmetic of two
  1497. * regs of such kind will get invalidated bounds on the dst side.
  1498. */
  1499. if ((min_val == BPF_REGISTER_MIN_RANGE &&
  1500. max_val == BPF_REGISTER_MAX_RANGE) ||
  1501. (BPF_SRC(insn->code) == BPF_X &&
  1502. ((min_val != BPF_REGISTER_MIN_RANGE &&
  1503. max_val == BPF_REGISTER_MAX_RANGE) ||
  1504. (min_val == BPF_REGISTER_MIN_RANGE &&
  1505. max_val != BPF_REGISTER_MAX_RANGE) ||
  1506. (dst_reg->min_value != BPF_REGISTER_MIN_RANGE &&
  1507. dst_reg->max_value == BPF_REGISTER_MAX_RANGE) ||
  1508. (dst_reg->min_value == BPF_REGISTER_MIN_RANGE &&
  1509. dst_reg->max_value != BPF_REGISTER_MAX_RANGE)) &&
  1510. regs[insn->dst_reg].value_from_signed !=
  1511. regs[insn->src_reg].value_from_signed)) {
  1512. reset_reg_range_values(regs, insn->dst_reg);
  1513. return;
  1514. }
  1515. /* If one of our values was at the end of our ranges then we can't just
  1516. * do our normal operations to the register, we need to set the values
  1517. * to the min/max since they are undefined.
  1518. */
  1519. if (opcode != BPF_SUB) {
  1520. if (min_val == BPF_REGISTER_MIN_RANGE)
  1521. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1522. if (max_val == BPF_REGISTER_MAX_RANGE)
  1523. dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
  1524. }
  1525. switch (opcode) {
  1526. case BPF_ADD:
  1527. if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
  1528. dst_reg->min_value += min_val;
  1529. if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1530. dst_reg->max_value += max_val;
  1531. break;
  1532. case BPF_SUB:
  1533. /* If one of our values was at the end of our ranges, then the
  1534. * _opposite_ value in the dst_reg goes to the end of our range.
  1535. */
  1536. if (min_val == BPF_REGISTER_MIN_RANGE)
  1537. dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
  1538. if (max_val == BPF_REGISTER_MAX_RANGE)
  1539. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1540. if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
  1541. dst_reg->min_value -= max_val;
  1542. if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1543. dst_reg->max_value -= min_val;
  1544. break;
  1545. case BPF_MUL:
  1546. if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
  1547. dst_reg->min_value *= min_val;
  1548. if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1549. dst_reg->max_value *= max_val;
  1550. break;
  1551. case BPF_AND:
  1552. /* Disallow AND'ing of negative numbers, ain't nobody got time
  1553. * for that. Otherwise the minimum is 0 and the max is the max
  1554. * value we could AND against.
  1555. */
  1556. if (min_val < 0)
  1557. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1558. else
  1559. dst_reg->min_value = 0;
  1560. dst_reg->max_value = max_val;
  1561. break;
  1562. case BPF_LSH:
  1563. /* Gotta have special overflow logic here, if we're shifting
  1564. * more than MAX_RANGE then just assume we have an invalid
  1565. * range.
  1566. */
  1567. if (min_val > ilog2(BPF_REGISTER_MAX_RANGE))
  1568. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1569. else if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
  1570. dst_reg->min_value <<= min_val;
  1571. if (max_val > ilog2(BPF_REGISTER_MAX_RANGE))
  1572. dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
  1573. else if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1574. dst_reg->max_value <<= max_val;
  1575. break;
  1576. case BPF_RSH:
  1577. /* RSH by a negative number is undefined, and the BPF_RSH is an
  1578. * unsigned shift, so make the appropriate casts.
  1579. */
  1580. if (min_val < 0 || dst_reg->min_value < 0)
  1581. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1582. else
  1583. dst_reg->min_value =
  1584. (u64)(dst_reg->min_value) >> min_val;
  1585. if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1586. dst_reg->max_value >>= max_val;
  1587. break;
  1588. default:
  1589. reset_reg_range_values(regs, insn->dst_reg);
  1590. break;
  1591. }
  1592. check_reg_overflow(dst_reg);
  1593. }
  1594. /* check validity of 32-bit and 64-bit arithmetic operations */
  1595. static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
  1596. {
  1597. struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
  1598. u8 opcode = BPF_OP(insn->code);
  1599. int err;
  1600. if (opcode == BPF_END || opcode == BPF_NEG) {
  1601. if (opcode == BPF_NEG) {
  1602. if (BPF_SRC(insn->code) != 0 ||
  1603. insn->src_reg != BPF_REG_0 ||
  1604. insn->off != 0 || insn->imm != 0) {
  1605. verbose("BPF_NEG uses reserved fields\n");
  1606. return -EINVAL;
  1607. }
  1608. } else {
  1609. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  1610. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
  1611. BPF_CLASS(insn->code) == BPF_ALU64) {
  1612. verbose("BPF_END uses reserved fields\n");
  1613. return -EINVAL;
  1614. }
  1615. }
  1616. /* check src operand */
  1617. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1618. if (err)
  1619. return err;
  1620. if (is_pointer_value(env, insn->dst_reg)) {
  1621. verbose("R%d pointer arithmetic prohibited\n",
  1622. insn->dst_reg);
  1623. return -EACCES;
  1624. }
  1625. /* check dest operand */
  1626. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1627. if (err)
  1628. return err;
  1629. } else if (opcode == BPF_MOV) {
  1630. if (BPF_SRC(insn->code) == BPF_X) {
  1631. if (insn->imm != 0 || insn->off != 0) {
  1632. verbose("BPF_MOV uses reserved fields\n");
  1633. return -EINVAL;
  1634. }
  1635. /* check src operand */
  1636. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1637. if (err)
  1638. return err;
  1639. } else {
  1640. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  1641. verbose("BPF_MOV uses reserved fields\n");
  1642. return -EINVAL;
  1643. }
  1644. }
  1645. /* check dest operand */
  1646. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1647. if (err)
  1648. return err;
  1649. /* we are setting our register to something new, we need to
  1650. * reset its range values.
  1651. */
  1652. reset_reg_range_values(regs, insn->dst_reg);
  1653. if (BPF_SRC(insn->code) == BPF_X) {
  1654. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  1655. /* case: R1 = R2
  1656. * copy register state to dest reg
  1657. */
  1658. regs[insn->dst_reg] = regs[insn->src_reg];
  1659. } else {
  1660. if (is_pointer_value(env, insn->src_reg)) {
  1661. verbose("R%d partial copy of pointer\n",
  1662. insn->src_reg);
  1663. return -EACCES;
  1664. }
  1665. mark_reg_unknown_value(regs, insn->dst_reg);
  1666. }
  1667. } else {
  1668. /* case: R = imm
  1669. * remember the value we stored into this reg
  1670. */
  1671. u64 imm;
  1672. if (BPF_CLASS(insn->code) == BPF_ALU64)
  1673. imm = insn->imm;
  1674. else
  1675. imm = (u32)insn->imm;
  1676. regs[insn->dst_reg].type = CONST_IMM;
  1677. regs[insn->dst_reg].imm = imm;
  1678. regs[insn->dst_reg].max_value = imm;
  1679. regs[insn->dst_reg].min_value = imm;
  1680. }
  1681. } else if (opcode > BPF_END) {
  1682. verbose("invalid BPF_ALU opcode %x\n", opcode);
  1683. return -EINVAL;
  1684. } else { /* all other ALU ops: and, sub, xor, add, ... */
  1685. if (BPF_SRC(insn->code) == BPF_X) {
  1686. if (insn->imm != 0 || insn->off != 0) {
  1687. verbose("BPF_ALU uses reserved fields\n");
  1688. return -EINVAL;
  1689. }
  1690. /* check src1 operand */
  1691. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1692. if (err)
  1693. return err;
  1694. } else {
  1695. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  1696. verbose("BPF_ALU uses reserved fields\n");
  1697. return -EINVAL;
  1698. }
  1699. }
  1700. /* check src2 operand */
  1701. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1702. if (err)
  1703. return err;
  1704. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  1705. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  1706. verbose("div by zero\n");
  1707. return -EINVAL;
  1708. }
  1709. if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
  1710. verbose("BPF_ARSH not supported for 32 bit ALU\n");
  1711. return -EINVAL;
  1712. }
  1713. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  1714. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  1715. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  1716. if (insn->imm < 0 || insn->imm >= size) {
  1717. verbose("invalid shift %d\n", insn->imm);
  1718. return -EINVAL;
  1719. }
  1720. }
  1721. /* check dest operand */
  1722. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  1723. if (err)
  1724. return err;
  1725. dst_reg = &regs[insn->dst_reg];
  1726. /* first we want to adjust our ranges. */
  1727. adjust_reg_min_max_vals(env, insn);
  1728. /* pattern match 'bpf_add Rx, imm' instruction */
  1729. if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
  1730. dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
  1731. dst_reg->type = PTR_TO_STACK;
  1732. dst_reg->imm = insn->imm;
  1733. return 0;
  1734. } else if (opcode == BPF_ADD &&
  1735. BPF_CLASS(insn->code) == BPF_ALU64 &&
  1736. dst_reg->type == PTR_TO_STACK &&
  1737. ((BPF_SRC(insn->code) == BPF_X &&
  1738. regs[insn->src_reg].type == CONST_IMM) ||
  1739. BPF_SRC(insn->code) == BPF_K)) {
  1740. if (BPF_SRC(insn->code) == BPF_X) {
  1741. /* check in case the register contains a big
  1742. * 64-bit value
  1743. */
  1744. if (regs[insn->src_reg].imm < -MAX_BPF_STACK ||
  1745. regs[insn->src_reg].imm > MAX_BPF_STACK) {
  1746. verbose("R%d value too big in R%d pointer arithmetic\n",
  1747. insn->src_reg, insn->dst_reg);
  1748. return -EACCES;
  1749. }
  1750. dst_reg->imm += regs[insn->src_reg].imm;
  1751. } else {
  1752. /* safe against overflow: addition of 32-bit
  1753. * numbers in 64-bit representation
  1754. */
  1755. dst_reg->imm += insn->imm;
  1756. }
  1757. if (dst_reg->imm > 0 || dst_reg->imm < -MAX_BPF_STACK) {
  1758. verbose("R%d out-of-bounds pointer arithmetic\n",
  1759. insn->dst_reg);
  1760. return -EACCES;
  1761. }
  1762. return 0;
  1763. } else if (opcode == BPF_ADD &&
  1764. BPF_CLASS(insn->code) == BPF_ALU64 &&
  1765. (dst_reg->type == PTR_TO_PACKET ||
  1766. (BPF_SRC(insn->code) == BPF_X &&
  1767. regs[insn->src_reg].type == PTR_TO_PACKET))) {
  1768. /* ptr_to_packet += K|X */
  1769. return check_packet_ptr_add(env, insn);
  1770. } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
  1771. dst_reg->type == UNKNOWN_VALUE &&
  1772. env->allow_ptr_leaks) {
  1773. /* unknown += K|X */
  1774. return evaluate_reg_alu(env, insn);
  1775. } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
  1776. dst_reg->type == CONST_IMM &&
  1777. env->allow_ptr_leaks) {
  1778. /* reg_imm += K|X */
  1779. return evaluate_reg_imm_alu(env, insn);
  1780. } else if (is_pointer_value(env, insn->dst_reg)) {
  1781. verbose("R%d pointer arithmetic prohibited\n",
  1782. insn->dst_reg);
  1783. return -EACCES;
  1784. } else if (BPF_SRC(insn->code) == BPF_X &&
  1785. is_pointer_value(env, insn->src_reg)) {
  1786. verbose("R%d pointer arithmetic prohibited\n",
  1787. insn->src_reg);
  1788. return -EACCES;
  1789. }
  1790. /* If we did pointer math on a map value then just set it to our
  1791. * PTR_TO_MAP_VALUE_ADJ type so we can deal with any stores or
  1792. * loads to this register appropriately, otherwise just mark the
  1793. * register as unknown.
  1794. */
  1795. if (env->allow_ptr_leaks &&
  1796. BPF_CLASS(insn->code) == BPF_ALU64 && opcode == BPF_ADD &&
  1797. (dst_reg->type == PTR_TO_MAP_VALUE ||
  1798. dst_reg->type == PTR_TO_MAP_VALUE_ADJ))
  1799. dst_reg->type = PTR_TO_MAP_VALUE_ADJ;
  1800. else
  1801. mark_reg_unknown_value(regs, insn->dst_reg);
  1802. }
  1803. return 0;
  1804. }
  1805. static void find_good_pkt_pointers(struct bpf_verifier_state *state,
  1806. struct bpf_reg_state *dst_reg)
  1807. {
  1808. struct bpf_reg_state *regs = state->regs, *reg;
  1809. int i;
  1810. /* LLVM can generate two kind of checks:
  1811. *
  1812. * Type 1:
  1813. *
  1814. * r2 = r3;
  1815. * r2 += 8;
  1816. * if (r2 > pkt_end) goto <handle exception>
  1817. * <access okay>
  1818. *
  1819. * Where:
  1820. * r2 == dst_reg, pkt_end == src_reg
  1821. * r2=pkt(id=n,off=8,r=0)
  1822. * r3=pkt(id=n,off=0,r=0)
  1823. *
  1824. * Type 2:
  1825. *
  1826. * r2 = r3;
  1827. * r2 += 8;
  1828. * if (pkt_end >= r2) goto <access okay>
  1829. * <handle exception>
  1830. *
  1831. * Where:
  1832. * pkt_end == dst_reg, r2 == src_reg
  1833. * r2=pkt(id=n,off=8,r=0)
  1834. * r3=pkt(id=n,off=0,r=0)
  1835. *
  1836. * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
  1837. * so that range of bytes [r3, r3 + 8) is safe to access.
  1838. */
  1839. for (i = 0; i < MAX_BPF_REG; i++)
  1840. if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
  1841. /* keep the maximum range already checked */
  1842. regs[i].range = max(regs[i].range, dst_reg->off);
  1843. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  1844. if (state->stack_slot_type[i] != STACK_SPILL)
  1845. continue;
  1846. reg = &state->spilled_regs[i / BPF_REG_SIZE];
  1847. if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
  1848. reg->range = max(reg->range, dst_reg->off);
  1849. }
  1850. }
  1851. /* Adjusts the register min/max values in the case that the dst_reg is the
  1852. * variable register that we are working on, and src_reg is a constant or we're
  1853. * simply doing a BPF_K check.
  1854. */
  1855. static void reg_set_min_max(struct bpf_reg_state *true_reg,
  1856. struct bpf_reg_state *false_reg, u64 val,
  1857. u8 opcode)
  1858. {
  1859. bool value_from_signed = true;
  1860. bool is_range = true;
  1861. switch (opcode) {
  1862. case BPF_JEQ:
  1863. /* If this is false then we know nothing Jon Snow, but if it is
  1864. * true then we know for sure.
  1865. */
  1866. true_reg->max_value = true_reg->min_value = val;
  1867. is_range = false;
  1868. break;
  1869. case BPF_JNE:
  1870. /* If this is true we know nothing Jon Snow, but if it is false
  1871. * we know the value for sure;
  1872. */
  1873. false_reg->max_value = false_reg->min_value = val;
  1874. is_range = false;
  1875. break;
  1876. case BPF_JGT:
  1877. value_from_signed = false;
  1878. /* fallthrough */
  1879. case BPF_JSGT:
  1880. if (true_reg->value_from_signed != value_from_signed)
  1881. reset_reg_range_values(true_reg, 0);
  1882. if (false_reg->value_from_signed != value_from_signed)
  1883. reset_reg_range_values(false_reg, 0);
  1884. if (opcode == BPF_JGT) {
  1885. /* Unsigned comparison, the minimum value is 0. */
  1886. false_reg->min_value = 0;
  1887. }
  1888. /* If this is false then we know the maximum val is val,
  1889. * otherwise we know the min val is val+1.
  1890. */
  1891. false_reg->max_value = val;
  1892. false_reg->value_from_signed = value_from_signed;
  1893. true_reg->min_value = val + 1;
  1894. true_reg->value_from_signed = value_from_signed;
  1895. break;
  1896. case BPF_JGE:
  1897. value_from_signed = false;
  1898. /* fallthrough */
  1899. case BPF_JSGE:
  1900. if (true_reg->value_from_signed != value_from_signed)
  1901. reset_reg_range_values(true_reg, 0);
  1902. if (false_reg->value_from_signed != value_from_signed)
  1903. reset_reg_range_values(false_reg, 0);
  1904. if (opcode == BPF_JGE) {
  1905. /* Unsigned comparison, the minimum value is 0. */
  1906. false_reg->min_value = 0;
  1907. }
  1908. /* If this is false then we know the maximum value is val - 1,
  1909. * otherwise we know the mimimum value is val.
  1910. */
  1911. false_reg->max_value = val - 1;
  1912. false_reg->value_from_signed = value_from_signed;
  1913. true_reg->min_value = val;
  1914. true_reg->value_from_signed = value_from_signed;
  1915. break;
  1916. default:
  1917. break;
  1918. }
  1919. check_reg_overflow(false_reg);
  1920. check_reg_overflow(true_reg);
  1921. if (is_range) {
  1922. if (__is_pointer_value(false, false_reg))
  1923. reset_reg_range_values(false_reg, 0);
  1924. if (__is_pointer_value(false, true_reg))
  1925. reset_reg_range_values(true_reg, 0);
  1926. }
  1927. }
  1928. /* Same as above, but for the case that dst_reg is a CONST_IMM reg and src_reg
  1929. * is the variable reg.
  1930. */
  1931. static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
  1932. struct bpf_reg_state *false_reg, u64 val,
  1933. u8 opcode)
  1934. {
  1935. bool value_from_signed = true;
  1936. bool is_range = true;
  1937. switch (opcode) {
  1938. case BPF_JEQ:
  1939. /* If this is false then we know nothing Jon Snow, but if it is
  1940. * true then we know for sure.
  1941. */
  1942. true_reg->max_value = true_reg->min_value = val;
  1943. is_range = false;
  1944. break;
  1945. case BPF_JNE:
  1946. /* If this is true we know nothing Jon Snow, but if it is false
  1947. * we know the value for sure;
  1948. */
  1949. false_reg->max_value = false_reg->min_value = val;
  1950. is_range = false;
  1951. break;
  1952. case BPF_JGT:
  1953. value_from_signed = false;
  1954. /* fallthrough */
  1955. case BPF_JSGT:
  1956. if (true_reg->value_from_signed != value_from_signed)
  1957. reset_reg_range_values(true_reg, 0);
  1958. if (false_reg->value_from_signed != value_from_signed)
  1959. reset_reg_range_values(false_reg, 0);
  1960. if (opcode == BPF_JGT) {
  1961. /* Unsigned comparison, the minimum value is 0. */
  1962. true_reg->min_value = 0;
  1963. }
  1964. /*
  1965. * If this is false, then the val is <= the register, if it is
  1966. * true the register <= to the val.
  1967. */
  1968. false_reg->min_value = val;
  1969. false_reg->value_from_signed = value_from_signed;
  1970. true_reg->max_value = val - 1;
  1971. true_reg->value_from_signed = value_from_signed;
  1972. break;
  1973. case BPF_JGE:
  1974. value_from_signed = false;
  1975. /* fallthrough */
  1976. case BPF_JSGE:
  1977. if (true_reg->value_from_signed != value_from_signed)
  1978. reset_reg_range_values(true_reg, 0);
  1979. if (false_reg->value_from_signed != value_from_signed)
  1980. reset_reg_range_values(false_reg, 0);
  1981. if (opcode == BPF_JGE) {
  1982. /* Unsigned comparison, the minimum value is 0. */
  1983. true_reg->min_value = 0;
  1984. }
  1985. /* If this is false then constant < register, if it is true then
  1986. * the register < constant.
  1987. */
  1988. false_reg->min_value = val + 1;
  1989. false_reg->value_from_signed = value_from_signed;
  1990. true_reg->max_value = val;
  1991. true_reg->value_from_signed = value_from_signed;
  1992. break;
  1993. default:
  1994. break;
  1995. }
  1996. check_reg_overflow(false_reg);
  1997. check_reg_overflow(true_reg);
  1998. if (is_range) {
  1999. if (__is_pointer_value(false, false_reg))
  2000. reset_reg_range_values(false_reg, 0);
  2001. if (__is_pointer_value(false, true_reg))
  2002. reset_reg_range_values(true_reg, 0);
  2003. }
  2004. }
  2005. static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
  2006. enum bpf_reg_type type)
  2007. {
  2008. struct bpf_reg_state *reg = &regs[regno];
  2009. if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
  2010. reg->type = type;
  2011. /* We don't need id from this point onwards anymore, thus we
  2012. * should better reset it, so that state pruning has chances
  2013. * to take effect.
  2014. */
  2015. reg->id = 0;
  2016. if (type == UNKNOWN_VALUE)
  2017. __mark_reg_unknown_value(regs, regno);
  2018. }
  2019. }
  2020. /* The logic is similar to find_good_pkt_pointers(), both could eventually
  2021. * be folded together at some point.
  2022. */
  2023. static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
  2024. enum bpf_reg_type type)
  2025. {
  2026. struct bpf_reg_state *regs = state->regs;
  2027. u32 id = regs[regno].id;
  2028. int i;
  2029. for (i = 0; i < MAX_BPF_REG; i++)
  2030. mark_map_reg(regs, i, id, type);
  2031. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  2032. if (state->stack_slot_type[i] != STACK_SPILL)
  2033. continue;
  2034. mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, type);
  2035. }
  2036. }
  2037. static int check_cond_jmp_op(struct bpf_verifier_env *env,
  2038. struct bpf_insn *insn, int *insn_idx)
  2039. {
  2040. struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
  2041. struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
  2042. u8 opcode = BPF_OP(insn->code);
  2043. int err;
  2044. if (opcode > BPF_EXIT) {
  2045. verbose("invalid BPF_JMP opcode %x\n", opcode);
  2046. return -EINVAL;
  2047. }
  2048. if (BPF_SRC(insn->code) == BPF_X) {
  2049. if (insn->imm != 0) {
  2050. verbose("BPF_JMP uses reserved fields\n");
  2051. return -EINVAL;
  2052. }
  2053. /* check src1 operand */
  2054. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2055. if (err)
  2056. return err;
  2057. if (is_pointer_value(env, insn->src_reg)) {
  2058. verbose("R%d pointer comparison prohibited\n",
  2059. insn->src_reg);
  2060. return -EACCES;
  2061. }
  2062. } else {
  2063. if (insn->src_reg != BPF_REG_0) {
  2064. verbose("BPF_JMP uses reserved fields\n");
  2065. return -EINVAL;
  2066. }
  2067. }
  2068. /* check src2 operand */
  2069. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  2070. if (err)
  2071. return err;
  2072. dst_reg = &regs[insn->dst_reg];
  2073. /* detect if R == 0 where R was initialized to zero earlier */
  2074. if (BPF_SRC(insn->code) == BPF_K &&
  2075. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  2076. dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
  2077. if (opcode == BPF_JEQ) {
  2078. /* if (imm == imm) goto pc+off;
  2079. * only follow the goto, ignore fall-through
  2080. */
  2081. *insn_idx += insn->off;
  2082. return 0;
  2083. } else {
  2084. /* if (imm != imm) goto pc+off;
  2085. * only follow fall-through branch, since
  2086. * that's where the program will go
  2087. */
  2088. return 0;
  2089. }
  2090. }
  2091. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  2092. if (!other_branch)
  2093. return -EFAULT;
  2094. /* detect if we are comparing against a constant value so we can adjust
  2095. * our min/max values for our dst register.
  2096. */
  2097. if (BPF_SRC(insn->code) == BPF_X) {
  2098. if (regs[insn->src_reg].type == CONST_IMM)
  2099. reg_set_min_max(&other_branch->regs[insn->dst_reg],
  2100. dst_reg, regs[insn->src_reg].imm,
  2101. opcode);
  2102. else if (dst_reg->type == CONST_IMM)
  2103. reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
  2104. &regs[insn->src_reg], dst_reg->imm,
  2105. opcode);
  2106. } else {
  2107. reg_set_min_max(&other_branch->regs[insn->dst_reg],
  2108. dst_reg, insn->imm, opcode);
  2109. }
  2110. /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
  2111. if (BPF_SRC(insn->code) == BPF_K &&
  2112. insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  2113. dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  2114. /* Mark all identical map registers in each branch as either
  2115. * safe or unknown depending R == 0 or R != 0 conditional.
  2116. */
  2117. mark_map_regs(this_branch, insn->dst_reg,
  2118. opcode == BPF_JEQ ? PTR_TO_MAP_VALUE : UNKNOWN_VALUE);
  2119. mark_map_regs(other_branch, insn->dst_reg,
  2120. opcode == BPF_JEQ ? UNKNOWN_VALUE : PTR_TO_MAP_VALUE);
  2121. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
  2122. dst_reg->type == PTR_TO_PACKET &&
  2123. regs[insn->src_reg].type == PTR_TO_PACKET_END) {
  2124. find_good_pkt_pointers(this_branch, dst_reg);
  2125. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
  2126. dst_reg->type == PTR_TO_PACKET_END &&
  2127. regs[insn->src_reg].type == PTR_TO_PACKET) {
  2128. find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
  2129. } else if (is_pointer_value(env, insn->dst_reg)) {
  2130. verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
  2131. return -EACCES;
  2132. }
  2133. if (log_level)
  2134. print_verifier_state(this_branch);
  2135. return 0;
  2136. }
  2137. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  2138. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  2139. {
  2140. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  2141. return (struct bpf_map *) (unsigned long) imm64;
  2142. }
  2143. /* verify BPF_LD_IMM64 instruction */
  2144. static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2145. {
  2146. struct bpf_reg_state *regs = env->cur_state.regs;
  2147. int err;
  2148. if (BPF_SIZE(insn->code) != BPF_DW) {
  2149. verbose("invalid BPF_LD_IMM insn\n");
  2150. return -EINVAL;
  2151. }
  2152. if (insn->off != 0) {
  2153. verbose("BPF_LD_IMM64 uses reserved fields\n");
  2154. return -EINVAL;
  2155. }
  2156. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  2157. if (err)
  2158. return err;
  2159. if (insn->src_reg == 0) {
  2160. /* generic move 64-bit immediate into a register,
  2161. * only analyzer needs to collect the ld_imm value.
  2162. */
  2163. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  2164. if (!env->analyzer_ops)
  2165. return 0;
  2166. regs[insn->dst_reg].type = CONST_IMM;
  2167. regs[insn->dst_reg].imm = imm;
  2168. return 0;
  2169. }
  2170. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  2171. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  2172. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  2173. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  2174. return 0;
  2175. }
  2176. static bool may_access_skb(enum bpf_prog_type type)
  2177. {
  2178. switch (type) {
  2179. case BPF_PROG_TYPE_SOCKET_FILTER:
  2180. case BPF_PROG_TYPE_SCHED_CLS:
  2181. case BPF_PROG_TYPE_SCHED_ACT:
  2182. return true;
  2183. default:
  2184. return false;
  2185. }
  2186. }
  2187. /* verify safety of LD_ABS|LD_IND instructions:
  2188. * - they can only appear in the programs where ctx == skb
  2189. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  2190. * preserve R6-R9, and store return value into R0
  2191. *
  2192. * Implicit input:
  2193. * ctx == skb == R6 == CTX
  2194. *
  2195. * Explicit input:
  2196. * SRC == any register
  2197. * IMM == 32-bit immediate
  2198. *
  2199. * Output:
  2200. * R0 - 8/16/32-bit skb data converted to cpu endianness
  2201. */
  2202. static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2203. {
  2204. struct bpf_reg_state *regs = env->cur_state.regs;
  2205. u8 mode = BPF_MODE(insn->code);
  2206. struct bpf_reg_state *reg;
  2207. int i, err;
  2208. if (!may_access_skb(env->prog->type)) {
  2209. verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
  2210. return -EINVAL;
  2211. }
  2212. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  2213. BPF_SIZE(insn->code) == BPF_DW ||
  2214. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  2215. verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
  2216. return -EINVAL;
  2217. }
  2218. /* check whether implicit source operand (register R6) is readable */
  2219. err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
  2220. if (err)
  2221. return err;
  2222. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  2223. verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  2224. return -EINVAL;
  2225. }
  2226. if (mode == BPF_IND) {
  2227. /* check explicit source operand */
  2228. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2229. if (err)
  2230. return err;
  2231. }
  2232. /* reset caller saved regs to unreadable */
  2233. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  2234. reg = regs + caller_saved[i];
  2235. reg->type = NOT_INIT;
  2236. reg->imm = 0;
  2237. }
  2238. /* mark destination R0 register as readable, since it contains
  2239. * the value fetched from the packet
  2240. */
  2241. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  2242. return 0;
  2243. }
  2244. /* non-recursive DFS pseudo code
  2245. * 1 procedure DFS-iterative(G,v):
  2246. * 2 label v as discovered
  2247. * 3 let S be a stack
  2248. * 4 S.push(v)
  2249. * 5 while S is not empty
  2250. * 6 t <- S.pop()
  2251. * 7 if t is what we're looking for:
  2252. * 8 return t
  2253. * 9 for all edges e in G.adjacentEdges(t) do
  2254. * 10 if edge e is already labelled
  2255. * 11 continue with the next edge
  2256. * 12 w <- G.adjacentVertex(t,e)
  2257. * 13 if vertex w is not discovered and not explored
  2258. * 14 label e as tree-edge
  2259. * 15 label w as discovered
  2260. * 16 S.push(w)
  2261. * 17 continue at 5
  2262. * 18 else if vertex w is discovered
  2263. * 19 label e as back-edge
  2264. * 20 else
  2265. * 21 // vertex w is explored
  2266. * 22 label e as forward- or cross-edge
  2267. * 23 label t as explored
  2268. * 24 S.pop()
  2269. *
  2270. * convention:
  2271. * 0x10 - discovered
  2272. * 0x11 - discovered and fall-through edge labelled
  2273. * 0x12 - discovered and fall-through and branch edges labelled
  2274. * 0x20 - explored
  2275. */
  2276. enum {
  2277. DISCOVERED = 0x10,
  2278. EXPLORED = 0x20,
  2279. FALLTHROUGH = 1,
  2280. BRANCH = 2,
  2281. };
  2282. #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
  2283. static int *insn_stack; /* stack of insns to process */
  2284. static int cur_stack; /* current stack index */
  2285. static int *insn_state;
  2286. /* t, w, e - match pseudo-code above:
  2287. * t - index of current instruction
  2288. * w - next instruction
  2289. * e - edge
  2290. */
  2291. static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
  2292. {
  2293. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  2294. return 0;
  2295. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  2296. return 0;
  2297. if (w < 0 || w >= env->prog->len) {
  2298. verbose("jump out of range from insn %d to %d\n", t, w);
  2299. return -EINVAL;
  2300. }
  2301. if (e == BRANCH)
  2302. /* mark branch target for state pruning */
  2303. env->explored_states[w] = STATE_LIST_MARK;
  2304. if (insn_state[w] == 0) {
  2305. /* tree-edge */
  2306. insn_state[t] = DISCOVERED | e;
  2307. insn_state[w] = DISCOVERED;
  2308. if (cur_stack >= env->prog->len)
  2309. return -E2BIG;
  2310. insn_stack[cur_stack++] = w;
  2311. return 1;
  2312. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  2313. verbose("back-edge from insn %d to %d\n", t, w);
  2314. return -EINVAL;
  2315. } else if (insn_state[w] == EXPLORED) {
  2316. /* forward- or cross-edge */
  2317. insn_state[t] = DISCOVERED | e;
  2318. } else {
  2319. verbose("insn state internal bug\n");
  2320. return -EFAULT;
  2321. }
  2322. return 0;
  2323. }
  2324. /* non-recursive depth-first-search to detect loops in BPF program
  2325. * loop == back-edge in directed graph
  2326. */
  2327. static int check_cfg(struct bpf_verifier_env *env)
  2328. {
  2329. struct bpf_insn *insns = env->prog->insnsi;
  2330. int insn_cnt = env->prog->len;
  2331. int ret = 0;
  2332. int i, t;
  2333. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  2334. if (!insn_state)
  2335. return -ENOMEM;
  2336. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  2337. if (!insn_stack) {
  2338. kfree(insn_state);
  2339. return -ENOMEM;
  2340. }
  2341. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  2342. insn_stack[0] = 0; /* 0 is the first instruction */
  2343. cur_stack = 1;
  2344. peek_stack:
  2345. if (cur_stack == 0)
  2346. goto check_state;
  2347. t = insn_stack[cur_stack - 1];
  2348. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  2349. u8 opcode = BPF_OP(insns[t].code);
  2350. if (opcode == BPF_EXIT) {
  2351. goto mark_explored;
  2352. } else if (opcode == BPF_CALL) {
  2353. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2354. if (ret == 1)
  2355. goto peek_stack;
  2356. else if (ret < 0)
  2357. goto err_free;
  2358. if (t + 1 < insn_cnt)
  2359. env->explored_states[t + 1] = STATE_LIST_MARK;
  2360. } else if (opcode == BPF_JA) {
  2361. if (BPF_SRC(insns[t].code) != BPF_K) {
  2362. ret = -EINVAL;
  2363. goto err_free;
  2364. }
  2365. /* unconditional jump with single edge */
  2366. ret = push_insn(t, t + insns[t].off + 1,
  2367. FALLTHROUGH, env);
  2368. if (ret == 1)
  2369. goto peek_stack;
  2370. else if (ret < 0)
  2371. goto err_free;
  2372. /* tell verifier to check for equivalent states
  2373. * after every call and jump
  2374. */
  2375. if (t + 1 < insn_cnt)
  2376. env->explored_states[t + 1] = STATE_LIST_MARK;
  2377. } else {
  2378. /* conditional jump with two edges */
  2379. env->explored_states[t] = STATE_LIST_MARK;
  2380. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2381. if (ret == 1)
  2382. goto peek_stack;
  2383. else if (ret < 0)
  2384. goto err_free;
  2385. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  2386. if (ret == 1)
  2387. goto peek_stack;
  2388. else if (ret < 0)
  2389. goto err_free;
  2390. }
  2391. } else {
  2392. /* all other non-branch instructions with single
  2393. * fall-through edge
  2394. */
  2395. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2396. if (ret == 1)
  2397. goto peek_stack;
  2398. else if (ret < 0)
  2399. goto err_free;
  2400. }
  2401. mark_explored:
  2402. insn_state[t] = EXPLORED;
  2403. if (cur_stack-- <= 0) {
  2404. verbose("pop stack internal bug\n");
  2405. ret = -EFAULT;
  2406. goto err_free;
  2407. }
  2408. goto peek_stack;
  2409. check_state:
  2410. for (i = 0; i < insn_cnt; i++) {
  2411. if (insn_state[i] != EXPLORED) {
  2412. verbose("unreachable insn %d\n", i);
  2413. ret = -EINVAL;
  2414. goto err_free;
  2415. }
  2416. }
  2417. ret = 0; /* cfg looks good */
  2418. err_free:
  2419. kfree(insn_state);
  2420. kfree(insn_stack);
  2421. return ret;
  2422. }
  2423. /* the following conditions reduce the number of explored insns
  2424. * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
  2425. */
  2426. static bool compare_ptrs_to_packet(struct bpf_reg_state *old,
  2427. struct bpf_reg_state *cur)
  2428. {
  2429. if (old->id != cur->id)
  2430. return false;
  2431. /* old ptr_to_packet is more conservative, since it allows smaller
  2432. * range. Ex:
  2433. * old(off=0,r=10) is equal to cur(off=0,r=20), because
  2434. * old(off=0,r=10) means that with range=10 the verifier proceeded
  2435. * further and found no issues with the program. Now we're in the same
  2436. * spot with cur(off=0,r=20), so we're safe too, since anything further
  2437. * will only be looking at most 10 bytes after this pointer.
  2438. */
  2439. if (old->off == cur->off && old->range < cur->range)
  2440. return true;
  2441. /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
  2442. * since both cannot be used for packet access and safe(old)
  2443. * pointer has smaller off that could be used for further
  2444. * 'if (ptr > data_end)' check
  2445. * Ex:
  2446. * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
  2447. * that we cannot access the packet.
  2448. * The safe range is:
  2449. * [ptr, ptr + range - off)
  2450. * so whenever off >=range, it means no safe bytes from this pointer.
  2451. * When comparing old->off <= cur->off, it means that older code
  2452. * went with smaller offset and that offset was later
  2453. * used to figure out the safe range after 'if (ptr > data_end)' check
  2454. * Say, 'old' state was explored like:
  2455. * ... R3(off=0, r=0)
  2456. * R4 = R3 + 20
  2457. * ... now R4(off=20,r=0) <-- here
  2458. * if (R4 > data_end)
  2459. * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
  2460. * ... the code further went all the way to bpf_exit.
  2461. * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
  2462. * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
  2463. * goes further, such cur_R4 will give larger safe packet range after
  2464. * 'if (R4 > data_end)' and all further insn were already good with r=20,
  2465. * so they will be good with r=30 and we can prune the search.
  2466. */
  2467. if (old->off <= cur->off &&
  2468. old->off >= old->range && cur->off >= cur->range)
  2469. return true;
  2470. return false;
  2471. }
  2472. /* compare two verifier states
  2473. *
  2474. * all states stored in state_list are known to be valid, since
  2475. * verifier reached 'bpf_exit' instruction through them
  2476. *
  2477. * this function is called when verifier exploring different branches of
  2478. * execution popped from the state stack. If it sees an old state that has
  2479. * more strict register state and more strict stack state then this execution
  2480. * branch doesn't need to be explored further, since verifier already
  2481. * concluded that more strict state leads to valid finish.
  2482. *
  2483. * Therefore two states are equivalent if register state is more conservative
  2484. * and explored stack state is more conservative than the current one.
  2485. * Example:
  2486. * explored current
  2487. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  2488. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  2489. *
  2490. * In other words if current stack state (one being explored) has more
  2491. * valid slots than old one that already passed validation, it means
  2492. * the verifier can stop exploring and conclude that current state is valid too
  2493. *
  2494. * Similarly with registers. If explored state has register type as invalid
  2495. * whereas register type in current state is meaningful, it means that
  2496. * the current state will reach 'bpf_exit' instruction safely
  2497. */
  2498. static bool states_equal(struct bpf_verifier_env *env,
  2499. struct bpf_verifier_state *old,
  2500. struct bpf_verifier_state *cur)
  2501. {
  2502. bool varlen_map_access = env->varlen_map_value_access;
  2503. struct bpf_reg_state *rold, *rcur;
  2504. int i;
  2505. for (i = 0; i < MAX_BPF_REG; i++) {
  2506. rold = &old->regs[i];
  2507. rcur = &cur->regs[i];
  2508. if (memcmp(rold, rcur, sizeof(*rold)) == 0)
  2509. continue;
  2510. /* If the ranges were not the same, but everything else was and
  2511. * we didn't do a variable access into a map then we are a-ok.
  2512. */
  2513. if (!varlen_map_access &&
  2514. memcmp(rold, rcur, offsetofend(struct bpf_reg_state, id)) == 0)
  2515. continue;
  2516. /* If we didn't map access then again we don't care about the
  2517. * mismatched range values and it's ok if our old type was
  2518. * UNKNOWN and we didn't go to a NOT_INIT'ed or pointer reg.
  2519. */
  2520. if (rold->type == NOT_INIT ||
  2521. (!varlen_map_access && rold->type == UNKNOWN_VALUE &&
  2522. rcur->type != NOT_INIT &&
  2523. !__is_pointer_value(env->allow_ptr_leaks, rcur)))
  2524. continue;
  2525. /* Don't care about the reg->id in this case. */
  2526. if (rold->type == PTR_TO_MAP_VALUE_OR_NULL &&
  2527. rcur->type == PTR_TO_MAP_VALUE_OR_NULL &&
  2528. rold->map_ptr == rcur->map_ptr)
  2529. continue;
  2530. if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
  2531. compare_ptrs_to_packet(rold, rcur))
  2532. continue;
  2533. return false;
  2534. }
  2535. for (i = 0; i < MAX_BPF_STACK; i++) {
  2536. if (old->stack_slot_type[i] == STACK_INVALID)
  2537. continue;
  2538. if (old->stack_slot_type[i] != cur->stack_slot_type[i])
  2539. /* Ex: old explored (safe) state has STACK_SPILL in
  2540. * this stack slot, but current has has STACK_MISC ->
  2541. * this verifier states are not equivalent,
  2542. * return false to continue verification of this path
  2543. */
  2544. return false;
  2545. if (i % BPF_REG_SIZE)
  2546. continue;
  2547. if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
  2548. &cur->spilled_regs[i / BPF_REG_SIZE],
  2549. sizeof(old->spilled_regs[0])))
  2550. /* when explored and current stack slot types are
  2551. * the same, check that stored pointers types
  2552. * are the same as well.
  2553. * Ex: explored safe path could have stored
  2554. * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
  2555. * but current path has stored:
  2556. * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
  2557. * such verifier states are not equivalent.
  2558. * return false to continue verification of this path
  2559. */
  2560. return false;
  2561. else
  2562. continue;
  2563. }
  2564. return true;
  2565. }
  2566. static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
  2567. {
  2568. struct bpf_verifier_state_list *new_sl;
  2569. struct bpf_verifier_state_list *sl;
  2570. sl = env->explored_states[insn_idx];
  2571. if (!sl)
  2572. /* this 'insn_idx' instruction wasn't marked, so we will not
  2573. * be doing state search here
  2574. */
  2575. return 0;
  2576. while (sl != STATE_LIST_MARK) {
  2577. if (states_equal(env, &sl->state, &env->cur_state))
  2578. /* reached equivalent register/stack state,
  2579. * prune the search
  2580. */
  2581. return 1;
  2582. sl = sl->next;
  2583. }
  2584. /* there were no equivalent states, remember current one.
  2585. * technically the current state is not proven to be safe yet,
  2586. * but it will either reach bpf_exit (which means it's safe) or
  2587. * it will be rejected. Since there are no loops, we won't be
  2588. * seeing this 'insn_idx' instruction again on the way to bpf_exit
  2589. */
  2590. new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
  2591. if (!new_sl)
  2592. return -ENOMEM;
  2593. /* add new state to the head of linked list */
  2594. memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
  2595. new_sl->next = env->explored_states[insn_idx];
  2596. env->explored_states[insn_idx] = new_sl;
  2597. return 0;
  2598. }
  2599. static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
  2600. int insn_idx, int prev_insn_idx)
  2601. {
  2602. if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
  2603. return 0;
  2604. return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
  2605. }
  2606. static int do_check(struct bpf_verifier_env *env)
  2607. {
  2608. struct bpf_verifier_state *state = &env->cur_state;
  2609. struct bpf_insn *insns = env->prog->insnsi;
  2610. struct bpf_reg_state *regs = state->regs;
  2611. int insn_cnt = env->prog->len;
  2612. int insn_idx, prev_insn_idx = 0;
  2613. int insn_processed = 0;
  2614. bool do_print_state = false;
  2615. init_reg_state(regs);
  2616. insn_idx = 0;
  2617. env->varlen_map_value_access = false;
  2618. for (;;) {
  2619. struct bpf_insn *insn;
  2620. u8 class;
  2621. int err;
  2622. if (insn_idx >= insn_cnt) {
  2623. verbose("invalid insn idx %d insn_cnt %d\n",
  2624. insn_idx, insn_cnt);
  2625. return -EFAULT;
  2626. }
  2627. insn = &insns[insn_idx];
  2628. class = BPF_CLASS(insn->code);
  2629. if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
  2630. verbose("BPF program is too large. Proccessed %d insn\n",
  2631. insn_processed);
  2632. return -E2BIG;
  2633. }
  2634. err = is_state_visited(env, insn_idx);
  2635. if (err < 0)
  2636. return err;
  2637. if (err == 1) {
  2638. /* found equivalent state, can prune the search */
  2639. if (log_level) {
  2640. if (do_print_state)
  2641. verbose("\nfrom %d to %d: safe\n",
  2642. prev_insn_idx, insn_idx);
  2643. else
  2644. verbose("%d: safe\n", insn_idx);
  2645. }
  2646. goto process_bpf_exit;
  2647. }
  2648. if (signal_pending(current))
  2649. return -EAGAIN;
  2650. if (need_resched())
  2651. cond_resched();
  2652. if (log_level && do_print_state) {
  2653. verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
  2654. print_verifier_state(&env->cur_state);
  2655. do_print_state = false;
  2656. }
  2657. if (log_level) {
  2658. verbose("%d: ", insn_idx);
  2659. print_bpf_insn(env, insn);
  2660. }
  2661. err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
  2662. if (err)
  2663. return err;
  2664. env->insn_aux_data[insn_idx].seen = true;
  2665. if (class == BPF_ALU || class == BPF_ALU64) {
  2666. err = check_alu_op(env, insn);
  2667. if (err)
  2668. return err;
  2669. } else if (class == BPF_LDX) {
  2670. enum bpf_reg_type *prev_src_type, src_reg_type;
  2671. /* check for reserved fields is already done */
  2672. /* check src operand */
  2673. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2674. if (err)
  2675. return err;
  2676. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  2677. if (err)
  2678. return err;
  2679. src_reg_type = regs[insn->src_reg].type;
  2680. /* check that memory (src_reg + off) is readable,
  2681. * the state of dst_reg will be updated by this func
  2682. */
  2683. err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
  2684. BPF_SIZE(insn->code), BPF_READ,
  2685. insn->dst_reg);
  2686. if (err)
  2687. return err;
  2688. reset_reg_range_values(regs, insn->dst_reg);
  2689. if (BPF_SIZE(insn->code) != BPF_W &&
  2690. BPF_SIZE(insn->code) != BPF_DW) {
  2691. insn_idx++;
  2692. continue;
  2693. }
  2694. prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
  2695. if (*prev_src_type == NOT_INIT) {
  2696. /* saw a valid insn
  2697. * dst_reg = *(u32 *)(src_reg + off)
  2698. * save type to validate intersecting paths
  2699. */
  2700. *prev_src_type = src_reg_type;
  2701. } else if (src_reg_type != *prev_src_type &&
  2702. (src_reg_type == PTR_TO_CTX ||
  2703. *prev_src_type == PTR_TO_CTX)) {
  2704. /* ABuser program is trying to use the same insn
  2705. * dst_reg = *(u32*) (src_reg + off)
  2706. * with different pointer types:
  2707. * src_reg == ctx in one branch and
  2708. * src_reg == stack|map in some other branch.
  2709. * Reject it.
  2710. */
  2711. verbose("same insn cannot be used with different pointers\n");
  2712. return -EINVAL;
  2713. }
  2714. } else if (class == BPF_STX) {
  2715. enum bpf_reg_type *prev_dst_type, dst_reg_type;
  2716. if (BPF_MODE(insn->code) == BPF_XADD) {
  2717. err = check_xadd(env, insn_idx, insn);
  2718. if (err)
  2719. return err;
  2720. insn_idx++;
  2721. continue;
  2722. }
  2723. /* check src1 operand */
  2724. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2725. if (err)
  2726. return err;
  2727. /* check src2 operand */
  2728. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  2729. if (err)
  2730. return err;
  2731. dst_reg_type = regs[insn->dst_reg].type;
  2732. /* check that memory (dst_reg + off) is writeable */
  2733. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  2734. BPF_SIZE(insn->code), BPF_WRITE,
  2735. insn->src_reg);
  2736. if (err)
  2737. return err;
  2738. prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
  2739. if (*prev_dst_type == NOT_INIT) {
  2740. *prev_dst_type = dst_reg_type;
  2741. } else if (dst_reg_type != *prev_dst_type &&
  2742. (dst_reg_type == PTR_TO_CTX ||
  2743. *prev_dst_type == PTR_TO_CTX)) {
  2744. verbose("same insn cannot be used with different pointers\n");
  2745. return -EINVAL;
  2746. }
  2747. } else if (class == BPF_ST) {
  2748. if (BPF_MODE(insn->code) != BPF_MEM ||
  2749. insn->src_reg != BPF_REG_0) {
  2750. verbose("BPF_ST uses reserved fields\n");
  2751. return -EINVAL;
  2752. }
  2753. /* check src operand */
  2754. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  2755. if (err)
  2756. return err;
  2757. if (is_ctx_reg(env, insn->dst_reg)) {
  2758. verbose("BPF_ST stores into R%d context is not allowed\n",
  2759. insn->dst_reg);
  2760. return -EACCES;
  2761. }
  2762. /* check that memory (dst_reg + off) is writeable */
  2763. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  2764. BPF_SIZE(insn->code), BPF_WRITE,
  2765. -1);
  2766. if (err)
  2767. return err;
  2768. } else if (class == BPF_JMP) {
  2769. u8 opcode = BPF_OP(insn->code);
  2770. if (opcode == BPF_CALL) {
  2771. if (BPF_SRC(insn->code) != BPF_K ||
  2772. insn->off != 0 ||
  2773. insn->src_reg != BPF_REG_0 ||
  2774. insn->dst_reg != BPF_REG_0) {
  2775. verbose("BPF_CALL uses reserved fields\n");
  2776. return -EINVAL;
  2777. }
  2778. err = check_call(env, insn->imm, insn_idx);
  2779. if (err)
  2780. return err;
  2781. } else if (opcode == BPF_JA) {
  2782. if (BPF_SRC(insn->code) != BPF_K ||
  2783. insn->imm != 0 ||
  2784. insn->src_reg != BPF_REG_0 ||
  2785. insn->dst_reg != BPF_REG_0) {
  2786. verbose("BPF_JA uses reserved fields\n");
  2787. return -EINVAL;
  2788. }
  2789. insn_idx += insn->off + 1;
  2790. continue;
  2791. } else if (opcode == BPF_EXIT) {
  2792. if (BPF_SRC(insn->code) != BPF_K ||
  2793. insn->imm != 0 ||
  2794. insn->src_reg != BPF_REG_0 ||
  2795. insn->dst_reg != BPF_REG_0) {
  2796. verbose("BPF_EXIT uses reserved fields\n");
  2797. return -EINVAL;
  2798. }
  2799. /* eBPF calling convetion is such that R0 is used
  2800. * to return the value from eBPF program.
  2801. * Make sure that it's readable at this time
  2802. * of bpf_exit, which means that program wrote
  2803. * something into it earlier
  2804. */
  2805. err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
  2806. if (err)
  2807. return err;
  2808. if (is_pointer_value(env, BPF_REG_0)) {
  2809. verbose("R0 leaks addr as return value\n");
  2810. return -EACCES;
  2811. }
  2812. process_bpf_exit:
  2813. insn_idx = pop_stack(env, &prev_insn_idx);
  2814. if (insn_idx < 0) {
  2815. break;
  2816. } else {
  2817. do_print_state = true;
  2818. continue;
  2819. }
  2820. } else {
  2821. err = check_cond_jmp_op(env, insn, &insn_idx);
  2822. if (err)
  2823. return err;
  2824. }
  2825. } else if (class == BPF_LD) {
  2826. u8 mode = BPF_MODE(insn->code);
  2827. if (mode == BPF_ABS || mode == BPF_IND) {
  2828. err = check_ld_abs(env, insn);
  2829. if (err)
  2830. return err;
  2831. } else if (mode == BPF_IMM) {
  2832. err = check_ld_imm(env, insn);
  2833. if (err)
  2834. return err;
  2835. insn_idx++;
  2836. env->insn_aux_data[insn_idx].seen = true;
  2837. } else {
  2838. verbose("invalid BPF_LD mode\n");
  2839. return -EINVAL;
  2840. }
  2841. reset_reg_range_values(regs, insn->dst_reg);
  2842. } else {
  2843. verbose("unknown insn class %d\n", class);
  2844. return -EINVAL;
  2845. }
  2846. insn_idx++;
  2847. }
  2848. verbose("processed %d insns\n", insn_processed);
  2849. return 0;
  2850. }
  2851. static int check_map_prog_compatibility(struct bpf_map *map,
  2852. struct bpf_prog *prog)
  2853. {
  2854. if (prog->type == BPF_PROG_TYPE_PERF_EVENT &&
  2855. (map->map_type == BPF_MAP_TYPE_HASH ||
  2856. map->map_type == BPF_MAP_TYPE_PERCPU_HASH) &&
  2857. (map->map_flags & BPF_F_NO_PREALLOC)) {
  2858. verbose("perf_event programs can only use preallocated hash map\n");
  2859. return -EINVAL;
  2860. }
  2861. return 0;
  2862. }
  2863. /* look for pseudo eBPF instructions that access map FDs and
  2864. * replace them with actual map pointers
  2865. */
  2866. static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
  2867. {
  2868. struct bpf_insn *insn = env->prog->insnsi;
  2869. int insn_cnt = env->prog->len;
  2870. int i, j, err;
  2871. for (i = 0; i < insn_cnt; i++, insn++) {
  2872. if (BPF_CLASS(insn->code) == BPF_LDX &&
  2873. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  2874. verbose("BPF_LDX uses reserved fields\n");
  2875. return -EINVAL;
  2876. }
  2877. if (BPF_CLASS(insn->code) == BPF_STX &&
  2878. ((BPF_MODE(insn->code) != BPF_MEM &&
  2879. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  2880. verbose("BPF_STX uses reserved fields\n");
  2881. return -EINVAL;
  2882. }
  2883. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  2884. struct bpf_map *map;
  2885. struct fd f;
  2886. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  2887. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  2888. insn[1].off != 0) {
  2889. verbose("invalid bpf_ld_imm64 insn\n");
  2890. return -EINVAL;
  2891. }
  2892. if (insn->src_reg == 0)
  2893. /* valid generic load 64-bit imm */
  2894. goto next_insn;
  2895. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  2896. verbose("unrecognized bpf_ld_imm64 insn\n");
  2897. return -EINVAL;
  2898. }
  2899. f = fdget(insn->imm);
  2900. map = __bpf_map_get(f);
  2901. if (IS_ERR(map)) {
  2902. verbose("fd %d is not pointing to valid bpf_map\n",
  2903. insn->imm);
  2904. return PTR_ERR(map);
  2905. }
  2906. err = check_map_prog_compatibility(map, env->prog);
  2907. if (err) {
  2908. fdput(f);
  2909. return err;
  2910. }
  2911. /* store map pointer inside BPF_LD_IMM64 instruction */
  2912. insn[0].imm = (u32) (unsigned long) map;
  2913. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  2914. /* check whether we recorded this map already */
  2915. for (j = 0; j < env->used_map_cnt; j++)
  2916. if (env->used_maps[j] == map) {
  2917. fdput(f);
  2918. goto next_insn;
  2919. }
  2920. if (env->used_map_cnt >= MAX_USED_MAPS) {
  2921. fdput(f);
  2922. return -E2BIG;
  2923. }
  2924. /* hold the map. If the program is rejected by verifier,
  2925. * the map will be released by release_maps() or it
  2926. * will be used by the valid program until it's unloaded
  2927. * and all maps are released in free_used_maps()
  2928. */
  2929. map = bpf_map_inc(map, false);
  2930. if (IS_ERR(map)) {
  2931. fdput(f);
  2932. return PTR_ERR(map);
  2933. }
  2934. env->used_maps[env->used_map_cnt++] = map;
  2935. fdput(f);
  2936. next_insn:
  2937. insn++;
  2938. i++;
  2939. }
  2940. }
  2941. /* now all pseudo BPF_LD_IMM64 instructions load valid
  2942. * 'struct bpf_map *' into a register instead of user map_fd.
  2943. * These pointers will be used later by verifier to validate map access.
  2944. */
  2945. return 0;
  2946. }
  2947. /* drop refcnt of maps used by the rejected program */
  2948. static void release_maps(struct bpf_verifier_env *env)
  2949. {
  2950. int i;
  2951. for (i = 0; i < env->used_map_cnt; i++)
  2952. bpf_map_put(env->used_maps[i]);
  2953. }
  2954. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  2955. static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
  2956. {
  2957. struct bpf_insn *insn = env->prog->insnsi;
  2958. int insn_cnt = env->prog->len;
  2959. int i;
  2960. for (i = 0; i < insn_cnt; i++, insn++)
  2961. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  2962. insn->src_reg = 0;
  2963. }
  2964. /* single env->prog->insni[off] instruction was replaced with the range
  2965. * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
  2966. * [0, off) and [off, end) to new locations, so the patched range stays zero
  2967. */
  2968. static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
  2969. u32 off, u32 cnt)
  2970. {
  2971. struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
  2972. int i;
  2973. if (cnt == 1)
  2974. return 0;
  2975. new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
  2976. if (!new_data)
  2977. return -ENOMEM;
  2978. memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
  2979. memcpy(new_data + off + cnt - 1, old_data + off,
  2980. sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
  2981. for (i = off; i < off + cnt - 1; i++)
  2982. new_data[i].seen = true;
  2983. env->insn_aux_data = new_data;
  2984. vfree(old_data);
  2985. return 0;
  2986. }
  2987. static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
  2988. const struct bpf_insn *patch, u32 len)
  2989. {
  2990. struct bpf_prog *new_prog;
  2991. new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
  2992. if (!new_prog)
  2993. return NULL;
  2994. if (adjust_insn_aux_data(env, new_prog->len, off, len))
  2995. return NULL;
  2996. return new_prog;
  2997. }
  2998. /* The verifier does more data flow analysis than llvm and will not explore
  2999. * branches that are dead at run time. Malicious programs can have dead code
  3000. * too. Therefore replace all dead at-run-time code with nops.
  3001. */
  3002. static void sanitize_dead_code(struct bpf_verifier_env *env)
  3003. {
  3004. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  3005. struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
  3006. struct bpf_insn *insn = env->prog->insnsi;
  3007. const int insn_cnt = env->prog->len;
  3008. int i;
  3009. for (i = 0; i < insn_cnt; i++) {
  3010. if (aux_data[i].seen)
  3011. continue;
  3012. memcpy(insn + i, &nop, sizeof(nop));
  3013. }
  3014. }
  3015. /* convert load instructions that access fields of 'struct __sk_buff'
  3016. * into sequence of instructions that access fields of 'struct sk_buff'
  3017. */
  3018. static int convert_ctx_accesses(struct bpf_verifier_env *env)
  3019. {
  3020. const struct bpf_verifier_ops *ops = env->prog->aux->ops;
  3021. const int insn_cnt = env->prog->len;
  3022. struct bpf_insn insn_buf[16], *insn;
  3023. struct bpf_prog *new_prog;
  3024. enum bpf_access_type type;
  3025. int i, cnt, delta = 0;
  3026. if (ops->gen_prologue) {
  3027. cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
  3028. env->prog);
  3029. if (cnt >= ARRAY_SIZE(insn_buf)) {
  3030. verbose("bpf verifier is misconfigured\n");
  3031. return -EINVAL;
  3032. } else if (cnt) {
  3033. new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
  3034. if (!new_prog)
  3035. return -ENOMEM;
  3036. env->prog = new_prog;
  3037. delta += cnt - 1;
  3038. }
  3039. }
  3040. if (!ops->convert_ctx_access)
  3041. return 0;
  3042. insn = env->prog->insnsi + delta;
  3043. for (i = 0; i < insn_cnt; i++, insn++) {
  3044. if (insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  3045. insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
  3046. type = BPF_READ;
  3047. else if (insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  3048. insn->code == (BPF_STX | BPF_MEM | BPF_DW))
  3049. type = BPF_WRITE;
  3050. else
  3051. continue;
  3052. if (type == BPF_WRITE &&
  3053. env->insn_aux_data[i + delta].sanitize_stack_off) {
  3054. struct bpf_insn patch[] = {
  3055. /* Sanitize suspicious stack slot with zero.
  3056. * There are no memory dependencies for this store,
  3057. * since it's only using frame pointer and immediate
  3058. * constant of zero
  3059. */
  3060. BPF_ST_MEM(BPF_DW, BPF_REG_FP,
  3061. env->insn_aux_data[i + delta].sanitize_stack_off,
  3062. 0),
  3063. /* the original STX instruction will immediately
  3064. * overwrite the same stack slot with appropriate value
  3065. */
  3066. *insn,
  3067. };
  3068. cnt = ARRAY_SIZE(patch);
  3069. new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
  3070. if (!new_prog)
  3071. return -ENOMEM;
  3072. delta += cnt - 1;
  3073. env->prog = new_prog;
  3074. insn = new_prog->insnsi + i + delta;
  3075. continue;
  3076. }
  3077. if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
  3078. continue;
  3079. cnt = ops->convert_ctx_access(type, insn->dst_reg, insn->src_reg,
  3080. insn->off, insn_buf, env->prog);
  3081. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  3082. verbose("bpf verifier is misconfigured\n");
  3083. return -EINVAL;
  3084. }
  3085. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  3086. if (!new_prog)
  3087. return -ENOMEM;
  3088. delta += cnt - 1;
  3089. /* keep walking new program and skip insns we just inserted */
  3090. env->prog = new_prog;
  3091. insn = new_prog->insnsi + i + delta;
  3092. }
  3093. return 0;
  3094. }
  3095. /* fixup insn->imm field of bpf_call instructions
  3096. *
  3097. * this function is called after eBPF program passed verification
  3098. */
  3099. static int fixup_bpf_calls(struct bpf_verifier_env *env)
  3100. {
  3101. struct bpf_prog *prog = env->prog;
  3102. struct bpf_insn *insn = prog->insnsi;
  3103. const struct bpf_func_proto *fn;
  3104. const int insn_cnt = prog->len;
  3105. struct bpf_insn insn_buf[16];
  3106. struct bpf_prog *new_prog;
  3107. struct bpf_map *map_ptr;
  3108. int i, cnt, delta = 0;
  3109. for (i = 0; i < insn_cnt; i++, insn++) {
  3110. if (insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
  3111. insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
  3112. /* due to JIT bugs clear upper 32-bits of src register
  3113. * before div/mod operation
  3114. */
  3115. insn_buf[0] = BPF_MOV32_REG(insn->src_reg, insn->src_reg);
  3116. insn_buf[1] = *insn;
  3117. cnt = 2;
  3118. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  3119. if (!new_prog)
  3120. return -ENOMEM;
  3121. delta += cnt - 1;
  3122. env->prog = prog = new_prog;
  3123. insn = new_prog->insnsi + i + delta;
  3124. continue;
  3125. }
  3126. if (insn->code != (BPF_JMP | BPF_CALL))
  3127. continue;
  3128. if (insn->imm == BPF_FUNC_get_route_realm)
  3129. prog->dst_needed = 1;
  3130. if (insn->imm == BPF_FUNC_get_prandom_u32)
  3131. bpf_user_rnd_init_once();
  3132. if (insn->imm == BPF_FUNC_tail_call) {
  3133. /* mark bpf_tail_call as different opcode to avoid
  3134. * conditional branch in the interpeter for every normal
  3135. * call and to prevent accidental JITing by JIT compiler
  3136. * that doesn't support bpf_tail_call yet
  3137. */
  3138. insn->imm = 0;
  3139. insn->code |= BPF_X;
  3140. /* instead of changing every JIT dealing with tail_call
  3141. * emit two extra insns:
  3142. * if (index >= max_entries) goto out;
  3143. * index &= array->index_mask;
  3144. * to avoid out-of-bounds cpu speculation
  3145. */
  3146. map_ptr = env->insn_aux_data[i + delta].map_ptr;
  3147. if (!map_ptr->unpriv_array)
  3148. continue;
  3149. insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
  3150. map_ptr->max_entries, 2);
  3151. insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
  3152. container_of(map_ptr,
  3153. struct bpf_array,
  3154. map)->index_mask);
  3155. insn_buf[2] = *insn;
  3156. cnt = 3;
  3157. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  3158. if (!new_prog)
  3159. return -ENOMEM;
  3160. delta += cnt - 1;
  3161. env->prog = prog = new_prog;
  3162. insn = new_prog->insnsi + i + delta;
  3163. continue;
  3164. }
  3165. fn = prog->aux->ops->get_func_proto(insn->imm);
  3166. /* all functions that have prototype and verifier allowed
  3167. * programs to call them, must be real in-kernel functions
  3168. */
  3169. if (!fn->func) {
  3170. verbose("kernel subsystem misconfigured func %d\n",
  3171. insn->imm);
  3172. return -EFAULT;
  3173. }
  3174. insn->imm = fn->func - __bpf_call_base;
  3175. }
  3176. return 0;
  3177. }
  3178. static void free_states(struct bpf_verifier_env *env)
  3179. {
  3180. struct bpf_verifier_state_list *sl, *sln;
  3181. int i;
  3182. if (!env->explored_states)
  3183. return;
  3184. for (i = 0; i < env->prog->len; i++) {
  3185. sl = env->explored_states[i];
  3186. if (sl)
  3187. while (sl != STATE_LIST_MARK) {
  3188. sln = sl->next;
  3189. kfree(sl);
  3190. sl = sln;
  3191. }
  3192. }
  3193. kfree(env->explored_states);
  3194. }
  3195. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  3196. {
  3197. char __user *log_ubuf = NULL;
  3198. struct bpf_verifier_env *env;
  3199. int ret = -EINVAL;
  3200. if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
  3201. return -E2BIG;
  3202. /* 'struct bpf_verifier_env' can be global, but since it's not small,
  3203. * allocate/free it every time bpf_check() is called
  3204. */
  3205. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  3206. if (!env)
  3207. return -ENOMEM;
  3208. env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
  3209. (*prog)->len);
  3210. ret = -ENOMEM;
  3211. if (!env->insn_aux_data)
  3212. goto err_free_env;
  3213. env->prog = *prog;
  3214. /* grab the mutex to protect few globals used by verifier */
  3215. mutex_lock(&bpf_verifier_lock);
  3216. if (attr->log_level || attr->log_buf || attr->log_size) {
  3217. /* user requested verbose verifier output
  3218. * and supplied buffer to store the verification trace
  3219. */
  3220. log_level = attr->log_level;
  3221. log_ubuf = (char __user *) (unsigned long) attr->log_buf;
  3222. log_size = attr->log_size;
  3223. log_len = 0;
  3224. ret = -EINVAL;
  3225. /* log_* values have to be sane */
  3226. if (log_size < 128 || log_size > UINT_MAX >> 8 ||
  3227. log_level == 0 || log_ubuf == NULL)
  3228. goto err_unlock;
  3229. ret = -ENOMEM;
  3230. log_buf = vmalloc(log_size);
  3231. if (!log_buf)
  3232. goto err_unlock;
  3233. } else {
  3234. log_level = 0;
  3235. }
  3236. ret = replace_map_fd_with_map_ptr(env);
  3237. if (ret < 0)
  3238. goto skip_full_check;
  3239. env->explored_states = kcalloc(env->prog->len,
  3240. sizeof(struct bpf_verifier_state_list *),
  3241. GFP_USER);
  3242. ret = -ENOMEM;
  3243. if (!env->explored_states)
  3244. goto skip_full_check;
  3245. ret = check_cfg(env);
  3246. if (ret < 0)
  3247. goto skip_full_check;
  3248. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  3249. ret = do_check(env);
  3250. skip_full_check:
  3251. while (pop_stack(env, NULL) >= 0);
  3252. free_states(env);
  3253. if (ret == 0)
  3254. sanitize_dead_code(env);
  3255. if (ret == 0)
  3256. /* program is valid, convert *(u32*)(ctx + off) accesses */
  3257. ret = convert_ctx_accesses(env);
  3258. if (ret == 0)
  3259. ret = fixup_bpf_calls(env);
  3260. if (log_level && log_len >= log_size - 1) {
  3261. BUG_ON(log_len >= log_size);
  3262. /* verifier log exceeded user supplied buffer */
  3263. ret = -ENOSPC;
  3264. /* fall through to return what was recorded */
  3265. }
  3266. /* copy verifier log back to user space including trailing zero */
  3267. if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
  3268. ret = -EFAULT;
  3269. goto free_log_buf;
  3270. }
  3271. if (ret == 0 && env->used_map_cnt) {
  3272. /* if program passed verifier, update used_maps in bpf_prog_info */
  3273. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  3274. sizeof(env->used_maps[0]),
  3275. GFP_KERNEL);
  3276. if (!env->prog->aux->used_maps) {
  3277. ret = -ENOMEM;
  3278. goto free_log_buf;
  3279. }
  3280. memcpy(env->prog->aux->used_maps, env->used_maps,
  3281. sizeof(env->used_maps[0]) * env->used_map_cnt);
  3282. env->prog->aux->used_map_cnt = env->used_map_cnt;
  3283. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  3284. * bpf_ld_imm64 instructions
  3285. */
  3286. convert_pseudo_ld_imm64(env);
  3287. }
  3288. free_log_buf:
  3289. if (log_level)
  3290. vfree(log_buf);
  3291. if (!env->prog->aux->used_maps)
  3292. /* if we didn't copy map pointers into bpf_prog_info, release
  3293. * them now. Otherwise free_used_maps() will release them.
  3294. */
  3295. release_maps(env);
  3296. *prog = env->prog;
  3297. err_unlock:
  3298. mutex_unlock(&bpf_verifier_lock);
  3299. vfree(env->insn_aux_data);
  3300. err_free_env:
  3301. kfree(env);
  3302. return ret;
  3303. }
  3304. int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
  3305. void *priv)
  3306. {
  3307. struct bpf_verifier_env *env;
  3308. int ret;
  3309. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  3310. if (!env)
  3311. return -ENOMEM;
  3312. env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
  3313. prog->len);
  3314. ret = -ENOMEM;
  3315. if (!env->insn_aux_data)
  3316. goto err_free_env;
  3317. env->prog = prog;
  3318. env->analyzer_ops = ops;
  3319. env->analyzer_priv = priv;
  3320. /* grab the mutex to protect few globals used by verifier */
  3321. mutex_lock(&bpf_verifier_lock);
  3322. log_level = 0;
  3323. env->explored_states = kcalloc(env->prog->len,
  3324. sizeof(struct bpf_verifier_state_list *),
  3325. GFP_KERNEL);
  3326. ret = -ENOMEM;
  3327. if (!env->explored_states)
  3328. goto skip_full_check;
  3329. ret = check_cfg(env);
  3330. if (ret < 0)
  3331. goto skip_full_check;
  3332. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  3333. ret = do_check(env);
  3334. skip_full_check:
  3335. while (pop_stack(env, NULL) >= 0);
  3336. free_states(env);
  3337. mutex_unlock(&bpf_verifier_lock);
  3338. vfree(env->insn_aux_data);
  3339. err_free_env:
  3340. kfree(env);
  3341. return ret;
  3342. }
  3343. EXPORT_SYMBOL_GPL(bpf_analyzer);