verifier.c 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409
  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. #include <linux/stringify.h>
  23. /* bpf_check() is a static code analyzer that walks eBPF program
  24. * instruction by instruction and updates register/stack state.
  25. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  26. *
  27. * The first pass is depth-first-search to check that the program is a DAG.
  28. * It rejects the following programs:
  29. * - larger than BPF_MAXINSNS insns
  30. * - if loop is present (detected via back-edge)
  31. * - unreachable insns exist (shouldn't be a forest. program = one function)
  32. * - out of bounds or malformed jumps
  33. * The second pass is all possible path descent from the 1st insn.
  34. * Since it's analyzing all pathes through the program, the length of the
  35. * analysis is limited to 64k insn, which may be hit even if total number of
  36. * insn is less then 4K, but there are too many branches that change stack/regs.
  37. * Number of 'branches to be analyzed' is limited to 1k
  38. *
  39. * On entry to each instruction, each register has a type, and the instruction
  40. * changes the types of the registers depending on instruction semantics.
  41. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  42. * copied to R1.
  43. *
  44. * All registers are 64-bit.
  45. * R0 - return register
  46. * R1-R5 argument passing registers
  47. * R6-R9 callee saved registers
  48. * R10 - frame pointer read-only
  49. *
  50. * At the start of BPF program the register R1 contains a pointer to bpf_context
  51. * and has type PTR_TO_CTX.
  52. *
  53. * Verifier tracks arithmetic operations on pointers in case:
  54. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  55. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  56. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  57. * and 2nd arithmetic instruction is pattern matched to recognize
  58. * that it wants to construct a pointer to some element within stack.
  59. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  60. * (and -20 constant is saved for further stack bounds checking).
  61. * Meaning that this reg is a pointer to stack plus known immediate constant.
  62. *
  63. * Most of the time the registers have SCALAR_VALUE type, which
  64. * means the register has some value, but it's not a valid pointer.
  65. * (like pointer plus pointer becomes SCALAR_VALUE type)
  66. *
  67. * When verifier sees load or store instructions the type of base register
  68. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
  69. * types recognized by check_mem_access() function.
  70. *
  71. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  72. * and the range of [ptr, ptr + map's value_size) is accessible.
  73. *
  74. * registers used to pass values to function calls are checked against
  75. * function argument constraints.
  76. *
  77. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  78. * It means that the register type passed to this function must be
  79. * PTR_TO_STACK and it will be used inside the function as
  80. * 'pointer to map element key'
  81. *
  82. * For example the argument constraints for bpf_map_lookup_elem():
  83. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  84. * .arg1_type = ARG_CONST_MAP_PTR,
  85. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  86. *
  87. * ret_type says that this function returns 'pointer to map elem value or null'
  88. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  89. * 2nd argument should be a pointer to stack, which will be used inside
  90. * the helper function as a pointer to map element key.
  91. *
  92. * On the kernel side the helper function looks like:
  93. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  94. * {
  95. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  96. * void *key = (void *) (unsigned long) r2;
  97. * void *value;
  98. *
  99. * here kernel can access 'key' and 'map' pointers safely, knowing that
  100. * [key, key + map->key_size) bytes are valid and were initialized on
  101. * the stack of eBPF program.
  102. * }
  103. *
  104. * Corresponding eBPF program may look like:
  105. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  106. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  107. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  108. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  109. * here verifier looks at prototype of map_lookup_elem() and sees:
  110. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  111. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  112. *
  113. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  114. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  115. * and were initialized prior to this call.
  116. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  117. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  118. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  119. * returns ether pointer to map value or NULL.
  120. *
  121. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  122. * insn, the register holding that pointer in the true branch changes state to
  123. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  124. * branch. See check_cond_jmp_op().
  125. *
  126. * After the call R0 is set to return type of the function and registers R1-R5
  127. * are set to NOT_INIT to indicate that they are no longer readable.
  128. */
  129. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  130. struct bpf_verifier_stack_elem {
  131. /* verifer state is 'st'
  132. * before processing instruction 'insn_idx'
  133. * and after processing instruction 'prev_insn_idx'
  134. */
  135. struct bpf_verifier_state st;
  136. int insn_idx;
  137. int prev_insn_idx;
  138. struct bpf_verifier_stack_elem *next;
  139. };
  140. #define BPF_COMPLEXITY_LIMIT_INSNS 131072
  141. #define BPF_COMPLEXITY_LIMIT_STACK 1024
  142. #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
  143. struct bpf_call_arg_meta {
  144. struct bpf_map *map_ptr;
  145. bool raw_mode;
  146. bool pkt_access;
  147. int regno;
  148. int access_size;
  149. };
  150. /* verbose verifier prints what it's seeing
  151. * bpf_check() is called under lock, so no race to access these global vars
  152. */
  153. static u32 log_level, log_size, log_len;
  154. static char *log_buf;
  155. static DEFINE_MUTEX(bpf_verifier_lock);
  156. /* log_level controls verbosity level of eBPF verifier.
  157. * verbose() is used to dump the verification trace to the log, so the user
  158. * can figure out what's wrong with the program
  159. */
  160. static __printf(1, 2) void verbose(const char *fmt, ...)
  161. {
  162. va_list args;
  163. if (log_level == 0 || log_len >= log_size - 1)
  164. return;
  165. va_start(args, fmt);
  166. log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
  167. va_end(args);
  168. }
  169. /* string representation of 'enum bpf_reg_type' */
  170. static const char * const reg_type_str[] = {
  171. [NOT_INIT] = "?",
  172. [SCALAR_VALUE] = "inv",
  173. [PTR_TO_CTX] = "ctx",
  174. [CONST_PTR_TO_MAP] = "map_ptr",
  175. [PTR_TO_MAP_VALUE] = "map_value",
  176. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  177. [PTR_TO_STACK] = "fp",
  178. [PTR_TO_PACKET] = "pkt",
  179. [PTR_TO_PACKET_END] = "pkt_end",
  180. };
  181. #define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
  182. static const char * const func_id_str[] = {
  183. __BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
  184. };
  185. #undef __BPF_FUNC_STR_FN
  186. static const char *func_id_name(int id)
  187. {
  188. BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID);
  189. if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id])
  190. return func_id_str[id];
  191. else
  192. return "unknown";
  193. }
  194. static void print_verifier_state(struct bpf_verifier_state *state)
  195. {
  196. struct bpf_reg_state *reg;
  197. enum bpf_reg_type t;
  198. int i;
  199. for (i = 0; i < MAX_BPF_REG; i++) {
  200. reg = &state->regs[i];
  201. t = reg->type;
  202. if (t == NOT_INIT)
  203. continue;
  204. verbose(" R%d=%s", i, reg_type_str[t]);
  205. if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
  206. tnum_is_const(reg->var_off)) {
  207. /* reg->off should be 0 for SCALAR_VALUE */
  208. verbose("%lld", reg->var_off.value + reg->off);
  209. } else {
  210. verbose("(id=%d", reg->id);
  211. if (t != SCALAR_VALUE)
  212. verbose(",off=%d", reg->off);
  213. if (t == PTR_TO_PACKET)
  214. verbose(",r=%d", reg->range);
  215. else if (t == CONST_PTR_TO_MAP ||
  216. t == PTR_TO_MAP_VALUE ||
  217. t == PTR_TO_MAP_VALUE_OR_NULL)
  218. verbose(",ks=%d,vs=%d",
  219. reg->map_ptr->key_size,
  220. reg->map_ptr->value_size);
  221. if (tnum_is_const(reg->var_off)) {
  222. /* Typically an immediate SCALAR_VALUE, but
  223. * could be a pointer whose offset is too big
  224. * for reg->off
  225. */
  226. verbose(",imm=%llx", reg->var_off.value);
  227. } else {
  228. if (reg->smin_value != reg->umin_value &&
  229. reg->smin_value != S64_MIN)
  230. verbose(",smin_value=%lld",
  231. (long long)reg->smin_value);
  232. if (reg->smax_value != reg->umax_value &&
  233. reg->smax_value != S64_MAX)
  234. verbose(",smax_value=%lld",
  235. (long long)reg->smax_value);
  236. if (reg->umin_value != 0)
  237. verbose(",umin_value=%llu",
  238. (unsigned long long)reg->umin_value);
  239. if (reg->umax_value != U64_MAX)
  240. verbose(",umax_value=%llu",
  241. (unsigned long long)reg->umax_value);
  242. if (!tnum_is_unknown(reg->var_off)) {
  243. char tn_buf[48];
  244. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  245. verbose(",var_off=%s", tn_buf);
  246. }
  247. }
  248. verbose(")");
  249. }
  250. }
  251. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  252. if (state->stack_slot_type[i] == STACK_SPILL)
  253. verbose(" fp%d=%s", -MAX_BPF_STACK + i,
  254. reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
  255. }
  256. verbose("\n");
  257. }
  258. static const char *const bpf_class_string[] = {
  259. [BPF_LD] = "ld",
  260. [BPF_LDX] = "ldx",
  261. [BPF_ST] = "st",
  262. [BPF_STX] = "stx",
  263. [BPF_ALU] = "alu",
  264. [BPF_JMP] = "jmp",
  265. [BPF_RET] = "BUG",
  266. [BPF_ALU64] = "alu64",
  267. };
  268. static const char *const bpf_alu_string[16] = {
  269. [BPF_ADD >> 4] = "+=",
  270. [BPF_SUB >> 4] = "-=",
  271. [BPF_MUL >> 4] = "*=",
  272. [BPF_DIV >> 4] = "/=",
  273. [BPF_OR >> 4] = "|=",
  274. [BPF_AND >> 4] = "&=",
  275. [BPF_LSH >> 4] = "<<=",
  276. [BPF_RSH >> 4] = ">>=",
  277. [BPF_NEG >> 4] = "neg",
  278. [BPF_MOD >> 4] = "%=",
  279. [BPF_XOR >> 4] = "^=",
  280. [BPF_MOV >> 4] = "=",
  281. [BPF_ARSH >> 4] = "s>>=",
  282. [BPF_END >> 4] = "endian",
  283. };
  284. static const char *const bpf_ldst_string[] = {
  285. [BPF_W >> 3] = "u32",
  286. [BPF_H >> 3] = "u16",
  287. [BPF_B >> 3] = "u8",
  288. [BPF_DW >> 3] = "u64",
  289. };
  290. static const char *const bpf_jmp_string[16] = {
  291. [BPF_JA >> 4] = "jmp",
  292. [BPF_JEQ >> 4] = "==",
  293. [BPF_JGT >> 4] = ">",
  294. [BPF_JLT >> 4] = "<",
  295. [BPF_JGE >> 4] = ">=",
  296. [BPF_JLE >> 4] = "<=",
  297. [BPF_JSET >> 4] = "&",
  298. [BPF_JNE >> 4] = "!=",
  299. [BPF_JSGT >> 4] = "s>",
  300. [BPF_JSLT >> 4] = "s<",
  301. [BPF_JSGE >> 4] = "s>=",
  302. [BPF_JSLE >> 4] = "s<=",
  303. [BPF_CALL >> 4] = "call",
  304. [BPF_EXIT >> 4] = "exit",
  305. };
  306. static void print_bpf_insn(const struct bpf_verifier_env *env,
  307. const struct bpf_insn *insn)
  308. {
  309. u8 class = BPF_CLASS(insn->code);
  310. if (class == BPF_ALU || class == BPF_ALU64) {
  311. if (BPF_SRC(insn->code) == BPF_X)
  312. verbose("(%02x) %sr%d %s %sr%d\n",
  313. insn->code, class == BPF_ALU ? "(u32) " : "",
  314. insn->dst_reg,
  315. bpf_alu_string[BPF_OP(insn->code) >> 4],
  316. class == BPF_ALU ? "(u32) " : "",
  317. insn->src_reg);
  318. else
  319. verbose("(%02x) %sr%d %s %s%d\n",
  320. insn->code, class == BPF_ALU ? "(u32) " : "",
  321. insn->dst_reg,
  322. bpf_alu_string[BPF_OP(insn->code) >> 4],
  323. class == BPF_ALU ? "(u32) " : "",
  324. insn->imm);
  325. } else if (class == BPF_STX) {
  326. if (BPF_MODE(insn->code) == BPF_MEM)
  327. verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
  328. insn->code,
  329. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  330. insn->dst_reg,
  331. insn->off, insn->src_reg);
  332. else if (BPF_MODE(insn->code) == BPF_XADD)
  333. verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
  334. insn->code,
  335. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  336. insn->dst_reg, insn->off,
  337. insn->src_reg);
  338. else
  339. verbose("BUG_%02x\n", insn->code);
  340. } else if (class == BPF_ST) {
  341. if (BPF_MODE(insn->code) != BPF_MEM) {
  342. verbose("BUG_st_%02x\n", insn->code);
  343. return;
  344. }
  345. verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
  346. insn->code,
  347. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  348. insn->dst_reg,
  349. insn->off, insn->imm);
  350. } else if (class == BPF_LDX) {
  351. if (BPF_MODE(insn->code) != BPF_MEM) {
  352. verbose("BUG_ldx_%02x\n", insn->code);
  353. return;
  354. }
  355. verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
  356. insn->code, insn->dst_reg,
  357. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  358. insn->src_reg, insn->off);
  359. } else if (class == BPF_LD) {
  360. if (BPF_MODE(insn->code) == BPF_ABS) {
  361. verbose("(%02x) r0 = *(%s *)skb[%d]\n",
  362. insn->code,
  363. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  364. insn->imm);
  365. } else if (BPF_MODE(insn->code) == BPF_IND) {
  366. verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
  367. insn->code,
  368. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  369. insn->src_reg, insn->imm);
  370. } else if (BPF_MODE(insn->code) == BPF_IMM &&
  371. BPF_SIZE(insn->code) == BPF_DW) {
  372. /* At this point, we already made sure that the second
  373. * part of the ldimm64 insn is accessible.
  374. */
  375. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  376. bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
  377. if (map_ptr && !env->allow_ptr_leaks)
  378. imm = 0;
  379. verbose("(%02x) r%d = 0x%llx\n", insn->code,
  380. insn->dst_reg, (unsigned long long)imm);
  381. } else {
  382. verbose("BUG_ld_%02x\n", insn->code);
  383. return;
  384. }
  385. } else if (class == BPF_JMP) {
  386. u8 opcode = BPF_OP(insn->code);
  387. if (opcode == BPF_CALL) {
  388. verbose("(%02x) call %s#%d\n", insn->code,
  389. func_id_name(insn->imm), insn->imm);
  390. } else if (insn->code == (BPF_JMP | BPF_JA)) {
  391. verbose("(%02x) goto pc%+d\n",
  392. insn->code, insn->off);
  393. } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
  394. verbose("(%02x) exit\n", insn->code);
  395. } else if (BPF_SRC(insn->code) == BPF_X) {
  396. verbose("(%02x) if r%d %s r%d goto pc%+d\n",
  397. insn->code, insn->dst_reg,
  398. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  399. insn->src_reg, insn->off);
  400. } else {
  401. verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
  402. insn->code, insn->dst_reg,
  403. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  404. insn->imm, insn->off);
  405. }
  406. } else {
  407. verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
  408. }
  409. }
  410. static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
  411. {
  412. struct bpf_verifier_stack_elem *elem;
  413. int insn_idx;
  414. if (env->head == NULL)
  415. return -1;
  416. memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
  417. insn_idx = env->head->insn_idx;
  418. if (prev_insn_idx)
  419. *prev_insn_idx = env->head->prev_insn_idx;
  420. elem = env->head->next;
  421. kfree(env->head);
  422. env->head = elem;
  423. env->stack_size--;
  424. return insn_idx;
  425. }
  426. static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
  427. int insn_idx, int prev_insn_idx)
  428. {
  429. struct bpf_verifier_stack_elem *elem;
  430. elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
  431. if (!elem)
  432. goto err;
  433. memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
  434. elem->insn_idx = insn_idx;
  435. elem->prev_insn_idx = prev_insn_idx;
  436. elem->next = env->head;
  437. env->head = elem;
  438. env->stack_size++;
  439. if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
  440. verbose("BPF program is too complex\n");
  441. goto err;
  442. }
  443. return &elem->st;
  444. err:
  445. /* pop all elements and return */
  446. while (pop_stack(env, NULL) >= 0);
  447. return NULL;
  448. }
  449. #define CALLER_SAVED_REGS 6
  450. static const int caller_saved[CALLER_SAVED_REGS] = {
  451. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  452. };
  453. static void __mark_reg_not_init(struct bpf_reg_state *reg);
  454. /* Mark the unknown part of a register (variable offset or scalar value) as
  455. * known to have the value @imm.
  456. */
  457. static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
  458. {
  459. reg->id = 0;
  460. reg->var_off = tnum_const(imm);
  461. reg->smin_value = (s64)imm;
  462. reg->smax_value = (s64)imm;
  463. reg->umin_value = imm;
  464. reg->umax_value = imm;
  465. }
  466. /* Mark the 'variable offset' part of a register as zero. This should be
  467. * used only on registers holding a pointer type.
  468. */
  469. static void __mark_reg_known_zero(struct bpf_reg_state *reg)
  470. {
  471. __mark_reg_known(reg, 0);
  472. }
  473. static void mark_reg_known_zero(struct bpf_reg_state *regs, u32 regno)
  474. {
  475. if (WARN_ON(regno >= MAX_BPF_REG)) {
  476. verbose("mark_reg_known_zero(regs, %u)\n", regno);
  477. /* Something bad happened, let's kill all regs */
  478. for (regno = 0; regno < MAX_BPF_REG; regno++)
  479. __mark_reg_not_init(regs + regno);
  480. return;
  481. }
  482. __mark_reg_known_zero(regs + regno);
  483. }
  484. /* Attempts to improve min/max values based on var_off information */
  485. static void __update_reg_bounds(struct bpf_reg_state *reg)
  486. {
  487. /* min signed is max(sign bit) | min(other bits) */
  488. reg->smin_value = max_t(s64, reg->smin_value,
  489. reg->var_off.value | (reg->var_off.mask & S64_MIN));
  490. /* max signed is min(sign bit) | max(other bits) */
  491. reg->smax_value = min_t(s64, reg->smax_value,
  492. reg->var_off.value | (reg->var_off.mask & S64_MAX));
  493. reg->umin_value = max(reg->umin_value, reg->var_off.value);
  494. reg->umax_value = min(reg->umax_value,
  495. reg->var_off.value | reg->var_off.mask);
  496. }
  497. /* Uses signed min/max values to inform unsigned, and vice-versa */
  498. static void __reg_deduce_bounds(struct bpf_reg_state *reg)
  499. {
  500. /* Learn sign from signed bounds.
  501. * If we cannot cross the sign boundary, then signed and unsigned bounds
  502. * are the same, so combine. This works even in the negative case, e.g.
  503. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
  504. */
  505. if (reg->smin_value >= 0 || reg->smax_value < 0) {
  506. reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
  507. reg->umin_value);
  508. reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
  509. reg->umax_value);
  510. return;
  511. }
  512. /* Learn sign from unsigned bounds. Signed bounds cross the sign
  513. * boundary, so we must be careful.
  514. */
  515. if ((s64)reg->umax_value >= 0) {
  516. /* Positive. We can't learn anything from the smin, but smax
  517. * is positive, hence safe.
  518. */
  519. reg->smin_value = reg->umin_value;
  520. reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
  521. reg->umax_value);
  522. } else if ((s64)reg->umin_value < 0) {
  523. /* Negative. We can't learn anything from the smax, but smin
  524. * is negative, hence safe.
  525. */
  526. reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
  527. reg->umin_value);
  528. reg->smax_value = reg->umax_value;
  529. }
  530. }
  531. /* Attempts to improve var_off based on unsigned min/max information */
  532. static void __reg_bound_offset(struct bpf_reg_state *reg)
  533. {
  534. reg->var_off = tnum_intersect(reg->var_off,
  535. tnum_range(reg->umin_value,
  536. reg->umax_value));
  537. }
  538. /* Reset the min/max bounds of a register */
  539. static void __mark_reg_unbounded(struct bpf_reg_state *reg)
  540. {
  541. reg->smin_value = S64_MIN;
  542. reg->smax_value = S64_MAX;
  543. reg->umin_value = 0;
  544. reg->umax_value = U64_MAX;
  545. }
  546. /* Mark a register as having a completely unknown (scalar) value. */
  547. static void __mark_reg_unknown(struct bpf_reg_state *reg)
  548. {
  549. reg->type = SCALAR_VALUE;
  550. reg->id = 0;
  551. reg->off = 0;
  552. reg->var_off = tnum_unknown;
  553. __mark_reg_unbounded(reg);
  554. }
  555. static void mark_reg_unknown(struct bpf_reg_state *regs, u32 regno)
  556. {
  557. if (WARN_ON(regno >= MAX_BPF_REG)) {
  558. verbose("mark_reg_unknown(regs, %u)\n", regno);
  559. /* Something bad happened, let's kill all regs */
  560. for (regno = 0; regno < MAX_BPF_REG; regno++)
  561. __mark_reg_not_init(regs + regno);
  562. return;
  563. }
  564. __mark_reg_unknown(regs + regno);
  565. }
  566. static void __mark_reg_not_init(struct bpf_reg_state *reg)
  567. {
  568. __mark_reg_unknown(reg);
  569. reg->type = NOT_INIT;
  570. }
  571. static void mark_reg_not_init(struct bpf_reg_state *regs, u32 regno)
  572. {
  573. if (WARN_ON(regno >= MAX_BPF_REG)) {
  574. verbose("mark_reg_not_init(regs, %u)\n", regno);
  575. /* Something bad happened, let's kill all regs */
  576. for (regno = 0; regno < MAX_BPF_REG; regno++)
  577. __mark_reg_not_init(regs + regno);
  578. return;
  579. }
  580. __mark_reg_not_init(regs + regno);
  581. }
  582. static void init_reg_state(struct bpf_reg_state *regs)
  583. {
  584. int i;
  585. for (i = 0; i < MAX_BPF_REG; i++) {
  586. mark_reg_not_init(regs, i);
  587. regs[i].live = REG_LIVE_NONE;
  588. }
  589. /* frame pointer */
  590. regs[BPF_REG_FP].type = PTR_TO_STACK;
  591. mark_reg_known_zero(regs, BPF_REG_FP);
  592. /* 1st arg to a function */
  593. regs[BPF_REG_1].type = PTR_TO_CTX;
  594. mark_reg_known_zero(regs, BPF_REG_1);
  595. }
  596. enum reg_arg_type {
  597. SRC_OP, /* register is used as source operand */
  598. DST_OP, /* register is used as destination operand */
  599. DST_OP_NO_MARK /* same as above, check only, don't mark */
  600. };
  601. static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno)
  602. {
  603. struct bpf_verifier_state *parent = state->parent;
  604. while (parent) {
  605. /* if read wasn't screened by an earlier write ... */
  606. if (state->regs[regno].live & REG_LIVE_WRITTEN)
  607. break;
  608. /* ... then we depend on parent's value */
  609. parent->regs[regno].live |= REG_LIVE_READ;
  610. state = parent;
  611. parent = state->parent;
  612. }
  613. }
  614. static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
  615. enum reg_arg_type t)
  616. {
  617. struct bpf_reg_state *regs = env->cur_state.regs;
  618. if (regno >= MAX_BPF_REG) {
  619. verbose("R%d is invalid\n", regno);
  620. return -EINVAL;
  621. }
  622. if (t == SRC_OP) {
  623. /* check whether register used as source operand can be read */
  624. if (regs[regno].type == NOT_INIT) {
  625. verbose("R%d !read_ok\n", regno);
  626. return -EACCES;
  627. }
  628. mark_reg_read(&env->cur_state, regno);
  629. } else {
  630. /* check whether register used as dest operand can be written to */
  631. if (regno == BPF_REG_FP) {
  632. verbose("frame pointer is read only\n");
  633. return -EACCES;
  634. }
  635. regs[regno].live |= REG_LIVE_WRITTEN;
  636. if (t == DST_OP)
  637. mark_reg_unknown(regs, regno);
  638. }
  639. return 0;
  640. }
  641. static bool is_spillable_regtype(enum bpf_reg_type type)
  642. {
  643. switch (type) {
  644. case PTR_TO_MAP_VALUE:
  645. case PTR_TO_MAP_VALUE_OR_NULL:
  646. case PTR_TO_STACK:
  647. case PTR_TO_CTX:
  648. case PTR_TO_PACKET:
  649. case PTR_TO_PACKET_END:
  650. case CONST_PTR_TO_MAP:
  651. return true;
  652. default:
  653. return false;
  654. }
  655. }
  656. /* check_stack_read/write functions track spill/fill of registers,
  657. * stack boundary and alignment are checked in check_mem_access()
  658. */
  659. static int check_stack_write(struct bpf_verifier_state *state, int off,
  660. int size, int value_regno)
  661. {
  662. int i, spi = (MAX_BPF_STACK + off) / BPF_REG_SIZE;
  663. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  664. * so it's aligned access and [off, off + size) are within stack limits
  665. */
  666. if (value_regno >= 0 &&
  667. is_spillable_regtype(state->regs[value_regno].type)) {
  668. /* register containing pointer is being spilled into stack */
  669. if (size != BPF_REG_SIZE) {
  670. verbose("invalid size of register spill\n");
  671. return -EACCES;
  672. }
  673. /* save register state */
  674. state->spilled_regs[spi] = state->regs[value_regno];
  675. state->spilled_regs[spi].live |= REG_LIVE_WRITTEN;
  676. for (i = 0; i < BPF_REG_SIZE; i++)
  677. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
  678. } else {
  679. /* regular write of data into stack */
  680. state->spilled_regs[spi] = (struct bpf_reg_state) {};
  681. for (i = 0; i < size; i++)
  682. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
  683. }
  684. return 0;
  685. }
  686. static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
  687. {
  688. struct bpf_verifier_state *parent = state->parent;
  689. while (parent) {
  690. /* if read wasn't screened by an earlier write ... */
  691. if (state->spilled_regs[slot].live & REG_LIVE_WRITTEN)
  692. break;
  693. /* ... then we depend on parent's value */
  694. parent->spilled_regs[slot].live |= REG_LIVE_READ;
  695. state = parent;
  696. parent = state->parent;
  697. }
  698. }
  699. static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
  700. int value_regno)
  701. {
  702. u8 *slot_type;
  703. int i, spi;
  704. slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
  705. if (slot_type[0] == STACK_SPILL) {
  706. if (size != BPF_REG_SIZE) {
  707. verbose("invalid size of register spill\n");
  708. return -EACCES;
  709. }
  710. for (i = 1; i < BPF_REG_SIZE; i++) {
  711. if (slot_type[i] != STACK_SPILL) {
  712. verbose("corrupted spill memory\n");
  713. return -EACCES;
  714. }
  715. }
  716. spi = (MAX_BPF_STACK + off) / BPF_REG_SIZE;
  717. if (value_regno >= 0) {
  718. /* restore register state from stack */
  719. state->regs[value_regno] = state->spilled_regs[spi];
  720. mark_stack_slot_read(state, spi);
  721. }
  722. return 0;
  723. } else {
  724. for (i = 0; i < size; i++) {
  725. if (slot_type[i] != STACK_MISC) {
  726. verbose("invalid read from stack off %d+%d size %d\n",
  727. off, i, size);
  728. return -EACCES;
  729. }
  730. }
  731. if (value_regno >= 0)
  732. /* have read misc data from the stack */
  733. mark_reg_unknown(state->regs, value_regno);
  734. return 0;
  735. }
  736. }
  737. /* check read/write into map element returned by bpf_map_lookup_elem() */
  738. static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
  739. int size)
  740. {
  741. struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
  742. if (off < 0 || size <= 0 || off + size > map->value_size) {
  743. verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
  744. map->value_size, off, size);
  745. return -EACCES;
  746. }
  747. return 0;
  748. }
  749. /* check read/write into a map element with possible variable offset */
  750. static int check_map_access(struct bpf_verifier_env *env, u32 regno,
  751. int off, int size)
  752. {
  753. struct bpf_verifier_state *state = &env->cur_state;
  754. struct bpf_reg_state *reg = &state->regs[regno];
  755. int err;
  756. /* We may have adjusted the register to this map value, so we
  757. * need to try adding each of min_value and max_value to off
  758. * to make sure our theoretical access will be safe.
  759. */
  760. if (log_level)
  761. print_verifier_state(state);
  762. /* If the offset is variable, we will need to be stricter in state
  763. * pruning from now on.
  764. */
  765. if (!tnum_is_const(reg->var_off))
  766. env->varlen_map_value_access = true;
  767. /* The minimum value is only important with signed
  768. * comparisons where we can't assume the floor of a
  769. * value is 0. If we are using signed variables for our
  770. * index'es we need to make sure that whatever we use
  771. * will have a set floor within our range.
  772. */
  773. if (reg->smin_value < 0) {
  774. verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  775. regno);
  776. return -EACCES;
  777. }
  778. err = __check_map_access(env, regno, reg->smin_value + off, size);
  779. if (err) {
  780. verbose("R%d min value is outside of the array range\n", regno);
  781. return err;
  782. }
  783. /* If we haven't set a max value then we need to bail since we can't be
  784. * sure we won't do bad things.
  785. * If reg->umax_value + off could overflow, treat that as unbounded too.
  786. */
  787. if (reg->umax_value >= BPF_MAX_VAR_OFF) {
  788. verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
  789. regno);
  790. return -EACCES;
  791. }
  792. err = __check_map_access(env, regno, reg->umax_value + off, size);
  793. if (err)
  794. verbose("R%d max value is outside of the array range\n", regno);
  795. return err;
  796. }
  797. #define MAX_PACKET_OFF 0xffff
  798. static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
  799. const struct bpf_call_arg_meta *meta,
  800. enum bpf_access_type t)
  801. {
  802. switch (env->prog->type) {
  803. case BPF_PROG_TYPE_LWT_IN:
  804. case BPF_PROG_TYPE_LWT_OUT:
  805. /* dst_input() and dst_output() can't write for now */
  806. if (t == BPF_WRITE)
  807. return false;
  808. /* fallthrough */
  809. case BPF_PROG_TYPE_SCHED_CLS:
  810. case BPF_PROG_TYPE_SCHED_ACT:
  811. case BPF_PROG_TYPE_XDP:
  812. case BPF_PROG_TYPE_LWT_XMIT:
  813. case BPF_PROG_TYPE_SK_SKB:
  814. if (meta)
  815. return meta->pkt_access;
  816. env->seen_direct_write = true;
  817. return true;
  818. default:
  819. return false;
  820. }
  821. }
  822. static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
  823. int off, int size)
  824. {
  825. struct bpf_reg_state *regs = env->cur_state.regs;
  826. struct bpf_reg_state *reg = &regs[regno];
  827. if (off < 0 || size <= 0 || (u64)off + size > reg->range) {
  828. verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
  829. off, size, regno, reg->id, reg->off, reg->range);
  830. return -EACCES;
  831. }
  832. return 0;
  833. }
  834. static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
  835. int size)
  836. {
  837. struct bpf_reg_state *regs = env->cur_state.regs;
  838. struct bpf_reg_state *reg = &regs[regno];
  839. int err;
  840. /* We may have added a variable offset to the packet pointer; but any
  841. * reg->range we have comes after that. We are only checking the fixed
  842. * offset.
  843. */
  844. /* We don't allow negative numbers, because we aren't tracking enough
  845. * detail to prove they're safe.
  846. */
  847. if (reg->smin_value < 0) {
  848. verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  849. regno);
  850. return -EACCES;
  851. }
  852. err = __check_packet_access(env, regno, off, size);
  853. if (err) {
  854. verbose("R%d offset is outside of the packet\n", regno);
  855. return err;
  856. }
  857. return err;
  858. }
  859. /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
  860. static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
  861. enum bpf_access_type t, enum bpf_reg_type *reg_type)
  862. {
  863. struct bpf_insn_access_aux info = {
  864. .reg_type = *reg_type,
  865. };
  866. /* for analyzer ctx accesses are already validated and converted */
  867. if (env->analyzer_ops)
  868. return 0;
  869. if (env->prog->aux->ops->is_valid_access &&
  870. env->prog->aux->ops->is_valid_access(off, size, t, &info)) {
  871. /* A non zero info.ctx_field_size indicates that this field is a
  872. * candidate for later verifier transformation to load the whole
  873. * field and then apply a mask when accessed with a narrower
  874. * access than actual ctx access size. A zero info.ctx_field_size
  875. * will only allow for whole field access and rejects any other
  876. * type of narrower access.
  877. */
  878. env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
  879. *reg_type = info.reg_type;
  880. /* remember the offset of last byte accessed in ctx */
  881. if (env->prog->aux->max_ctx_offset < off + size)
  882. env->prog->aux->max_ctx_offset = off + size;
  883. return 0;
  884. }
  885. verbose("invalid bpf_context access off=%d size=%d\n", off, size);
  886. return -EACCES;
  887. }
  888. static bool __is_pointer_value(bool allow_ptr_leaks,
  889. const struct bpf_reg_state *reg)
  890. {
  891. if (allow_ptr_leaks)
  892. return false;
  893. return reg->type != SCALAR_VALUE;
  894. }
  895. static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
  896. {
  897. return __is_pointer_value(env->allow_ptr_leaks, &env->cur_state.regs[regno]);
  898. }
  899. static int check_pkt_ptr_alignment(const struct bpf_reg_state *reg,
  900. int off, int size, bool strict)
  901. {
  902. struct tnum reg_off;
  903. int ip_align;
  904. /* Byte size accesses are always allowed. */
  905. if (!strict || size == 1)
  906. return 0;
  907. /* For platforms that do not have a Kconfig enabling
  908. * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
  909. * NET_IP_ALIGN is universally set to '2'. And on platforms
  910. * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
  911. * to this code only in strict mode where we want to emulate
  912. * the NET_IP_ALIGN==2 checking. Therefore use an
  913. * unconditional IP align value of '2'.
  914. */
  915. ip_align = 2;
  916. reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
  917. if (!tnum_is_aligned(reg_off, size)) {
  918. char tn_buf[48];
  919. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  920. verbose("misaligned packet access off %d+%s+%d+%d size %d\n",
  921. ip_align, tn_buf, reg->off, off, size);
  922. return -EACCES;
  923. }
  924. return 0;
  925. }
  926. static int check_generic_ptr_alignment(const struct bpf_reg_state *reg,
  927. const char *pointer_desc,
  928. int off, int size, bool strict)
  929. {
  930. struct tnum reg_off;
  931. /* Byte size accesses are always allowed. */
  932. if (!strict || size == 1)
  933. return 0;
  934. reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
  935. if (!tnum_is_aligned(reg_off, size)) {
  936. char tn_buf[48];
  937. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  938. verbose("misaligned %saccess off %s+%d+%d size %d\n",
  939. pointer_desc, tn_buf, reg->off, off, size);
  940. return -EACCES;
  941. }
  942. return 0;
  943. }
  944. static int check_ptr_alignment(struct bpf_verifier_env *env,
  945. const struct bpf_reg_state *reg,
  946. int off, int size)
  947. {
  948. bool strict = env->strict_alignment;
  949. const char *pointer_desc = "";
  950. switch (reg->type) {
  951. case PTR_TO_PACKET:
  952. /* special case, because of NET_IP_ALIGN */
  953. return check_pkt_ptr_alignment(reg, off, size, strict);
  954. case PTR_TO_MAP_VALUE:
  955. pointer_desc = "value ";
  956. break;
  957. case PTR_TO_CTX:
  958. pointer_desc = "context ";
  959. break;
  960. case PTR_TO_STACK:
  961. pointer_desc = "stack ";
  962. break;
  963. default:
  964. break;
  965. }
  966. return check_generic_ptr_alignment(reg, pointer_desc, off, size, strict);
  967. }
  968. /* check whether memory at (regno + off) is accessible for t = (read | write)
  969. * if t==write, value_regno is a register which value is stored into memory
  970. * if t==read, value_regno is a register which will receive the value from memory
  971. * if t==write && value_regno==-1, some unknown value is stored into memory
  972. * if t==read && value_regno==-1, don't care what we read from memory
  973. */
  974. static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
  975. int bpf_size, enum bpf_access_type t,
  976. int value_regno)
  977. {
  978. struct bpf_verifier_state *state = &env->cur_state;
  979. struct bpf_reg_state *reg = &state->regs[regno];
  980. int size, err = 0;
  981. size = bpf_size_to_bytes(bpf_size);
  982. if (size < 0)
  983. return size;
  984. /* alignment checks will add in reg->off themselves */
  985. err = check_ptr_alignment(env, reg, off, size);
  986. if (err)
  987. return err;
  988. /* for access checks, reg->off is just part of off */
  989. off += reg->off;
  990. if (reg->type == PTR_TO_MAP_VALUE) {
  991. if (t == BPF_WRITE && value_regno >= 0 &&
  992. is_pointer_value(env, value_regno)) {
  993. verbose("R%d leaks addr into map\n", value_regno);
  994. return -EACCES;
  995. }
  996. err = check_map_access(env, regno, off, size);
  997. if (!err && t == BPF_READ && value_regno >= 0)
  998. mark_reg_unknown(state->regs, value_regno);
  999. } else if (reg->type == PTR_TO_CTX) {
  1000. enum bpf_reg_type reg_type = SCALAR_VALUE;
  1001. if (t == BPF_WRITE && value_regno >= 0 &&
  1002. is_pointer_value(env, value_regno)) {
  1003. verbose("R%d leaks addr into ctx\n", value_regno);
  1004. return -EACCES;
  1005. }
  1006. /* ctx accesses must be at a fixed offset, so that we can
  1007. * determine what type of data were returned.
  1008. */
  1009. if (!tnum_is_const(reg->var_off)) {
  1010. char tn_buf[48];
  1011. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1012. verbose("variable ctx access var_off=%s off=%d size=%d",
  1013. tn_buf, off, size);
  1014. return -EACCES;
  1015. }
  1016. off += reg->var_off.value;
  1017. err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
  1018. if (!err && t == BPF_READ && value_regno >= 0) {
  1019. /* ctx access returns either a scalar, or a
  1020. * PTR_TO_PACKET[_END]. In the latter case, we know
  1021. * the offset is zero.
  1022. */
  1023. if (reg_type == SCALAR_VALUE)
  1024. mark_reg_unknown(state->regs, value_regno);
  1025. else
  1026. mark_reg_known_zero(state->regs, value_regno);
  1027. state->regs[value_regno].id = 0;
  1028. state->regs[value_regno].off = 0;
  1029. state->regs[value_regno].range = 0;
  1030. state->regs[value_regno].type = reg_type;
  1031. }
  1032. } else if (reg->type == PTR_TO_STACK) {
  1033. /* stack accesses must be at a fixed offset, so that we can
  1034. * determine what type of data were returned.
  1035. * See check_stack_read().
  1036. */
  1037. if (!tnum_is_const(reg->var_off)) {
  1038. char tn_buf[48];
  1039. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1040. verbose("variable stack access var_off=%s off=%d size=%d",
  1041. tn_buf, off, size);
  1042. return -EACCES;
  1043. }
  1044. off += reg->var_off.value;
  1045. if (off >= 0 || off < -MAX_BPF_STACK) {
  1046. verbose("invalid stack off=%d size=%d\n", off, size);
  1047. return -EACCES;
  1048. }
  1049. if (env->prog->aux->stack_depth < -off)
  1050. env->prog->aux->stack_depth = -off;
  1051. if (t == BPF_WRITE) {
  1052. if (!env->allow_ptr_leaks &&
  1053. state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
  1054. size != BPF_REG_SIZE) {
  1055. verbose("attempt to corrupt spilled pointer on stack\n");
  1056. return -EACCES;
  1057. }
  1058. err = check_stack_write(state, off, size, value_regno);
  1059. } else {
  1060. err = check_stack_read(state, off, size, value_regno);
  1061. }
  1062. } else if (reg->type == PTR_TO_PACKET) {
  1063. if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
  1064. verbose("cannot write into packet\n");
  1065. return -EACCES;
  1066. }
  1067. if (t == BPF_WRITE && value_regno >= 0 &&
  1068. is_pointer_value(env, value_regno)) {
  1069. verbose("R%d leaks addr into packet\n", value_regno);
  1070. return -EACCES;
  1071. }
  1072. err = check_packet_access(env, regno, off, size);
  1073. if (!err && t == BPF_READ && value_regno >= 0)
  1074. mark_reg_unknown(state->regs, value_regno);
  1075. } else {
  1076. verbose("R%d invalid mem access '%s'\n",
  1077. regno, reg_type_str[reg->type]);
  1078. return -EACCES;
  1079. }
  1080. if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
  1081. state->regs[value_regno].type == SCALAR_VALUE) {
  1082. /* b/h/w load zero-extends, mark upper bits as known 0 */
  1083. state->regs[value_regno].var_off = tnum_cast(
  1084. state->regs[value_regno].var_off, size);
  1085. __update_reg_bounds(&state->regs[value_regno]);
  1086. }
  1087. return err;
  1088. }
  1089. static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
  1090. {
  1091. int err;
  1092. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  1093. insn->imm != 0) {
  1094. verbose("BPF_XADD uses reserved fields\n");
  1095. return -EINVAL;
  1096. }
  1097. /* check src1 operand */
  1098. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  1099. if (err)
  1100. return err;
  1101. /* check src2 operand */
  1102. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  1103. if (err)
  1104. return err;
  1105. if (is_pointer_value(env, insn->src_reg)) {
  1106. verbose("R%d leaks addr into mem\n", insn->src_reg);
  1107. return -EACCES;
  1108. }
  1109. /* check whether atomic_add can read the memory */
  1110. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  1111. BPF_SIZE(insn->code), BPF_READ, -1);
  1112. if (err)
  1113. return err;
  1114. /* check whether atomic_add can write into the same memory */
  1115. return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  1116. BPF_SIZE(insn->code), BPF_WRITE, -1);
  1117. }
  1118. /* Does this register contain a constant zero? */
  1119. static bool register_is_null(struct bpf_reg_state reg)
  1120. {
  1121. return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
  1122. }
  1123. /* when register 'regno' is passed into function that will read 'access_size'
  1124. * bytes from that pointer, make sure that it's within stack boundary
  1125. * and all elements of stack are initialized.
  1126. * Unlike most pointer bounds-checking functions, this one doesn't take an
  1127. * 'off' argument, so it has to add in reg->off itself.
  1128. */
  1129. static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
  1130. int access_size, bool zero_size_allowed,
  1131. struct bpf_call_arg_meta *meta)
  1132. {
  1133. struct bpf_verifier_state *state = &env->cur_state;
  1134. struct bpf_reg_state *regs = state->regs;
  1135. int off, i;
  1136. if (regs[regno].type != PTR_TO_STACK) {
  1137. /* Allow zero-byte read from NULL, regardless of pointer type */
  1138. if (zero_size_allowed && access_size == 0 &&
  1139. register_is_null(regs[regno]))
  1140. return 0;
  1141. verbose("R%d type=%s expected=%s\n", regno,
  1142. reg_type_str[regs[regno].type],
  1143. reg_type_str[PTR_TO_STACK]);
  1144. return -EACCES;
  1145. }
  1146. /* Only allow fixed-offset stack reads */
  1147. if (!tnum_is_const(regs[regno].var_off)) {
  1148. char tn_buf[48];
  1149. tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
  1150. verbose("invalid variable stack read R%d var_off=%s\n",
  1151. regno, tn_buf);
  1152. }
  1153. off = regs[regno].off + regs[regno].var_off.value;
  1154. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  1155. access_size <= 0) {
  1156. verbose("invalid stack type R%d off=%d access_size=%d\n",
  1157. regno, off, access_size);
  1158. return -EACCES;
  1159. }
  1160. if (env->prog->aux->stack_depth < -off)
  1161. env->prog->aux->stack_depth = -off;
  1162. if (meta && meta->raw_mode) {
  1163. meta->access_size = access_size;
  1164. meta->regno = regno;
  1165. return 0;
  1166. }
  1167. for (i = 0; i < access_size; i++) {
  1168. if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
  1169. verbose("invalid indirect read from stack off %d+%d size %d\n",
  1170. off, i, access_size);
  1171. return -EACCES;
  1172. }
  1173. }
  1174. return 0;
  1175. }
  1176. static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
  1177. int access_size, bool zero_size_allowed,
  1178. struct bpf_call_arg_meta *meta)
  1179. {
  1180. struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
  1181. switch (reg->type) {
  1182. case PTR_TO_PACKET:
  1183. return check_packet_access(env, regno, reg->off, access_size);
  1184. case PTR_TO_MAP_VALUE:
  1185. return check_map_access(env, regno, reg->off, access_size);
  1186. default: /* scalar_value|ptr_to_stack or invalid ptr */
  1187. return check_stack_boundary(env, regno, access_size,
  1188. zero_size_allowed, meta);
  1189. }
  1190. }
  1191. static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
  1192. enum bpf_arg_type arg_type,
  1193. struct bpf_call_arg_meta *meta)
  1194. {
  1195. struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
  1196. enum bpf_reg_type expected_type, type = reg->type;
  1197. int err = 0;
  1198. if (arg_type == ARG_DONTCARE)
  1199. return 0;
  1200. err = check_reg_arg(env, regno, SRC_OP);
  1201. if (err)
  1202. return err;
  1203. if (arg_type == ARG_ANYTHING) {
  1204. if (is_pointer_value(env, regno)) {
  1205. verbose("R%d leaks addr into helper function\n", regno);
  1206. return -EACCES;
  1207. }
  1208. return 0;
  1209. }
  1210. if (type == PTR_TO_PACKET &&
  1211. !may_access_direct_pkt_data(env, meta, BPF_READ)) {
  1212. verbose("helper access to the packet is not allowed\n");
  1213. return -EACCES;
  1214. }
  1215. if (arg_type == ARG_PTR_TO_MAP_KEY ||
  1216. arg_type == ARG_PTR_TO_MAP_VALUE) {
  1217. expected_type = PTR_TO_STACK;
  1218. if (type != PTR_TO_PACKET && type != expected_type)
  1219. goto err_type;
  1220. } else if (arg_type == ARG_CONST_SIZE ||
  1221. arg_type == ARG_CONST_SIZE_OR_ZERO) {
  1222. expected_type = SCALAR_VALUE;
  1223. if (type != expected_type)
  1224. goto err_type;
  1225. } else if (arg_type == ARG_CONST_MAP_PTR) {
  1226. expected_type = CONST_PTR_TO_MAP;
  1227. if (type != expected_type)
  1228. goto err_type;
  1229. } else if (arg_type == ARG_PTR_TO_CTX) {
  1230. expected_type = PTR_TO_CTX;
  1231. if (type != expected_type)
  1232. goto err_type;
  1233. } else if (arg_type == ARG_PTR_TO_MEM ||
  1234. arg_type == ARG_PTR_TO_UNINIT_MEM) {
  1235. expected_type = PTR_TO_STACK;
  1236. /* One exception here. In case function allows for NULL to be
  1237. * passed in as argument, it's a SCALAR_VALUE type. Final test
  1238. * happens during stack boundary checking.
  1239. */
  1240. if (register_is_null(*reg))
  1241. /* final test in check_stack_boundary() */;
  1242. else if (type != PTR_TO_PACKET && type != PTR_TO_MAP_VALUE &&
  1243. type != expected_type)
  1244. goto err_type;
  1245. meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
  1246. } else {
  1247. verbose("unsupported arg_type %d\n", arg_type);
  1248. return -EFAULT;
  1249. }
  1250. if (arg_type == ARG_CONST_MAP_PTR) {
  1251. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  1252. meta->map_ptr = reg->map_ptr;
  1253. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  1254. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  1255. * check that [key, key + map->key_size) are within
  1256. * stack limits and initialized
  1257. */
  1258. if (!meta->map_ptr) {
  1259. /* in function declaration map_ptr must come before
  1260. * map_key, so that it's verified and known before
  1261. * we have to check map_key here. Otherwise it means
  1262. * that kernel subsystem misconfigured verifier
  1263. */
  1264. verbose("invalid map_ptr to access map->key\n");
  1265. return -EACCES;
  1266. }
  1267. if (type == PTR_TO_PACKET)
  1268. err = check_packet_access(env, regno, reg->off,
  1269. meta->map_ptr->key_size);
  1270. else
  1271. err = check_stack_boundary(env, regno,
  1272. meta->map_ptr->key_size,
  1273. false, NULL);
  1274. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  1275. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  1276. * check [value, value + map->value_size) validity
  1277. */
  1278. if (!meta->map_ptr) {
  1279. /* kernel subsystem misconfigured verifier */
  1280. verbose("invalid map_ptr to access map->value\n");
  1281. return -EACCES;
  1282. }
  1283. if (type == PTR_TO_PACKET)
  1284. err = check_packet_access(env, regno, reg->off,
  1285. meta->map_ptr->value_size);
  1286. else
  1287. err = check_stack_boundary(env, regno,
  1288. meta->map_ptr->value_size,
  1289. false, NULL);
  1290. } else if (arg_type == ARG_CONST_SIZE ||
  1291. arg_type == ARG_CONST_SIZE_OR_ZERO) {
  1292. bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
  1293. /* bpf_xxx(..., buf, len) call will access 'len' bytes
  1294. * from stack pointer 'buf'. Check it
  1295. * note: regno == len, regno - 1 == buf
  1296. */
  1297. if (regno == 0) {
  1298. /* kernel subsystem misconfigured verifier */
  1299. verbose("ARG_CONST_SIZE cannot be first argument\n");
  1300. return -EACCES;
  1301. }
  1302. /* The register is SCALAR_VALUE; the access check
  1303. * happens using its boundaries.
  1304. */
  1305. if (!tnum_is_const(reg->var_off))
  1306. /* For unprivileged variable accesses, disable raw
  1307. * mode so that the program is required to
  1308. * initialize all the memory that the helper could
  1309. * just partially fill up.
  1310. */
  1311. meta = NULL;
  1312. if (reg->smin_value < 0) {
  1313. verbose("R%d min value is negative, either use unsigned or 'var &= const'\n",
  1314. regno);
  1315. return -EACCES;
  1316. }
  1317. if (reg->umin_value == 0) {
  1318. err = check_helper_mem_access(env, regno - 1, 0,
  1319. zero_size_allowed,
  1320. meta);
  1321. if (err)
  1322. return err;
  1323. }
  1324. if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
  1325. verbose("R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
  1326. regno);
  1327. return -EACCES;
  1328. }
  1329. err = check_helper_mem_access(env, regno - 1,
  1330. reg->umax_value,
  1331. zero_size_allowed, meta);
  1332. }
  1333. return err;
  1334. err_type:
  1335. verbose("R%d type=%s expected=%s\n", regno,
  1336. reg_type_str[type], reg_type_str[expected_type]);
  1337. return -EACCES;
  1338. }
  1339. static int check_map_func_compatibility(struct bpf_map *map, int func_id)
  1340. {
  1341. if (!map)
  1342. return 0;
  1343. /* We need a two way check, first is from map perspective ... */
  1344. switch (map->map_type) {
  1345. case BPF_MAP_TYPE_PROG_ARRAY:
  1346. if (func_id != BPF_FUNC_tail_call)
  1347. goto error;
  1348. break;
  1349. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  1350. if (func_id != BPF_FUNC_perf_event_read &&
  1351. func_id != BPF_FUNC_perf_event_output)
  1352. goto error;
  1353. break;
  1354. case BPF_MAP_TYPE_STACK_TRACE:
  1355. if (func_id != BPF_FUNC_get_stackid)
  1356. goto error;
  1357. break;
  1358. case BPF_MAP_TYPE_CGROUP_ARRAY:
  1359. if (func_id != BPF_FUNC_skb_under_cgroup &&
  1360. func_id != BPF_FUNC_current_task_under_cgroup)
  1361. goto error;
  1362. break;
  1363. /* devmap returns a pointer to a live net_device ifindex that we cannot
  1364. * allow to be modified from bpf side. So do not allow lookup elements
  1365. * for now.
  1366. */
  1367. case BPF_MAP_TYPE_DEVMAP:
  1368. if (func_id != BPF_FUNC_redirect_map)
  1369. goto error;
  1370. break;
  1371. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  1372. case BPF_MAP_TYPE_HASH_OF_MAPS:
  1373. if (func_id != BPF_FUNC_map_lookup_elem)
  1374. goto error;
  1375. case BPF_MAP_TYPE_SOCKMAP:
  1376. if (func_id != BPF_FUNC_sk_redirect_map &&
  1377. func_id != BPF_FUNC_sock_map_update &&
  1378. func_id != BPF_FUNC_map_delete_elem)
  1379. goto error;
  1380. break;
  1381. default:
  1382. break;
  1383. }
  1384. /* ... and second from the function itself. */
  1385. switch (func_id) {
  1386. case BPF_FUNC_tail_call:
  1387. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  1388. goto error;
  1389. break;
  1390. case BPF_FUNC_perf_event_read:
  1391. case BPF_FUNC_perf_event_output:
  1392. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  1393. goto error;
  1394. break;
  1395. case BPF_FUNC_get_stackid:
  1396. if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
  1397. goto error;
  1398. break;
  1399. case BPF_FUNC_current_task_under_cgroup:
  1400. case BPF_FUNC_skb_under_cgroup:
  1401. if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
  1402. goto error;
  1403. break;
  1404. case BPF_FUNC_redirect_map:
  1405. if (map->map_type != BPF_MAP_TYPE_DEVMAP)
  1406. goto error;
  1407. break;
  1408. case BPF_FUNC_sk_redirect_map:
  1409. if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
  1410. goto error;
  1411. break;
  1412. case BPF_FUNC_sock_map_update:
  1413. if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
  1414. goto error;
  1415. break;
  1416. default:
  1417. break;
  1418. }
  1419. return 0;
  1420. error:
  1421. verbose("cannot pass map_type %d into func %s#%d\n",
  1422. map->map_type, func_id_name(func_id), func_id);
  1423. return -EINVAL;
  1424. }
  1425. static int check_raw_mode(const struct bpf_func_proto *fn)
  1426. {
  1427. int count = 0;
  1428. if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
  1429. count++;
  1430. if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
  1431. count++;
  1432. if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
  1433. count++;
  1434. if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
  1435. count++;
  1436. if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
  1437. count++;
  1438. return count > 1 ? -EINVAL : 0;
  1439. }
  1440. /* Packet data might have moved, any old PTR_TO_PACKET[_END] are now invalid,
  1441. * so turn them into unknown SCALAR_VALUE.
  1442. */
  1443. static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
  1444. {
  1445. struct bpf_verifier_state *state = &env->cur_state;
  1446. struct bpf_reg_state *regs = state->regs, *reg;
  1447. int i;
  1448. for (i = 0; i < MAX_BPF_REG; i++)
  1449. if (regs[i].type == PTR_TO_PACKET ||
  1450. regs[i].type == PTR_TO_PACKET_END)
  1451. mark_reg_unknown(regs, i);
  1452. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  1453. if (state->stack_slot_type[i] != STACK_SPILL)
  1454. continue;
  1455. reg = &state->spilled_regs[i / BPF_REG_SIZE];
  1456. if (reg->type != PTR_TO_PACKET &&
  1457. reg->type != PTR_TO_PACKET_END)
  1458. continue;
  1459. __mark_reg_unknown(reg);
  1460. }
  1461. }
  1462. static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
  1463. {
  1464. struct bpf_verifier_state *state = &env->cur_state;
  1465. const struct bpf_func_proto *fn = NULL;
  1466. struct bpf_reg_state *regs = state->regs;
  1467. struct bpf_call_arg_meta meta;
  1468. bool changes_data;
  1469. int i, err;
  1470. /* find function prototype */
  1471. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  1472. verbose("invalid func %s#%d\n", func_id_name(func_id), func_id);
  1473. return -EINVAL;
  1474. }
  1475. if (env->prog->aux->ops->get_func_proto)
  1476. fn = env->prog->aux->ops->get_func_proto(func_id);
  1477. if (!fn) {
  1478. verbose("unknown func %s#%d\n", func_id_name(func_id), func_id);
  1479. return -EINVAL;
  1480. }
  1481. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  1482. if (!env->prog->gpl_compatible && fn->gpl_only) {
  1483. verbose("cannot call GPL only function from proprietary program\n");
  1484. return -EINVAL;
  1485. }
  1486. changes_data = bpf_helper_changes_pkt_data(fn->func);
  1487. memset(&meta, 0, sizeof(meta));
  1488. meta.pkt_access = fn->pkt_access;
  1489. /* We only support one arg being in raw mode at the moment, which
  1490. * is sufficient for the helper functions we have right now.
  1491. */
  1492. err = check_raw_mode(fn);
  1493. if (err) {
  1494. verbose("kernel subsystem misconfigured func %s#%d\n",
  1495. func_id_name(func_id), func_id);
  1496. return err;
  1497. }
  1498. /* check args */
  1499. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
  1500. if (err)
  1501. return err;
  1502. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
  1503. if (err)
  1504. return err;
  1505. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
  1506. if (err)
  1507. return err;
  1508. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
  1509. if (err)
  1510. return err;
  1511. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
  1512. if (err)
  1513. return err;
  1514. /* Mark slots with STACK_MISC in case of raw mode, stack offset
  1515. * is inferred from register state.
  1516. */
  1517. for (i = 0; i < meta.access_size; i++) {
  1518. err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
  1519. if (err)
  1520. return err;
  1521. }
  1522. /* reset caller saved regs */
  1523. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  1524. mark_reg_not_init(regs, caller_saved[i]);
  1525. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  1526. }
  1527. /* update return register (already marked as written above) */
  1528. if (fn->ret_type == RET_INTEGER) {
  1529. /* sets type to SCALAR_VALUE */
  1530. mark_reg_unknown(regs, BPF_REG_0);
  1531. } else if (fn->ret_type == RET_VOID) {
  1532. regs[BPF_REG_0].type = NOT_INIT;
  1533. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  1534. struct bpf_insn_aux_data *insn_aux;
  1535. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  1536. /* There is no offset yet applied, variable or fixed */
  1537. mark_reg_known_zero(regs, BPF_REG_0);
  1538. regs[BPF_REG_0].off = 0;
  1539. /* remember map_ptr, so that check_map_access()
  1540. * can check 'value_size' boundary of memory access
  1541. * to map element returned from bpf_map_lookup_elem()
  1542. */
  1543. if (meta.map_ptr == NULL) {
  1544. verbose("kernel subsystem misconfigured verifier\n");
  1545. return -EINVAL;
  1546. }
  1547. regs[BPF_REG_0].map_ptr = meta.map_ptr;
  1548. regs[BPF_REG_0].id = ++env->id_gen;
  1549. insn_aux = &env->insn_aux_data[insn_idx];
  1550. if (!insn_aux->map_ptr)
  1551. insn_aux->map_ptr = meta.map_ptr;
  1552. else if (insn_aux->map_ptr != meta.map_ptr)
  1553. insn_aux->map_ptr = BPF_MAP_PTR_POISON;
  1554. } else {
  1555. verbose("unknown return type %d of func %s#%d\n",
  1556. fn->ret_type, func_id_name(func_id), func_id);
  1557. return -EINVAL;
  1558. }
  1559. err = check_map_func_compatibility(meta.map_ptr, func_id);
  1560. if (err)
  1561. return err;
  1562. if (changes_data)
  1563. clear_all_pkt_pointers(env);
  1564. return 0;
  1565. }
  1566. static void coerce_reg_to_32(struct bpf_reg_state *reg)
  1567. {
  1568. /* clear high 32 bits */
  1569. reg->var_off = tnum_cast(reg->var_off, 4);
  1570. /* Update bounds */
  1571. __update_reg_bounds(reg);
  1572. }
  1573. static bool signed_add_overflows(s64 a, s64 b)
  1574. {
  1575. /* Do the add in u64, where overflow is well-defined */
  1576. s64 res = (s64)((u64)a + (u64)b);
  1577. if (b < 0)
  1578. return res > a;
  1579. return res < a;
  1580. }
  1581. static bool signed_sub_overflows(s64 a, s64 b)
  1582. {
  1583. /* Do the sub in u64, where overflow is well-defined */
  1584. s64 res = (s64)((u64)a - (u64)b);
  1585. if (b < 0)
  1586. return res < a;
  1587. return res > a;
  1588. }
  1589. /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
  1590. * Caller should also handle BPF_MOV case separately.
  1591. * If we return -EACCES, caller may want to try again treating pointer as a
  1592. * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
  1593. */
  1594. static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
  1595. struct bpf_insn *insn,
  1596. const struct bpf_reg_state *ptr_reg,
  1597. const struct bpf_reg_state *off_reg)
  1598. {
  1599. struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
  1600. bool known = tnum_is_const(off_reg->var_off);
  1601. s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
  1602. smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
  1603. u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
  1604. umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
  1605. u8 opcode = BPF_OP(insn->code);
  1606. u32 dst = insn->dst_reg;
  1607. dst_reg = &regs[dst];
  1608. if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
  1609. print_verifier_state(&env->cur_state);
  1610. verbose("verifier internal error: known but bad sbounds\n");
  1611. return -EINVAL;
  1612. }
  1613. if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
  1614. print_verifier_state(&env->cur_state);
  1615. verbose("verifier internal error: known but bad ubounds\n");
  1616. return -EINVAL;
  1617. }
  1618. if (BPF_CLASS(insn->code) != BPF_ALU64) {
  1619. /* 32-bit ALU ops on pointers produce (meaningless) scalars */
  1620. if (!env->allow_ptr_leaks)
  1621. verbose("R%d 32-bit pointer arithmetic prohibited\n",
  1622. dst);
  1623. return -EACCES;
  1624. }
  1625. if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  1626. if (!env->allow_ptr_leaks)
  1627. verbose("R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
  1628. dst);
  1629. return -EACCES;
  1630. }
  1631. if (ptr_reg->type == CONST_PTR_TO_MAP) {
  1632. if (!env->allow_ptr_leaks)
  1633. verbose("R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
  1634. dst);
  1635. return -EACCES;
  1636. }
  1637. if (ptr_reg->type == PTR_TO_PACKET_END) {
  1638. if (!env->allow_ptr_leaks)
  1639. verbose("R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
  1640. dst);
  1641. return -EACCES;
  1642. }
  1643. /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
  1644. * The id may be overwritten later if we create a new variable offset.
  1645. */
  1646. dst_reg->type = ptr_reg->type;
  1647. dst_reg->id = ptr_reg->id;
  1648. switch (opcode) {
  1649. case BPF_ADD:
  1650. /* We can take a fixed offset as long as it doesn't overflow
  1651. * the s32 'off' field
  1652. */
  1653. if (known && (ptr_reg->off + smin_val ==
  1654. (s64)(s32)(ptr_reg->off + smin_val))) {
  1655. /* pointer += K. Accumulate it into fixed offset */
  1656. dst_reg->smin_value = smin_ptr;
  1657. dst_reg->smax_value = smax_ptr;
  1658. dst_reg->umin_value = umin_ptr;
  1659. dst_reg->umax_value = umax_ptr;
  1660. dst_reg->var_off = ptr_reg->var_off;
  1661. dst_reg->off = ptr_reg->off + smin_val;
  1662. dst_reg->range = ptr_reg->range;
  1663. break;
  1664. }
  1665. /* A new variable offset is created. Note that off_reg->off
  1666. * == 0, since it's a scalar.
  1667. * dst_reg gets the pointer type and since some positive
  1668. * integer value was added to the pointer, give it a new 'id'
  1669. * if it's a PTR_TO_PACKET.
  1670. * this creates a new 'base' pointer, off_reg (variable) gets
  1671. * added into the variable offset, and we copy the fixed offset
  1672. * from ptr_reg.
  1673. */
  1674. if (signed_add_overflows(smin_ptr, smin_val) ||
  1675. signed_add_overflows(smax_ptr, smax_val)) {
  1676. dst_reg->smin_value = S64_MIN;
  1677. dst_reg->smax_value = S64_MAX;
  1678. } else {
  1679. dst_reg->smin_value = smin_ptr + smin_val;
  1680. dst_reg->smax_value = smax_ptr + smax_val;
  1681. }
  1682. if (umin_ptr + umin_val < umin_ptr ||
  1683. umax_ptr + umax_val < umax_ptr) {
  1684. dst_reg->umin_value = 0;
  1685. dst_reg->umax_value = U64_MAX;
  1686. } else {
  1687. dst_reg->umin_value = umin_ptr + umin_val;
  1688. dst_reg->umax_value = umax_ptr + umax_val;
  1689. }
  1690. dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
  1691. dst_reg->off = ptr_reg->off;
  1692. if (ptr_reg->type == PTR_TO_PACKET) {
  1693. dst_reg->id = ++env->id_gen;
  1694. /* something was added to pkt_ptr, set range to zero */
  1695. dst_reg->range = 0;
  1696. }
  1697. break;
  1698. case BPF_SUB:
  1699. if (dst_reg == off_reg) {
  1700. /* scalar -= pointer. Creates an unknown scalar */
  1701. if (!env->allow_ptr_leaks)
  1702. verbose("R%d tried to subtract pointer from scalar\n",
  1703. dst);
  1704. return -EACCES;
  1705. }
  1706. /* We don't allow subtraction from FP, because (according to
  1707. * test_verifier.c test "invalid fp arithmetic", JITs might not
  1708. * be able to deal with it.
  1709. */
  1710. if (ptr_reg->type == PTR_TO_STACK) {
  1711. if (!env->allow_ptr_leaks)
  1712. verbose("R%d subtraction from stack pointer prohibited\n",
  1713. dst);
  1714. return -EACCES;
  1715. }
  1716. if (known && (ptr_reg->off - smin_val ==
  1717. (s64)(s32)(ptr_reg->off - smin_val))) {
  1718. /* pointer -= K. Subtract it from fixed offset */
  1719. dst_reg->smin_value = smin_ptr;
  1720. dst_reg->smax_value = smax_ptr;
  1721. dst_reg->umin_value = umin_ptr;
  1722. dst_reg->umax_value = umax_ptr;
  1723. dst_reg->var_off = ptr_reg->var_off;
  1724. dst_reg->id = ptr_reg->id;
  1725. dst_reg->off = ptr_reg->off - smin_val;
  1726. dst_reg->range = ptr_reg->range;
  1727. break;
  1728. }
  1729. /* A new variable offset is created. If the subtrahend is known
  1730. * nonnegative, then any reg->range we had before is still good.
  1731. */
  1732. if (signed_sub_overflows(smin_ptr, smax_val) ||
  1733. signed_sub_overflows(smax_ptr, smin_val)) {
  1734. /* Overflow possible, we know nothing */
  1735. dst_reg->smin_value = S64_MIN;
  1736. dst_reg->smax_value = S64_MAX;
  1737. } else {
  1738. dst_reg->smin_value = smin_ptr - smax_val;
  1739. dst_reg->smax_value = smax_ptr - smin_val;
  1740. }
  1741. if (umin_ptr < umax_val) {
  1742. /* Overflow possible, we know nothing */
  1743. dst_reg->umin_value = 0;
  1744. dst_reg->umax_value = U64_MAX;
  1745. } else {
  1746. /* Cannot overflow (as long as bounds are consistent) */
  1747. dst_reg->umin_value = umin_ptr - umax_val;
  1748. dst_reg->umax_value = umax_ptr - umin_val;
  1749. }
  1750. dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
  1751. dst_reg->off = ptr_reg->off;
  1752. if (ptr_reg->type == PTR_TO_PACKET) {
  1753. dst_reg->id = ++env->id_gen;
  1754. /* something was added to pkt_ptr, set range to zero */
  1755. if (smin_val < 0)
  1756. dst_reg->range = 0;
  1757. }
  1758. break;
  1759. case BPF_AND:
  1760. case BPF_OR:
  1761. case BPF_XOR:
  1762. /* bitwise ops on pointers are troublesome, prohibit for now.
  1763. * (However, in principle we could allow some cases, e.g.
  1764. * ptr &= ~3 which would reduce min_value by 3.)
  1765. */
  1766. if (!env->allow_ptr_leaks)
  1767. verbose("R%d bitwise operator %s on pointer prohibited\n",
  1768. dst, bpf_alu_string[opcode >> 4]);
  1769. return -EACCES;
  1770. default:
  1771. /* other operators (e.g. MUL,LSH) produce non-pointer results */
  1772. if (!env->allow_ptr_leaks)
  1773. verbose("R%d pointer arithmetic with %s operator prohibited\n",
  1774. dst, bpf_alu_string[opcode >> 4]);
  1775. return -EACCES;
  1776. }
  1777. __update_reg_bounds(dst_reg);
  1778. __reg_deduce_bounds(dst_reg);
  1779. __reg_bound_offset(dst_reg);
  1780. return 0;
  1781. }
  1782. static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
  1783. struct bpf_insn *insn,
  1784. struct bpf_reg_state *dst_reg,
  1785. struct bpf_reg_state src_reg)
  1786. {
  1787. struct bpf_reg_state *regs = env->cur_state.regs;
  1788. u8 opcode = BPF_OP(insn->code);
  1789. bool src_known, dst_known;
  1790. s64 smin_val, smax_val;
  1791. u64 umin_val, umax_val;
  1792. if (BPF_CLASS(insn->code) != BPF_ALU64) {
  1793. /* 32-bit ALU ops are (32,32)->64 */
  1794. coerce_reg_to_32(dst_reg);
  1795. coerce_reg_to_32(&src_reg);
  1796. }
  1797. smin_val = src_reg.smin_value;
  1798. smax_val = src_reg.smax_value;
  1799. umin_val = src_reg.umin_value;
  1800. umax_val = src_reg.umax_value;
  1801. src_known = tnum_is_const(src_reg.var_off);
  1802. dst_known = tnum_is_const(dst_reg->var_off);
  1803. switch (opcode) {
  1804. case BPF_ADD:
  1805. if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
  1806. signed_add_overflows(dst_reg->smax_value, smax_val)) {
  1807. dst_reg->smin_value = S64_MIN;
  1808. dst_reg->smax_value = S64_MAX;
  1809. } else {
  1810. dst_reg->smin_value += smin_val;
  1811. dst_reg->smax_value += smax_val;
  1812. }
  1813. if (dst_reg->umin_value + umin_val < umin_val ||
  1814. dst_reg->umax_value + umax_val < umax_val) {
  1815. dst_reg->umin_value = 0;
  1816. dst_reg->umax_value = U64_MAX;
  1817. } else {
  1818. dst_reg->umin_value += umin_val;
  1819. dst_reg->umax_value += umax_val;
  1820. }
  1821. dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
  1822. break;
  1823. case BPF_SUB:
  1824. if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
  1825. signed_sub_overflows(dst_reg->smax_value, smin_val)) {
  1826. /* Overflow possible, we know nothing */
  1827. dst_reg->smin_value = S64_MIN;
  1828. dst_reg->smax_value = S64_MAX;
  1829. } else {
  1830. dst_reg->smin_value -= smax_val;
  1831. dst_reg->smax_value -= smin_val;
  1832. }
  1833. if (dst_reg->umin_value < umax_val) {
  1834. /* Overflow possible, we know nothing */
  1835. dst_reg->umin_value = 0;
  1836. dst_reg->umax_value = U64_MAX;
  1837. } else {
  1838. /* Cannot overflow (as long as bounds are consistent) */
  1839. dst_reg->umin_value -= umax_val;
  1840. dst_reg->umax_value -= umin_val;
  1841. }
  1842. dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
  1843. break;
  1844. case BPF_MUL:
  1845. dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
  1846. if (smin_val < 0 || dst_reg->smin_value < 0) {
  1847. /* Ain't nobody got time to multiply that sign */
  1848. __mark_reg_unbounded(dst_reg);
  1849. __update_reg_bounds(dst_reg);
  1850. break;
  1851. }
  1852. /* Both values are positive, so we can work with unsigned and
  1853. * copy the result to signed (unless it exceeds S64_MAX).
  1854. */
  1855. if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
  1856. /* Potential overflow, we know nothing */
  1857. __mark_reg_unbounded(dst_reg);
  1858. /* (except what we can learn from the var_off) */
  1859. __update_reg_bounds(dst_reg);
  1860. break;
  1861. }
  1862. dst_reg->umin_value *= umin_val;
  1863. dst_reg->umax_value *= umax_val;
  1864. if (dst_reg->umax_value > S64_MAX) {
  1865. /* Overflow possible, we know nothing */
  1866. dst_reg->smin_value = S64_MIN;
  1867. dst_reg->smax_value = S64_MAX;
  1868. } else {
  1869. dst_reg->smin_value = dst_reg->umin_value;
  1870. dst_reg->smax_value = dst_reg->umax_value;
  1871. }
  1872. break;
  1873. case BPF_AND:
  1874. if (src_known && dst_known) {
  1875. __mark_reg_known(dst_reg, dst_reg->var_off.value &
  1876. src_reg.var_off.value);
  1877. break;
  1878. }
  1879. /* We get our minimum from the var_off, since that's inherently
  1880. * bitwise. Our maximum is the minimum of the operands' maxima.
  1881. */
  1882. dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
  1883. dst_reg->umin_value = dst_reg->var_off.value;
  1884. dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
  1885. if (dst_reg->smin_value < 0 || smin_val < 0) {
  1886. /* Lose signed bounds when ANDing negative numbers,
  1887. * ain't nobody got time for that.
  1888. */
  1889. dst_reg->smin_value = S64_MIN;
  1890. dst_reg->smax_value = S64_MAX;
  1891. } else {
  1892. /* ANDing two positives gives a positive, so safe to
  1893. * cast result into s64.
  1894. */
  1895. dst_reg->smin_value = dst_reg->umin_value;
  1896. dst_reg->smax_value = dst_reg->umax_value;
  1897. }
  1898. /* We may learn something more from the var_off */
  1899. __update_reg_bounds(dst_reg);
  1900. break;
  1901. case BPF_OR:
  1902. if (src_known && dst_known) {
  1903. __mark_reg_known(dst_reg, dst_reg->var_off.value |
  1904. src_reg.var_off.value);
  1905. break;
  1906. }
  1907. /* We get our maximum from the var_off, and our minimum is the
  1908. * maximum of the operands' minima
  1909. */
  1910. dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
  1911. dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
  1912. dst_reg->umax_value = dst_reg->var_off.value |
  1913. dst_reg->var_off.mask;
  1914. if (dst_reg->smin_value < 0 || smin_val < 0) {
  1915. /* Lose signed bounds when ORing negative numbers,
  1916. * ain't nobody got time for that.
  1917. */
  1918. dst_reg->smin_value = S64_MIN;
  1919. dst_reg->smax_value = S64_MAX;
  1920. } else {
  1921. /* ORing two positives gives a positive, so safe to
  1922. * cast result into s64.
  1923. */
  1924. dst_reg->smin_value = dst_reg->umin_value;
  1925. dst_reg->smax_value = dst_reg->umax_value;
  1926. }
  1927. /* We may learn something more from the var_off */
  1928. __update_reg_bounds(dst_reg);
  1929. break;
  1930. case BPF_LSH:
  1931. if (umax_val > 63) {
  1932. /* Shifts greater than 63 are undefined. This includes
  1933. * shifts by a negative number.
  1934. */
  1935. mark_reg_unknown(regs, insn->dst_reg);
  1936. break;
  1937. }
  1938. /* We lose all sign bit information (except what we can pick
  1939. * up from var_off)
  1940. */
  1941. dst_reg->smin_value = S64_MIN;
  1942. dst_reg->smax_value = S64_MAX;
  1943. /* If we might shift our top bit out, then we know nothing */
  1944. if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
  1945. dst_reg->umin_value = 0;
  1946. dst_reg->umax_value = U64_MAX;
  1947. } else {
  1948. dst_reg->umin_value <<= umin_val;
  1949. dst_reg->umax_value <<= umax_val;
  1950. }
  1951. if (src_known)
  1952. dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
  1953. else
  1954. dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
  1955. /* We may learn something more from the var_off */
  1956. __update_reg_bounds(dst_reg);
  1957. break;
  1958. case BPF_RSH:
  1959. if (umax_val > 63) {
  1960. /* Shifts greater than 63 are undefined. This includes
  1961. * shifts by a negative number.
  1962. */
  1963. mark_reg_unknown(regs, insn->dst_reg);
  1964. break;
  1965. }
  1966. /* BPF_RSH is an unsigned shift, so make the appropriate casts */
  1967. if (dst_reg->smin_value < 0) {
  1968. if (umin_val) {
  1969. /* Sign bit will be cleared */
  1970. dst_reg->smin_value = 0;
  1971. } else {
  1972. /* Lost sign bit information */
  1973. dst_reg->smin_value = S64_MIN;
  1974. dst_reg->smax_value = S64_MAX;
  1975. }
  1976. } else {
  1977. dst_reg->smin_value =
  1978. (u64)(dst_reg->smin_value) >> umax_val;
  1979. }
  1980. if (src_known)
  1981. dst_reg->var_off = tnum_rshift(dst_reg->var_off,
  1982. umin_val);
  1983. else
  1984. dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
  1985. dst_reg->umin_value >>= umax_val;
  1986. dst_reg->umax_value >>= umin_val;
  1987. /* We may learn something more from the var_off */
  1988. __update_reg_bounds(dst_reg);
  1989. break;
  1990. default:
  1991. mark_reg_unknown(regs, insn->dst_reg);
  1992. break;
  1993. }
  1994. __reg_deduce_bounds(dst_reg);
  1995. __reg_bound_offset(dst_reg);
  1996. return 0;
  1997. }
  1998. /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
  1999. * and var_off.
  2000. */
  2001. static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
  2002. struct bpf_insn *insn)
  2003. {
  2004. struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg, *src_reg;
  2005. struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
  2006. u8 opcode = BPF_OP(insn->code);
  2007. int rc;
  2008. dst_reg = &regs[insn->dst_reg];
  2009. src_reg = NULL;
  2010. if (dst_reg->type != SCALAR_VALUE)
  2011. ptr_reg = dst_reg;
  2012. if (BPF_SRC(insn->code) == BPF_X) {
  2013. src_reg = &regs[insn->src_reg];
  2014. if (src_reg->type != SCALAR_VALUE) {
  2015. if (dst_reg->type != SCALAR_VALUE) {
  2016. /* Combining two pointers by any ALU op yields
  2017. * an arbitrary scalar.
  2018. */
  2019. if (!env->allow_ptr_leaks) {
  2020. verbose("R%d pointer %s pointer prohibited\n",
  2021. insn->dst_reg,
  2022. bpf_alu_string[opcode >> 4]);
  2023. return -EACCES;
  2024. }
  2025. mark_reg_unknown(regs, insn->dst_reg);
  2026. return 0;
  2027. } else {
  2028. /* scalar += pointer
  2029. * This is legal, but we have to reverse our
  2030. * src/dest handling in computing the range
  2031. */
  2032. rc = adjust_ptr_min_max_vals(env, insn,
  2033. src_reg, dst_reg);
  2034. if (rc == -EACCES && env->allow_ptr_leaks) {
  2035. /* scalar += unknown scalar */
  2036. __mark_reg_unknown(&off_reg);
  2037. return adjust_scalar_min_max_vals(
  2038. env, insn,
  2039. dst_reg, off_reg);
  2040. }
  2041. return rc;
  2042. }
  2043. } else if (ptr_reg) {
  2044. /* pointer += scalar */
  2045. rc = adjust_ptr_min_max_vals(env, insn,
  2046. dst_reg, src_reg);
  2047. if (rc == -EACCES && env->allow_ptr_leaks) {
  2048. /* unknown scalar += scalar */
  2049. __mark_reg_unknown(dst_reg);
  2050. return adjust_scalar_min_max_vals(
  2051. env, insn, dst_reg, *src_reg);
  2052. }
  2053. return rc;
  2054. }
  2055. } else {
  2056. /* Pretend the src is a reg with a known value, since we only
  2057. * need to be able to read from this state.
  2058. */
  2059. off_reg.type = SCALAR_VALUE;
  2060. __mark_reg_known(&off_reg, insn->imm);
  2061. src_reg = &off_reg;
  2062. if (ptr_reg) { /* pointer += K */
  2063. rc = adjust_ptr_min_max_vals(env, insn,
  2064. ptr_reg, src_reg);
  2065. if (rc == -EACCES && env->allow_ptr_leaks) {
  2066. /* unknown scalar += K */
  2067. __mark_reg_unknown(dst_reg);
  2068. return adjust_scalar_min_max_vals(
  2069. env, insn, dst_reg, off_reg);
  2070. }
  2071. return rc;
  2072. }
  2073. }
  2074. /* Got here implies adding two SCALAR_VALUEs */
  2075. if (WARN_ON_ONCE(ptr_reg)) {
  2076. print_verifier_state(&env->cur_state);
  2077. verbose("verifier internal error: unexpected ptr_reg\n");
  2078. return -EINVAL;
  2079. }
  2080. if (WARN_ON(!src_reg)) {
  2081. print_verifier_state(&env->cur_state);
  2082. verbose("verifier internal error: no src_reg\n");
  2083. return -EINVAL;
  2084. }
  2085. return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
  2086. }
  2087. /* check validity of 32-bit and 64-bit arithmetic operations */
  2088. static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2089. {
  2090. struct bpf_reg_state *regs = env->cur_state.regs;
  2091. u8 opcode = BPF_OP(insn->code);
  2092. int err;
  2093. if (opcode == BPF_END || opcode == BPF_NEG) {
  2094. if (opcode == BPF_NEG) {
  2095. if (BPF_SRC(insn->code) != 0 ||
  2096. insn->src_reg != BPF_REG_0 ||
  2097. insn->off != 0 || insn->imm != 0) {
  2098. verbose("BPF_NEG uses reserved fields\n");
  2099. return -EINVAL;
  2100. }
  2101. } else {
  2102. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  2103. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
  2104. verbose("BPF_END uses reserved fields\n");
  2105. return -EINVAL;
  2106. }
  2107. }
  2108. /* check src operand */
  2109. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  2110. if (err)
  2111. return err;
  2112. if (is_pointer_value(env, insn->dst_reg)) {
  2113. verbose("R%d pointer arithmetic prohibited\n",
  2114. insn->dst_reg);
  2115. return -EACCES;
  2116. }
  2117. /* check dest operand */
  2118. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  2119. if (err)
  2120. return err;
  2121. } else if (opcode == BPF_MOV) {
  2122. if (BPF_SRC(insn->code) == BPF_X) {
  2123. if (insn->imm != 0 || insn->off != 0) {
  2124. verbose("BPF_MOV uses reserved fields\n");
  2125. return -EINVAL;
  2126. }
  2127. /* check src operand */
  2128. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  2129. if (err)
  2130. return err;
  2131. } else {
  2132. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  2133. verbose("BPF_MOV uses reserved fields\n");
  2134. return -EINVAL;
  2135. }
  2136. }
  2137. /* check dest operand */
  2138. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  2139. if (err)
  2140. return err;
  2141. if (BPF_SRC(insn->code) == BPF_X) {
  2142. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  2143. /* case: R1 = R2
  2144. * copy register state to dest reg
  2145. */
  2146. regs[insn->dst_reg] = regs[insn->src_reg];
  2147. } else {
  2148. /* R1 = (u32) R2 */
  2149. if (is_pointer_value(env, insn->src_reg)) {
  2150. verbose("R%d partial copy of pointer\n",
  2151. insn->src_reg);
  2152. return -EACCES;
  2153. }
  2154. mark_reg_unknown(regs, insn->dst_reg);
  2155. /* high 32 bits are known zero. */
  2156. regs[insn->dst_reg].var_off = tnum_cast(
  2157. regs[insn->dst_reg].var_off, 4);
  2158. __update_reg_bounds(&regs[insn->dst_reg]);
  2159. }
  2160. } else {
  2161. /* case: R = imm
  2162. * remember the value we stored into this reg
  2163. */
  2164. regs[insn->dst_reg].type = SCALAR_VALUE;
  2165. __mark_reg_known(regs + insn->dst_reg, insn->imm);
  2166. }
  2167. } else if (opcode > BPF_END) {
  2168. verbose("invalid BPF_ALU opcode %x\n", opcode);
  2169. return -EINVAL;
  2170. } else { /* all other ALU ops: and, sub, xor, add, ... */
  2171. if (BPF_SRC(insn->code) == BPF_X) {
  2172. if (insn->imm != 0 || insn->off != 0) {
  2173. verbose("BPF_ALU uses reserved fields\n");
  2174. return -EINVAL;
  2175. }
  2176. /* check src1 operand */
  2177. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  2178. if (err)
  2179. return err;
  2180. } else {
  2181. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  2182. verbose("BPF_ALU uses reserved fields\n");
  2183. return -EINVAL;
  2184. }
  2185. }
  2186. /* check src2 operand */
  2187. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  2188. if (err)
  2189. return err;
  2190. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  2191. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  2192. verbose("div by zero\n");
  2193. return -EINVAL;
  2194. }
  2195. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  2196. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  2197. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  2198. if (insn->imm < 0 || insn->imm >= size) {
  2199. verbose("invalid shift %d\n", insn->imm);
  2200. return -EINVAL;
  2201. }
  2202. }
  2203. /* check dest operand */
  2204. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  2205. if (err)
  2206. return err;
  2207. return adjust_reg_min_max_vals(env, insn);
  2208. }
  2209. return 0;
  2210. }
  2211. static void find_good_pkt_pointers(struct bpf_verifier_state *state,
  2212. struct bpf_reg_state *dst_reg)
  2213. {
  2214. struct bpf_reg_state *regs = state->regs, *reg;
  2215. int i;
  2216. if (dst_reg->off < 0)
  2217. /* This doesn't give us any range */
  2218. return;
  2219. if (dst_reg->umax_value > MAX_PACKET_OFF ||
  2220. dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
  2221. /* Risk of overflow. For instance, ptr + (1<<63) may be less
  2222. * than pkt_end, but that's because it's also less than pkt.
  2223. */
  2224. return;
  2225. /* LLVM can generate four kind of checks:
  2226. *
  2227. * Type 1/2:
  2228. *
  2229. * r2 = r3;
  2230. * r2 += 8;
  2231. * if (r2 > pkt_end) goto <handle exception>
  2232. * <access okay>
  2233. *
  2234. * r2 = r3;
  2235. * r2 += 8;
  2236. * if (r2 < pkt_end) goto <access okay>
  2237. * <handle exception>
  2238. *
  2239. * Where:
  2240. * r2 == dst_reg, pkt_end == src_reg
  2241. * r2=pkt(id=n,off=8,r=0)
  2242. * r3=pkt(id=n,off=0,r=0)
  2243. *
  2244. * Type 3/4:
  2245. *
  2246. * r2 = r3;
  2247. * r2 += 8;
  2248. * if (pkt_end >= r2) goto <access okay>
  2249. * <handle exception>
  2250. *
  2251. * r2 = r3;
  2252. * r2 += 8;
  2253. * if (pkt_end <= r2) goto <handle exception>
  2254. * <access okay>
  2255. *
  2256. * Where:
  2257. * pkt_end == dst_reg, r2 == src_reg
  2258. * r2=pkt(id=n,off=8,r=0)
  2259. * r3=pkt(id=n,off=0,r=0)
  2260. *
  2261. * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
  2262. * so that range of bytes [r3, r3 + 8) is safe to access.
  2263. */
  2264. /* If our ids match, then we must have the same max_value. And we
  2265. * don't care about the other reg's fixed offset, since if it's too big
  2266. * the range won't allow anything.
  2267. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
  2268. */
  2269. for (i = 0; i < MAX_BPF_REG; i++)
  2270. if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
  2271. /* keep the maximum range already checked */
  2272. regs[i].range = max_t(u16, regs[i].range, dst_reg->off);
  2273. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  2274. if (state->stack_slot_type[i] != STACK_SPILL)
  2275. continue;
  2276. reg = &state->spilled_regs[i / BPF_REG_SIZE];
  2277. if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
  2278. reg->range = max_t(u16, reg->range, dst_reg->off);
  2279. }
  2280. }
  2281. /* Adjusts the register min/max values in the case that the dst_reg is the
  2282. * variable register that we are working on, and src_reg is a constant or we're
  2283. * simply doing a BPF_K check.
  2284. * In JEQ/JNE cases we also adjust the var_off values.
  2285. */
  2286. static void reg_set_min_max(struct bpf_reg_state *true_reg,
  2287. struct bpf_reg_state *false_reg, u64 val,
  2288. u8 opcode)
  2289. {
  2290. /* If the dst_reg is a pointer, we can't learn anything about its
  2291. * variable offset from the compare (unless src_reg were a pointer into
  2292. * the same object, but we don't bother with that.
  2293. * Since false_reg and true_reg have the same type by construction, we
  2294. * only need to check one of them for pointerness.
  2295. */
  2296. if (__is_pointer_value(false, false_reg))
  2297. return;
  2298. switch (opcode) {
  2299. case BPF_JEQ:
  2300. /* If this is false then we know nothing Jon Snow, but if it is
  2301. * true then we know for sure.
  2302. */
  2303. __mark_reg_known(true_reg, val);
  2304. break;
  2305. case BPF_JNE:
  2306. /* If this is true we know nothing Jon Snow, but if it is false
  2307. * we know the value for sure;
  2308. */
  2309. __mark_reg_known(false_reg, val);
  2310. break;
  2311. case BPF_JGT:
  2312. false_reg->umax_value = min(false_reg->umax_value, val);
  2313. true_reg->umin_value = max(true_reg->umin_value, val + 1);
  2314. break;
  2315. case BPF_JSGT:
  2316. false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
  2317. true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
  2318. break;
  2319. case BPF_JLT:
  2320. false_reg->umin_value = max(false_reg->umin_value, val);
  2321. true_reg->umax_value = min(true_reg->umax_value, val - 1);
  2322. break;
  2323. case BPF_JSLT:
  2324. false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
  2325. true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
  2326. break;
  2327. case BPF_JGE:
  2328. false_reg->umax_value = min(false_reg->umax_value, val - 1);
  2329. true_reg->umin_value = max(true_reg->umin_value, val);
  2330. break;
  2331. case BPF_JSGE:
  2332. false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
  2333. true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
  2334. break;
  2335. case BPF_JLE:
  2336. false_reg->umin_value = max(false_reg->umin_value, val + 1);
  2337. true_reg->umax_value = min(true_reg->umax_value, val);
  2338. break;
  2339. case BPF_JSLE:
  2340. false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
  2341. true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
  2342. break;
  2343. default:
  2344. break;
  2345. }
  2346. __reg_deduce_bounds(false_reg);
  2347. __reg_deduce_bounds(true_reg);
  2348. /* We might have learned some bits from the bounds. */
  2349. __reg_bound_offset(false_reg);
  2350. __reg_bound_offset(true_reg);
  2351. /* Intersecting with the old var_off might have improved our bounds
  2352. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  2353. * then new var_off is (0; 0x7f...fc) which improves our umax.
  2354. */
  2355. __update_reg_bounds(false_reg);
  2356. __update_reg_bounds(true_reg);
  2357. }
  2358. /* Same as above, but for the case that dst_reg holds a constant and src_reg is
  2359. * the variable reg.
  2360. */
  2361. static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
  2362. struct bpf_reg_state *false_reg, u64 val,
  2363. u8 opcode)
  2364. {
  2365. if (__is_pointer_value(false, false_reg))
  2366. return;
  2367. switch (opcode) {
  2368. case BPF_JEQ:
  2369. /* If this is false then we know nothing Jon Snow, but if it is
  2370. * true then we know for sure.
  2371. */
  2372. __mark_reg_known(true_reg, val);
  2373. break;
  2374. case BPF_JNE:
  2375. /* If this is true we know nothing Jon Snow, but if it is false
  2376. * we know the value for sure;
  2377. */
  2378. __mark_reg_known(false_reg, val);
  2379. break;
  2380. case BPF_JGT:
  2381. true_reg->umax_value = min(true_reg->umax_value, val - 1);
  2382. false_reg->umin_value = max(false_reg->umin_value, val);
  2383. break;
  2384. case BPF_JSGT:
  2385. true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
  2386. false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
  2387. break;
  2388. case BPF_JLT:
  2389. true_reg->umin_value = max(true_reg->umin_value, val + 1);
  2390. false_reg->umax_value = min(false_reg->umax_value, val);
  2391. break;
  2392. case BPF_JSLT:
  2393. true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
  2394. false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
  2395. break;
  2396. case BPF_JGE:
  2397. true_reg->umax_value = min(true_reg->umax_value, val);
  2398. false_reg->umin_value = max(false_reg->umin_value, val + 1);
  2399. break;
  2400. case BPF_JSGE:
  2401. true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
  2402. false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
  2403. break;
  2404. case BPF_JLE:
  2405. true_reg->umin_value = max(true_reg->umin_value, val);
  2406. false_reg->umax_value = min(false_reg->umax_value, val - 1);
  2407. break;
  2408. case BPF_JSLE:
  2409. true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
  2410. false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
  2411. break;
  2412. default:
  2413. break;
  2414. }
  2415. __reg_deduce_bounds(false_reg);
  2416. __reg_deduce_bounds(true_reg);
  2417. /* We might have learned some bits from the bounds. */
  2418. __reg_bound_offset(false_reg);
  2419. __reg_bound_offset(true_reg);
  2420. /* Intersecting with the old var_off might have improved our bounds
  2421. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  2422. * then new var_off is (0; 0x7f...fc) which improves our umax.
  2423. */
  2424. __update_reg_bounds(false_reg);
  2425. __update_reg_bounds(true_reg);
  2426. }
  2427. /* Regs are known to be equal, so intersect their min/max/var_off */
  2428. static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
  2429. struct bpf_reg_state *dst_reg)
  2430. {
  2431. src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
  2432. dst_reg->umin_value);
  2433. src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
  2434. dst_reg->umax_value);
  2435. src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
  2436. dst_reg->smin_value);
  2437. src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
  2438. dst_reg->smax_value);
  2439. src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
  2440. dst_reg->var_off);
  2441. /* We might have learned new bounds from the var_off. */
  2442. __update_reg_bounds(src_reg);
  2443. __update_reg_bounds(dst_reg);
  2444. /* We might have learned something about the sign bit. */
  2445. __reg_deduce_bounds(src_reg);
  2446. __reg_deduce_bounds(dst_reg);
  2447. /* We might have learned some bits from the bounds. */
  2448. __reg_bound_offset(src_reg);
  2449. __reg_bound_offset(dst_reg);
  2450. /* Intersecting with the old var_off might have improved our bounds
  2451. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  2452. * then new var_off is (0; 0x7f...fc) which improves our umax.
  2453. */
  2454. __update_reg_bounds(src_reg);
  2455. __update_reg_bounds(dst_reg);
  2456. }
  2457. static void reg_combine_min_max(struct bpf_reg_state *true_src,
  2458. struct bpf_reg_state *true_dst,
  2459. struct bpf_reg_state *false_src,
  2460. struct bpf_reg_state *false_dst,
  2461. u8 opcode)
  2462. {
  2463. switch (opcode) {
  2464. case BPF_JEQ:
  2465. __reg_combine_min_max(true_src, true_dst);
  2466. break;
  2467. case BPF_JNE:
  2468. __reg_combine_min_max(false_src, false_dst);
  2469. break;
  2470. }
  2471. }
  2472. static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
  2473. bool is_null)
  2474. {
  2475. struct bpf_reg_state *reg = &regs[regno];
  2476. if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
  2477. /* Old offset (both fixed and variable parts) should
  2478. * have been known-zero, because we don't allow pointer
  2479. * arithmetic on pointers that might be NULL.
  2480. */
  2481. if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
  2482. !tnum_equals_const(reg->var_off, 0) ||
  2483. reg->off)) {
  2484. __mark_reg_known_zero(reg);
  2485. reg->off = 0;
  2486. }
  2487. if (is_null) {
  2488. reg->type = SCALAR_VALUE;
  2489. } else if (reg->map_ptr->inner_map_meta) {
  2490. reg->type = CONST_PTR_TO_MAP;
  2491. reg->map_ptr = reg->map_ptr->inner_map_meta;
  2492. } else {
  2493. reg->type = PTR_TO_MAP_VALUE;
  2494. }
  2495. /* We don't need id from this point onwards anymore, thus we
  2496. * should better reset it, so that state pruning has chances
  2497. * to take effect.
  2498. */
  2499. reg->id = 0;
  2500. }
  2501. }
  2502. /* The logic is similar to find_good_pkt_pointers(), both could eventually
  2503. * be folded together at some point.
  2504. */
  2505. static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
  2506. bool is_null)
  2507. {
  2508. struct bpf_reg_state *regs = state->regs;
  2509. u32 id = regs[regno].id;
  2510. int i;
  2511. for (i = 0; i < MAX_BPF_REG; i++)
  2512. mark_map_reg(regs, i, id, is_null);
  2513. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  2514. if (state->stack_slot_type[i] != STACK_SPILL)
  2515. continue;
  2516. mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, is_null);
  2517. }
  2518. }
  2519. static int check_cond_jmp_op(struct bpf_verifier_env *env,
  2520. struct bpf_insn *insn, int *insn_idx)
  2521. {
  2522. struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
  2523. struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
  2524. u8 opcode = BPF_OP(insn->code);
  2525. int err;
  2526. if (opcode > BPF_JSLE) {
  2527. verbose("invalid BPF_JMP opcode %x\n", opcode);
  2528. return -EINVAL;
  2529. }
  2530. if (BPF_SRC(insn->code) == BPF_X) {
  2531. if (insn->imm != 0) {
  2532. verbose("BPF_JMP uses reserved fields\n");
  2533. return -EINVAL;
  2534. }
  2535. /* check src1 operand */
  2536. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  2537. if (err)
  2538. return err;
  2539. if (is_pointer_value(env, insn->src_reg)) {
  2540. verbose("R%d pointer comparison prohibited\n",
  2541. insn->src_reg);
  2542. return -EACCES;
  2543. }
  2544. } else {
  2545. if (insn->src_reg != BPF_REG_0) {
  2546. verbose("BPF_JMP uses reserved fields\n");
  2547. return -EINVAL;
  2548. }
  2549. }
  2550. /* check src2 operand */
  2551. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  2552. if (err)
  2553. return err;
  2554. dst_reg = &regs[insn->dst_reg];
  2555. /* detect if R == 0 where R was initialized to zero earlier */
  2556. if (BPF_SRC(insn->code) == BPF_K &&
  2557. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  2558. dst_reg->type == SCALAR_VALUE &&
  2559. tnum_equals_const(dst_reg->var_off, insn->imm)) {
  2560. if (opcode == BPF_JEQ) {
  2561. /* if (imm == imm) goto pc+off;
  2562. * only follow the goto, ignore fall-through
  2563. */
  2564. *insn_idx += insn->off;
  2565. return 0;
  2566. } else {
  2567. /* if (imm != imm) goto pc+off;
  2568. * only follow fall-through branch, since
  2569. * that's where the program will go
  2570. */
  2571. return 0;
  2572. }
  2573. }
  2574. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  2575. if (!other_branch)
  2576. return -EFAULT;
  2577. /* detect if we are comparing against a constant value so we can adjust
  2578. * our min/max values for our dst register.
  2579. * this is only legit if both are scalars (or pointers to the same
  2580. * object, I suppose, but we don't support that right now), because
  2581. * otherwise the different base pointers mean the offsets aren't
  2582. * comparable.
  2583. */
  2584. if (BPF_SRC(insn->code) == BPF_X) {
  2585. if (dst_reg->type == SCALAR_VALUE &&
  2586. regs[insn->src_reg].type == SCALAR_VALUE) {
  2587. if (tnum_is_const(regs[insn->src_reg].var_off))
  2588. reg_set_min_max(&other_branch->regs[insn->dst_reg],
  2589. dst_reg, regs[insn->src_reg].var_off.value,
  2590. opcode);
  2591. else if (tnum_is_const(dst_reg->var_off))
  2592. reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
  2593. &regs[insn->src_reg],
  2594. dst_reg->var_off.value, opcode);
  2595. else if (opcode == BPF_JEQ || opcode == BPF_JNE)
  2596. /* Comparing for equality, we can combine knowledge */
  2597. reg_combine_min_max(&other_branch->regs[insn->src_reg],
  2598. &other_branch->regs[insn->dst_reg],
  2599. &regs[insn->src_reg],
  2600. &regs[insn->dst_reg], opcode);
  2601. }
  2602. } else if (dst_reg->type == SCALAR_VALUE) {
  2603. reg_set_min_max(&other_branch->regs[insn->dst_reg],
  2604. dst_reg, insn->imm, opcode);
  2605. }
  2606. /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
  2607. if (BPF_SRC(insn->code) == BPF_K &&
  2608. insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  2609. dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  2610. /* Mark all identical map registers in each branch as either
  2611. * safe or unknown depending R == 0 or R != 0 conditional.
  2612. */
  2613. mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
  2614. mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
  2615. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
  2616. dst_reg->type == PTR_TO_PACKET &&
  2617. regs[insn->src_reg].type == PTR_TO_PACKET_END) {
  2618. find_good_pkt_pointers(this_branch, dst_reg);
  2619. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
  2620. dst_reg->type == PTR_TO_PACKET &&
  2621. regs[insn->src_reg].type == PTR_TO_PACKET_END) {
  2622. find_good_pkt_pointers(other_branch, dst_reg);
  2623. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
  2624. dst_reg->type == PTR_TO_PACKET_END &&
  2625. regs[insn->src_reg].type == PTR_TO_PACKET) {
  2626. find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
  2627. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
  2628. dst_reg->type == PTR_TO_PACKET_END &&
  2629. regs[insn->src_reg].type == PTR_TO_PACKET) {
  2630. find_good_pkt_pointers(this_branch, &regs[insn->src_reg]);
  2631. } else if (is_pointer_value(env, insn->dst_reg)) {
  2632. verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
  2633. return -EACCES;
  2634. }
  2635. if (log_level)
  2636. print_verifier_state(this_branch);
  2637. return 0;
  2638. }
  2639. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  2640. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  2641. {
  2642. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  2643. return (struct bpf_map *) (unsigned long) imm64;
  2644. }
  2645. /* verify BPF_LD_IMM64 instruction */
  2646. static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2647. {
  2648. struct bpf_reg_state *regs = env->cur_state.regs;
  2649. int err;
  2650. if (BPF_SIZE(insn->code) != BPF_DW) {
  2651. verbose("invalid BPF_LD_IMM insn\n");
  2652. return -EINVAL;
  2653. }
  2654. if (insn->off != 0) {
  2655. verbose("BPF_LD_IMM64 uses reserved fields\n");
  2656. return -EINVAL;
  2657. }
  2658. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  2659. if (err)
  2660. return err;
  2661. if (insn->src_reg == 0) {
  2662. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  2663. regs[insn->dst_reg].type = SCALAR_VALUE;
  2664. __mark_reg_known(&regs[insn->dst_reg], imm);
  2665. return 0;
  2666. }
  2667. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  2668. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  2669. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  2670. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  2671. return 0;
  2672. }
  2673. static bool may_access_skb(enum bpf_prog_type type)
  2674. {
  2675. switch (type) {
  2676. case BPF_PROG_TYPE_SOCKET_FILTER:
  2677. case BPF_PROG_TYPE_SCHED_CLS:
  2678. case BPF_PROG_TYPE_SCHED_ACT:
  2679. return true;
  2680. default:
  2681. return false;
  2682. }
  2683. }
  2684. /* verify safety of LD_ABS|LD_IND instructions:
  2685. * - they can only appear in the programs where ctx == skb
  2686. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  2687. * preserve R6-R9, and store return value into R0
  2688. *
  2689. * Implicit input:
  2690. * ctx == skb == R6 == CTX
  2691. *
  2692. * Explicit input:
  2693. * SRC == any register
  2694. * IMM == 32-bit immediate
  2695. *
  2696. * Output:
  2697. * R0 - 8/16/32-bit skb data converted to cpu endianness
  2698. */
  2699. static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2700. {
  2701. struct bpf_reg_state *regs = env->cur_state.regs;
  2702. u8 mode = BPF_MODE(insn->code);
  2703. int i, err;
  2704. if (!may_access_skb(env->prog->type)) {
  2705. verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
  2706. return -EINVAL;
  2707. }
  2708. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  2709. BPF_SIZE(insn->code) == BPF_DW ||
  2710. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  2711. verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
  2712. return -EINVAL;
  2713. }
  2714. /* check whether implicit source operand (register R6) is readable */
  2715. err = check_reg_arg(env, BPF_REG_6, SRC_OP);
  2716. if (err)
  2717. return err;
  2718. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  2719. verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  2720. return -EINVAL;
  2721. }
  2722. if (mode == BPF_IND) {
  2723. /* check explicit source operand */
  2724. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  2725. if (err)
  2726. return err;
  2727. }
  2728. /* reset caller saved regs to unreadable */
  2729. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  2730. mark_reg_not_init(regs, caller_saved[i]);
  2731. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  2732. }
  2733. /* mark destination R0 register as readable, since it contains
  2734. * the value fetched from the packet.
  2735. * Already marked as written above.
  2736. */
  2737. mark_reg_unknown(regs, BPF_REG_0);
  2738. return 0;
  2739. }
  2740. /* non-recursive DFS pseudo code
  2741. * 1 procedure DFS-iterative(G,v):
  2742. * 2 label v as discovered
  2743. * 3 let S be a stack
  2744. * 4 S.push(v)
  2745. * 5 while S is not empty
  2746. * 6 t <- S.pop()
  2747. * 7 if t is what we're looking for:
  2748. * 8 return t
  2749. * 9 for all edges e in G.adjacentEdges(t) do
  2750. * 10 if edge e is already labelled
  2751. * 11 continue with the next edge
  2752. * 12 w <- G.adjacentVertex(t,e)
  2753. * 13 if vertex w is not discovered and not explored
  2754. * 14 label e as tree-edge
  2755. * 15 label w as discovered
  2756. * 16 S.push(w)
  2757. * 17 continue at 5
  2758. * 18 else if vertex w is discovered
  2759. * 19 label e as back-edge
  2760. * 20 else
  2761. * 21 // vertex w is explored
  2762. * 22 label e as forward- or cross-edge
  2763. * 23 label t as explored
  2764. * 24 S.pop()
  2765. *
  2766. * convention:
  2767. * 0x10 - discovered
  2768. * 0x11 - discovered and fall-through edge labelled
  2769. * 0x12 - discovered and fall-through and branch edges labelled
  2770. * 0x20 - explored
  2771. */
  2772. enum {
  2773. DISCOVERED = 0x10,
  2774. EXPLORED = 0x20,
  2775. FALLTHROUGH = 1,
  2776. BRANCH = 2,
  2777. };
  2778. #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
  2779. static int *insn_stack; /* stack of insns to process */
  2780. static int cur_stack; /* current stack index */
  2781. static int *insn_state;
  2782. /* t, w, e - match pseudo-code above:
  2783. * t - index of current instruction
  2784. * w - next instruction
  2785. * e - edge
  2786. */
  2787. static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
  2788. {
  2789. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  2790. return 0;
  2791. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  2792. return 0;
  2793. if (w < 0 || w >= env->prog->len) {
  2794. verbose("jump out of range from insn %d to %d\n", t, w);
  2795. return -EINVAL;
  2796. }
  2797. if (e == BRANCH)
  2798. /* mark branch target for state pruning */
  2799. env->explored_states[w] = STATE_LIST_MARK;
  2800. if (insn_state[w] == 0) {
  2801. /* tree-edge */
  2802. insn_state[t] = DISCOVERED | e;
  2803. insn_state[w] = DISCOVERED;
  2804. if (cur_stack >= env->prog->len)
  2805. return -E2BIG;
  2806. insn_stack[cur_stack++] = w;
  2807. return 1;
  2808. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  2809. verbose("back-edge from insn %d to %d\n", t, w);
  2810. return -EINVAL;
  2811. } else if (insn_state[w] == EXPLORED) {
  2812. /* forward- or cross-edge */
  2813. insn_state[t] = DISCOVERED | e;
  2814. } else {
  2815. verbose("insn state internal bug\n");
  2816. return -EFAULT;
  2817. }
  2818. return 0;
  2819. }
  2820. /* non-recursive depth-first-search to detect loops in BPF program
  2821. * loop == back-edge in directed graph
  2822. */
  2823. static int check_cfg(struct bpf_verifier_env *env)
  2824. {
  2825. struct bpf_insn *insns = env->prog->insnsi;
  2826. int insn_cnt = env->prog->len;
  2827. int ret = 0;
  2828. int i, t;
  2829. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  2830. if (!insn_state)
  2831. return -ENOMEM;
  2832. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  2833. if (!insn_stack) {
  2834. kfree(insn_state);
  2835. return -ENOMEM;
  2836. }
  2837. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  2838. insn_stack[0] = 0; /* 0 is the first instruction */
  2839. cur_stack = 1;
  2840. peek_stack:
  2841. if (cur_stack == 0)
  2842. goto check_state;
  2843. t = insn_stack[cur_stack - 1];
  2844. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  2845. u8 opcode = BPF_OP(insns[t].code);
  2846. if (opcode == BPF_EXIT) {
  2847. goto mark_explored;
  2848. } else if (opcode == BPF_CALL) {
  2849. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2850. if (ret == 1)
  2851. goto peek_stack;
  2852. else if (ret < 0)
  2853. goto err_free;
  2854. if (t + 1 < insn_cnt)
  2855. env->explored_states[t + 1] = STATE_LIST_MARK;
  2856. } else if (opcode == BPF_JA) {
  2857. if (BPF_SRC(insns[t].code) != BPF_K) {
  2858. ret = -EINVAL;
  2859. goto err_free;
  2860. }
  2861. /* unconditional jump with single edge */
  2862. ret = push_insn(t, t + insns[t].off + 1,
  2863. FALLTHROUGH, env);
  2864. if (ret == 1)
  2865. goto peek_stack;
  2866. else if (ret < 0)
  2867. goto err_free;
  2868. /* tell verifier to check for equivalent states
  2869. * after every call and jump
  2870. */
  2871. if (t + 1 < insn_cnt)
  2872. env->explored_states[t + 1] = STATE_LIST_MARK;
  2873. } else {
  2874. /* conditional jump with two edges */
  2875. env->explored_states[t] = STATE_LIST_MARK;
  2876. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2877. if (ret == 1)
  2878. goto peek_stack;
  2879. else if (ret < 0)
  2880. goto err_free;
  2881. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  2882. if (ret == 1)
  2883. goto peek_stack;
  2884. else if (ret < 0)
  2885. goto err_free;
  2886. }
  2887. } else {
  2888. /* all other non-branch instructions with single
  2889. * fall-through edge
  2890. */
  2891. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2892. if (ret == 1)
  2893. goto peek_stack;
  2894. else if (ret < 0)
  2895. goto err_free;
  2896. }
  2897. mark_explored:
  2898. insn_state[t] = EXPLORED;
  2899. if (cur_stack-- <= 0) {
  2900. verbose("pop stack internal bug\n");
  2901. ret = -EFAULT;
  2902. goto err_free;
  2903. }
  2904. goto peek_stack;
  2905. check_state:
  2906. for (i = 0; i < insn_cnt; i++) {
  2907. if (insn_state[i] != EXPLORED) {
  2908. verbose("unreachable insn %d\n", i);
  2909. ret = -EINVAL;
  2910. goto err_free;
  2911. }
  2912. }
  2913. ret = 0; /* cfg looks good */
  2914. err_free:
  2915. kfree(insn_state);
  2916. kfree(insn_stack);
  2917. return ret;
  2918. }
  2919. /* check %cur's range satisfies %old's */
  2920. static bool range_within(struct bpf_reg_state *old,
  2921. struct bpf_reg_state *cur)
  2922. {
  2923. return old->umin_value <= cur->umin_value &&
  2924. old->umax_value >= cur->umax_value &&
  2925. old->smin_value <= cur->smin_value &&
  2926. old->smax_value >= cur->smax_value;
  2927. }
  2928. /* Maximum number of register states that can exist at once */
  2929. #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
  2930. struct idpair {
  2931. u32 old;
  2932. u32 cur;
  2933. };
  2934. /* If in the old state two registers had the same id, then they need to have
  2935. * the same id in the new state as well. But that id could be different from
  2936. * the old state, so we need to track the mapping from old to new ids.
  2937. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
  2938. * regs with old id 5 must also have new id 9 for the new state to be safe. But
  2939. * regs with a different old id could still have new id 9, we don't care about
  2940. * that.
  2941. * So we look through our idmap to see if this old id has been seen before. If
  2942. * so, we require the new id to match; otherwise, we add the id pair to the map.
  2943. */
  2944. static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
  2945. {
  2946. unsigned int i;
  2947. for (i = 0; i < ID_MAP_SIZE; i++) {
  2948. if (!idmap[i].old) {
  2949. /* Reached an empty slot; haven't seen this id before */
  2950. idmap[i].old = old_id;
  2951. idmap[i].cur = cur_id;
  2952. return true;
  2953. }
  2954. if (idmap[i].old == old_id)
  2955. return idmap[i].cur == cur_id;
  2956. }
  2957. /* We ran out of idmap slots, which should be impossible */
  2958. WARN_ON_ONCE(1);
  2959. return false;
  2960. }
  2961. /* Returns true if (rold safe implies rcur safe) */
  2962. static bool regsafe(struct bpf_reg_state *rold,
  2963. struct bpf_reg_state *rcur,
  2964. bool varlen_map_access, struct idpair *idmap)
  2965. {
  2966. if (!(rold->live & REG_LIVE_READ))
  2967. /* explored state didn't use this */
  2968. return true;
  2969. if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
  2970. return true;
  2971. if (rold->type == NOT_INIT)
  2972. /* explored state can't have used this */
  2973. return true;
  2974. if (rcur->type == NOT_INIT)
  2975. return false;
  2976. switch (rold->type) {
  2977. case SCALAR_VALUE:
  2978. if (rcur->type == SCALAR_VALUE) {
  2979. /* new val must satisfy old val knowledge */
  2980. return range_within(rold, rcur) &&
  2981. tnum_in(rold->var_off, rcur->var_off);
  2982. } else {
  2983. /* if we knew anything about the old value, we're not
  2984. * equal, because we can't know anything about the
  2985. * scalar value of the pointer in the new value.
  2986. */
  2987. return rold->umin_value == 0 &&
  2988. rold->umax_value == U64_MAX &&
  2989. rold->smin_value == S64_MIN &&
  2990. rold->smax_value == S64_MAX &&
  2991. tnum_is_unknown(rold->var_off);
  2992. }
  2993. case PTR_TO_MAP_VALUE:
  2994. if (varlen_map_access) {
  2995. /* If the new min/max/var_off satisfy the old ones and
  2996. * everything else matches, we are OK.
  2997. * We don't care about the 'id' value, because nothing
  2998. * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
  2999. */
  3000. return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
  3001. range_within(rold, rcur) &&
  3002. tnum_in(rold->var_off, rcur->var_off);
  3003. } else {
  3004. /* If the ranges/var_off were not the same, but
  3005. * everything else was and we didn't do a variable
  3006. * access into a map then we are a-ok.
  3007. */
  3008. return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0;
  3009. }
  3010. case PTR_TO_MAP_VALUE_OR_NULL:
  3011. /* a PTR_TO_MAP_VALUE could be safe to use as a
  3012. * PTR_TO_MAP_VALUE_OR_NULL into the same map.
  3013. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
  3014. * checked, doing so could have affected others with the same
  3015. * id, and we can't check for that because we lost the id when
  3016. * we converted to a PTR_TO_MAP_VALUE.
  3017. */
  3018. if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
  3019. return false;
  3020. if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
  3021. return false;
  3022. /* Check our ids match any regs they're supposed to */
  3023. return check_ids(rold->id, rcur->id, idmap);
  3024. case PTR_TO_PACKET:
  3025. if (rcur->type != PTR_TO_PACKET)
  3026. return false;
  3027. /* We must have at least as much range as the old ptr
  3028. * did, so that any accesses which were safe before are
  3029. * still safe. This is true even if old range < old off,
  3030. * since someone could have accessed through (ptr - k), or
  3031. * even done ptr -= k in a register, to get a safe access.
  3032. */
  3033. if (rold->range > rcur->range)
  3034. return false;
  3035. /* If the offsets don't match, we can't trust our alignment;
  3036. * nor can we be sure that we won't fall out of range.
  3037. */
  3038. if (rold->off != rcur->off)
  3039. return false;
  3040. /* id relations must be preserved */
  3041. if (rold->id && !check_ids(rold->id, rcur->id, idmap))
  3042. return false;
  3043. /* new val must satisfy old val knowledge */
  3044. return range_within(rold, rcur) &&
  3045. tnum_in(rold->var_off, rcur->var_off);
  3046. case PTR_TO_CTX:
  3047. case CONST_PTR_TO_MAP:
  3048. case PTR_TO_STACK:
  3049. case PTR_TO_PACKET_END:
  3050. /* Only valid matches are exact, which memcmp() above
  3051. * would have accepted
  3052. */
  3053. default:
  3054. /* Don't know what's going on, just say it's not safe */
  3055. return false;
  3056. }
  3057. /* Shouldn't get here; if we do, say it's not safe */
  3058. WARN_ON_ONCE(1);
  3059. return false;
  3060. }
  3061. /* compare two verifier states
  3062. *
  3063. * all states stored in state_list are known to be valid, since
  3064. * verifier reached 'bpf_exit' instruction through them
  3065. *
  3066. * this function is called when verifier exploring different branches of
  3067. * execution popped from the state stack. If it sees an old state that has
  3068. * more strict register state and more strict stack state then this execution
  3069. * branch doesn't need to be explored further, since verifier already
  3070. * concluded that more strict state leads to valid finish.
  3071. *
  3072. * Therefore two states are equivalent if register state is more conservative
  3073. * and explored stack state is more conservative than the current one.
  3074. * Example:
  3075. * explored current
  3076. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  3077. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  3078. *
  3079. * In other words if current stack state (one being explored) has more
  3080. * valid slots than old one that already passed validation, it means
  3081. * the verifier can stop exploring and conclude that current state is valid too
  3082. *
  3083. * Similarly with registers. If explored state has register type as invalid
  3084. * whereas register type in current state is meaningful, it means that
  3085. * the current state will reach 'bpf_exit' instruction safely
  3086. */
  3087. static bool states_equal(struct bpf_verifier_env *env,
  3088. struct bpf_verifier_state *old,
  3089. struct bpf_verifier_state *cur)
  3090. {
  3091. bool varlen_map_access = env->varlen_map_value_access;
  3092. struct idpair *idmap;
  3093. bool ret = false;
  3094. int i;
  3095. idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
  3096. /* If we failed to allocate the idmap, just say it's not safe */
  3097. if (!idmap)
  3098. return false;
  3099. for (i = 0; i < MAX_BPF_REG; i++) {
  3100. if (!regsafe(&old->regs[i], &cur->regs[i], varlen_map_access,
  3101. idmap))
  3102. goto out_free;
  3103. }
  3104. for (i = 0; i < MAX_BPF_STACK; i++) {
  3105. if (old->stack_slot_type[i] == STACK_INVALID)
  3106. continue;
  3107. if (old->stack_slot_type[i] != cur->stack_slot_type[i])
  3108. /* Ex: old explored (safe) state has STACK_SPILL in
  3109. * this stack slot, but current has has STACK_MISC ->
  3110. * this verifier states are not equivalent,
  3111. * return false to continue verification of this path
  3112. */
  3113. goto out_free;
  3114. if (i % BPF_REG_SIZE)
  3115. continue;
  3116. if (old->stack_slot_type[i] != STACK_SPILL)
  3117. continue;
  3118. if (!regsafe(&old->spilled_regs[i / BPF_REG_SIZE],
  3119. &cur->spilled_regs[i / BPF_REG_SIZE],
  3120. varlen_map_access, idmap))
  3121. /* when explored and current stack slot are both storing
  3122. * spilled registers, check that stored pointers types
  3123. * are the same as well.
  3124. * Ex: explored safe path could have stored
  3125. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
  3126. * but current path has stored:
  3127. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
  3128. * such verifier states are not equivalent.
  3129. * return false to continue verification of this path
  3130. */
  3131. goto out_free;
  3132. else
  3133. continue;
  3134. }
  3135. ret = true;
  3136. out_free:
  3137. kfree(idmap);
  3138. return ret;
  3139. }
  3140. static bool do_propagate_liveness(const struct bpf_verifier_state *state,
  3141. struct bpf_verifier_state *parent)
  3142. {
  3143. bool touched = false; /* any changes made? */
  3144. int i;
  3145. if (!parent)
  3146. return touched;
  3147. /* Propagate read liveness of registers... */
  3148. BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
  3149. /* We don't need to worry about FP liveness because it's read-only */
  3150. for (i = 0; i < BPF_REG_FP; i++) {
  3151. if (parent->regs[i].live & REG_LIVE_READ)
  3152. continue;
  3153. if (state->regs[i].live == REG_LIVE_READ) {
  3154. parent->regs[i].live |= REG_LIVE_READ;
  3155. touched = true;
  3156. }
  3157. }
  3158. /* ... and stack slots */
  3159. for (i = 0; i < MAX_BPF_STACK / BPF_REG_SIZE; i++) {
  3160. if (parent->stack_slot_type[i * BPF_REG_SIZE] != STACK_SPILL)
  3161. continue;
  3162. if (state->stack_slot_type[i * BPF_REG_SIZE] != STACK_SPILL)
  3163. continue;
  3164. if (parent->spilled_regs[i].live & REG_LIVE_READ)
  3165. continue;
  3166. if (state->spilled_regs[i].live == REG_LIVE_READ) {
  3167. parent->regs[i].live |= REG_LIVE_READ;
  3168. touched = true;
  3169. }
  3170. }
  3171. return touched;
  3172. }
  3173. static void propagate_liveness(const struct bpf_verifier_state *state,
  3174. struct bpf_verifier_state *parent)
  3175. {
  3176. while (do_propagate_liveness(state, parent)) {
  3177. /* Something changed, so we need to feed those changes onward */
  3178. state = parent;
  3179. parent = state->parent;
  3180. }
  3181. }
  3182. static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
  3183. {
  3184. struct bpf_verifier_state_list *new_sl;
  3185. struct bpf_verifier_state_list *sl;
  3186. int i;
  3187. sl = env->explored_states[insn_idx];
  3188. if (!sl)
  3189. /* this 'insn_idx' instruction wasn't marked, so we will not
  3190. * be doing state search here
  3191. */
  3192. return 0;
  3193. while (sl != STATE_LIST_MARK) {
  3194. if (states_equal(env, &sl->state, &env->cur_state)) {
  3195. /* reached equivalent register/stack state,
  3196. * prune the search.
  3197. * Registers read by the continuation are read by us.
  3198. */
  3199. propagate_liveness(&sl->state, &env->cur_state);
  3200. return 1;
  3201. }
  3202. sl = sl->next;
  3203. }
  3204. /* there were no equivalent states, remember current one.
  3205. * technically the current state is not proven to be safe yet,
  3206. * but it will either reach bpf_exit (which means it's safe) or
  3207. * it will be rejected. Since there are no loops, we won't be
  3208. * seeing this 'insn_idx' instruction again on the way to bpf_exit
  3209. */
  3210. new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
  3211. if (!new_sl)
  3212. return -ENOMEM;
  3213. /* add new state to the head of linked list */
  3214. memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
  3215. new_sl->next = env->explored_states[insn_idx];
  3216. env->explored_states[insn_idx] = new_sl;
  3217. /* connect new state to parentage chain */
  3218. env->cur_state.parent = &new_sl->state;
  3219. /* clear liveness marks in current state */
  3220. for (i = 0; i < BPF_REG_FP; i++)
  3221. env->cur_state.regs[i].live = REG_LIVE_NONE;
  3222. for (i = 0; i < MAX_BPF_STACK / BPF_REG_SIZE; i++)
  3223. if (env->cur_state.stack_slot_type[i * BPF_REG_SIZE] == STACK_SPILL)
  3224. env->cur_state.spilled_regs[i].live = REG_LIVE_NONE;
  3225. return 0;
  3226. }
  3227. static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
  3228. int insn_idx, int prev_insn_idx)
  3229. {
  3230. if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
  3231. return 0;
  3232. return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
  3233. }
  3234. static int do_check(struct bpf_verifier_env *env)
  3235. {
  3236. struct bpf_verifier_state *state = &env->cur_state;
  3237. struct bpf_insn *insns = env->prog->insnsi;
  3238. struct bpf_reg_state *regs = state->regs;
  3239. int insn_cnt = env->prog->len;
  3240. int insn_idx, prev_insn_idx = 0;
  3241. int insn_processed = 0;
  3242. bool do_print_state = false;
  3243. init_reg_state(regs);
  3244. state->parent = NULL;
  3245. insn_idx = 0;
  3246. env->varlen_map_value_access = false;
  3247. for (;;) {
  3248. struct bpf_insn *insn;
  3249. u8 class;
  3250. int err;
  3251. if (insn_idx >= insn_cnt) {
  3252. verbose("invalid insn idx %d insn_cnt %d\n",
  3253. insn_idx, insn_cnt);
  3254. return -EFAULT;
  3255. }
  3256. insn = &insns[insn_idx];
  3257. class = BPF_CLASS(insn->code);
  3258. if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
  3259. verbose("BPF program is too large. Processed %d insn\n",
  3260. insn_processed);
  3261. return -E2BIG;
  3262. }
  3263. err = is_state_visited(env, insn_idx);
  3264. if (err < 0)
  3265. return err;
  3266. if (err == 1) {
  3267. /* found equivalent state, can prune the search */
  3268. if (log_level) {
  3269. if (do_print_state)
  3270. verbose("\nfrom %d to %d: safe\n",
  3271. prev_insn_idx, insn_idx);
  3272. else
  3273. verbose("%d: safe\n", insn_idx);
  3274. }
  3275. goto process_bpf_exit;
  3276. }
  3277. if (need_resched())
  3278. cond_resched();
  3279. if (log_level > 1 || (log_level && do_print_state)) {
  3280. if (log_level > 1)
  3281. verbose("%d:", insn_idx);
  3282. else
  3283. verbose("\nfrom %d to %d:",
  3284. prev_insn_idx, insn_idx);
  3285. print_verifier_state(&env->cur_state);
  3286. do_print_state = false;
  3287. }
  3288. if (log_level) {
  3289. verbose("%d: ", insn_idx);
  3290. print_bpf_insn(env, insn);
  3291. }
  3292. err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
  3293. if (err)
  3294. return err;
  3295. if (class == BPF_ALU || class == BPF_ALU64) {
  3296. err = check_alu_op(env, insn);
  3297. if (err)
  3298. return err;
  3299. } else if (class == BPF_LDX) {
  3300. enum bpf_reg_type *prev_src_type, src_reg_type;
  3301. /* check for reserved fields is already done */
  3302. /* check src operand */
  3303. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  3304. if (err)
  3305. return err;
  3306. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  3307. if (err)
  3308. return err;
  3309. src_reg_type = regs[insn->src_reg].type;
  3310. /* check that memory (src_reg + off) is readable,
  3311. * the state of dst_reg will be updated by this func
  3312. */
  3313. err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
  3314. BPF_SIZE(insn->code), BPF_READ,
  3315. insn->dst_reg);
  3316. if (err)
  3317. return err;
  3318. prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
  3319. if (*prev_src_type == NOT_INIT) {
  3320. /* saw a valid insn
  3321. * dst_reg = *(u32 *)(src_reg + off)
  3322. * save type to validate intersecting paths
  3323. */
  3324. *prev_src_type = src_reg_type;
  3325. } else if (src_reg_type != *prev_src_type &&
  3326. (src_reg_type == PTR_TO_CTX ||
  3327. *prev_src_type == PTR_TO_CTX)) {
  3328. /* ABuser program is trying to use the same insn
  3329. * dst_reg = *(u32*) (src_reg + off)
  3330. * with different pointer types:
  3331. * src_reg == ctx in one branch and
  3332. * src_reg == stack|map in some other branch.
  3333. * Reject it.
  3334. */
  3335. verbose("same insn cannot be used with different pointers\n");
  3336. return -EINVAL;
  3337. }
  3338. } else if (class == BPF_STX) {
  3339. enum bpf_reg_type *prev_dst_type, dst_reg_type;
  3340. if (BPF_MODE(insn->code) == BPF_XADD) {
  3341. err = check_xadd(env, insn_idx, insn);
  3342. if (err)
  3343. return err;
  3344. insn_idx++;
  3345. continue;
  3346. }
  3347. /* check src1 operand */
  3348. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  3349. if (err)
  3350. return err;
  3351. /* check src2 operand */
  3352. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  3353. if (err)
  3354. return err;
  3355. dst_reg_type = regs[insn->dst_reg].type;
  3356. /* check that memory (dst_reg + off) is writeable */
  3357. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  3358. BPF_SIZE(insn->code), BPF_WRITE,
  3359. insn->src_reg);
  3360. if (err)
  3361. return err;
  3362. prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
  3363. if (*prev_dst_type == NOT_INIT) {
  3364. *prev_dst_type = dst_reg_type;
  3365. } else if (dst_reg_type != *prev_dst_type &&
  3366. (dst_reg_type == PTR_TO_CTX ||
  3367. *prev_dst_type == PTR_TO_CTX)) {
  3368. verbose("same insn cannot be used with different pointers\n");
  3369. return -EINVAL;
  3370. }
  3371. } else if (class == BPF_ST) {
  3372. if (BPF_MODE(insn->code) != BPF_MEM ||
  3373. insn->src_reg != BPF_REG_0) {
  3374. verbose("BPF_ST uses reserved fields\n");
  3375. return -EINVAL;
  3376. }
  3377. /* check src operand */
  3378. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  3379. if (err)
  3380. return err;
  3381. /* check that memory (dst_reg + off) is writeable */
  3382. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  3383. BPF_SIZE(insn->code), BPF_WRITE,
  3384. -1);
  3385. if (err)
  3386. return err;
  3387. } else if (class == BPF_JMP) {
  3388. u8 opcode = BPF_OP(insn->code);
  3389. if (opcode == BPF_CALL) {
  3390. if (BPF_SRC(insn->code) != BPF_K ||
  3391. insn->off != 0 ||
  3392. insn->src_reg != BPF_REG_0 ||
  3393. insn->dst_reg != BPF_REG_0) {
  3394. verbose("BPF_CALL uses reserved fields\n");
  3395. return -EINVAL;
  3396. }
  3397. err = check_call(env, insn->imm, insn_idx);
  3398. if (err)
  3399. return err;
  3400. } else if (opcode == BPF_JA) {
  3401. if (BPF_SRC(insn->code) != BPF_K ||
  3402. insn->imm != 0 ||
  3403. insn->src_reg != BPF_REG_0 ||
  3404. insn->dst_reg != BPF_REG_0) {
  3405. verbose("BPF_JA uses reserved fields\n");
  3406. return -EINVAL;
  3407. }
  3408. insn_idx += insn->off + 1;
  3409. continue;
  3410. } else if (opcode == BPF_EXIT) {
  3411. if (BPF_SRC(insn->code) != BPF_K ||
  3412. insn->imm != 0 ||
  3413. insn->src_reg != BPF_REG_0 ||
  3414. insn->dst_reg != BPF_REG_0) {
  3415. verbose("BPF_EXIT uses reserved fields\n");
  3416. return -EINVAL;
  3417. }
  3418. /* eBPF calling convetion is such that R0 is used
  3419. * to return the value from eBPF program.
  3420. * Make sure that it's readable at this time
  3421. * of bpf_exit, which means that program wrote
  3422. * something into it earlier
  3423. */
  3424. err = check_reg_arg(env, BPF_REG_0, SRC_OP);
  3425. if (err)
  3426. return err;
  3427. if (is_pointer_value(env, BPF_REG_0)) {
  3428. verbose("R0 leaks addr as return value\n");
  3429. return -EACCES;
  3430. }
  3431. process_bpf_exit:
  3432. insn_idx = pop_stack(env, &prev_insn_idx);
  3433. if (insn_idx < 0) {
  3434. break;
  3435. } else {
  3436. do_print_state = true;
  3437. continue;
  3438. }
  3439. } else {
  3440. err = check_cond_jmp_op(env, insn, &insn_idx);
  3441. if (err)
  3442. return err;
  3443. }
  3444. } else if (class == BPF_LD) {
  3445. u8 mode = BPF_MODE(insn->code);
  3446. if (mode == BPF_ABS || mode == BPF_IND) {
  3447. err = check_ld_abs(env, insn);
  3448. if (err)
  3449. return err;
  3450. } else if (mode == BPF_IMM) {
  3451. err = check_ld_imm(env, insn);
  3452. if (err)
  3453. return err;
  3454. insn_idx++;
  3455. } else {
  3456. verbose("invalid BPF_LD mode\n");
  3457. return -EINVAL;
  3458. }
  3459. } else {
  3460. verbose("unknown insn class %d\n", class);
  3461. return -EINVAL;
  3462. }
  3463. insn_idx++;
  3464. }
  3465. verbose("processed %d insns, stack depth %d\n",
  3466. insn_processed, env->prog->aux->stack_depth);
  3467. return 0;
  3468. }
  3469. static int check_map_prealloc(struct bpf_map *map)
  3470. {
  3471. return (map->map_type != BPF_MAP_TYPE_HASH &&
  3472. map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
  3473. map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
  3474. !(map->map_flags & BPF_F_NO_PREALLOC);
  3475. }
  3476. static int check_map_prog_compatibility(struct bpf_map *map,
  3477. struct bpf_prog *prog)
  3478. {
  3479. /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
  3480. * preallocated hash maps, since doing memory allocation
  3481. * in overflow_handler can crash depending on where nmi got
  3482. * triggered.
  3483. */
  3484. if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
  3485. if (!check_map_prealloc(map)) {
  3486. verbose("perf_event programs can only use preallocated hash map\n");
  3487. return -EINVAL;
  3488. }
  3489. if (map->inner_map_meta &&
  3490. !check_map_prealloc(map->inner_map_meta)) {
  3491. verbose("perf_event programs can only use preallocated inner hash map\n");
  3492. return -EINVAL;
  3493. }
  3494. }
  3495. return 0;
  3496. }
  3497. /* look for pseudo eBPF instructions that access map FDs and
  3498. * replace them with actual map pointers
  3499. */
  3500. static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
  3501. {
  3502. struct bpf_insn *insn = env->prog->insnsi;
  3503. int insn_cnt = env->prog->len;
  3504. int i, j, err;
  3505. err = bpf_prog_calc_tag(env->prog);
  3506. if (err)
  3507. return err;
  3508. for (i = 0; i < insn_cnt; i++, insn++) {
  3509. if (BPF_CLASS(insn->code) == BPF_LDX &&
  3510. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  3511. verbose("BPF_LDX uses reserved fields\n");
  3512. return -EINVAL;
  3513. }
  3514. if (BPF_CLASS(insn->code) == BPF_STX &&
  3515. ((BPF_MODE(insn->code) != BPF_MEM &&
  3516. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  3517. verbose("BPF_STX uses reserved fields\n");
  3518. return -EINVAL;
  3519. }
  3520. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  3521. struct bpf_map *map;
  3522. struct fd f;
  3523. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  3524. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  3525. insn[1].off != 0) {
  3526. verbose("invalid bpf_ld_imm64 insn\n");
  3527. return -EINVAL;
  3528. }
  3529. if (insn->src_reg == 0)
  3530. /* valid generic load 64-bit imm */
  3531. goto next_insn;
  3532. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  3533. verbose("unrecognized bpf_ld_imm64 insn\n");
  3534. return -EINVAL;
  3535. }
  3536. f = fdget(insn->imm);
  3537. map = __bpf_map_get(f);
  3538. if (IS_ERR(map)) {
  3539. verbose("fd %d is not pointing to valid bpf_map\n",
  3540. insn->imm);
  3541. return PTR_ERR(map);
  3542. }
  3543. err = check_map_prog_compatibility(map, env->prog);
  3544. if (err) {
  3545. fdput(f);
  3546. return err;
  3547. }
  3548. /* store map pointer inside BPF_LD_IMM64 instruction */
  3549. insn[0].imm = (u32) (unsigned long) map;
  3550. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  3551. /* check whether we recorded this map already */
  3552. for (j = 0; j < env->used_map_cnt; j++)
  3553. if (env->used_maps[j] == map) {
  3554. fdput(f);
  3555. goto next_insn;
  3556. }
  3557. if (env->used_map_cnt >= MAX_USED_MAPS) {
  3558. fdput(f);
  3559. return -E2BIG;
  3560. }
  3561. /* hold the map. If the program is rejected by verifier,
  3562. * the map will be released by release_maps() or it
  3563. * will be used by the valid program until it's unloaded
  3564. * and all maps are released in free_bpf_prog_info()
  3565. */
  3566. map = bpf_map_inc(map, false);
  3567. if (IS_ERR(map)) {
  3568. fdput(f);
  3569. return PTR_ERR(map);
  3570. }
  3571. env->used_maps[env->used_map_cnt++] = map;
  3572. fdput(f);
  3573. next_insn:
  3574. insn++;
  3575. i++;
  3576. }
  3577. }
  3578. /* now all pseudo BPF_LD_IMM64 instructions load valid
  3579. * 'struct bpf_map *' into a register instead of user map_fd.
  3580. * These pointers will be used later by verifier to validate map access.
  3581. */
  3582. return 0;
  3583. }
  3584. /* drop refcnt of maps used by the rejected program */
  3585. static void release_maps(struct bpf_verifier_env *env)
  3586. {
  3587. int i;
  3588. for (i = 0; i < env->used_map_cnt; i++)
  3589. bpf_map_put(env->used_maps[i]);
  3590. }
  3591. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  3592. static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
  3593. {
  3594. struct bpf_insn *insn = env->prog->insnsi;
  3595. int insn_cnt = env->prog->len;
  3596. int i;
  3597. for (i = 0; i < insn_cnt; i++, insn++)
  3598. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  3599. insn->src_reg = 0;
  3600. }
  3601. /* single env->prog->insni[off] instruction was replaced with the range
  3602. * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
  3603. * [0, off) and [off, end) to new locations, so the patched range stays zero
  3604. */
  3605. static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
  3606. u32 off, u32 cnt)
  3607. {
  3608. struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
  3609. if (cnt == 1)
  3610. return 0;
  3611. new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
  3612. if (!new_data)
  3613. return -ENOMEM;
  3614. memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
  3615. memcpy(new_data + off + cnt - 1, old_data + off,
  3616. sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
  3617. env->insn_aux_data = new_data;
  3618. vfree(old_data);
  3619. return 0;
  3620. }
  3621. static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
  3622. const struct bpf_insn *patch, u32 len)
  3623. {
  3624. struct bpf_prog *new_prog;
  3625. new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
  3626. if (!new_prog)
  3627. return NULL;
  3628. if (adjust_insn_aux_data(env, new_prog->len, off, len))
  3629. return NULL;
  3630. return new_prog;
  3631. }
  3632. /* convert load instructions that access fields of 'struct __sk_buff'
  3633. * into sequence of instructions that access fields of 'struct sk_buff'
  3634. */
  3635. static int convert_ctx_accesses(struct bpf_verifier_env *env)
  3636. {
  3637. const struct bpf_verifier_ops *ops = env->prog->aux->ops;
  3638. int i, cnt, size, ctx_field_size, delta = 0;
  3639. const int insn_cnt = env->prog->len;
  3640. struct bpf_insn insn_buf[16], *insn;
  3641. struct bpf_prog *new_prog;
  3642. enum bpf_access_type type;
  3643. bool is_narrower_load;
  3644. u32 target_size;
  3645. if (ops->gen_prologue) {
  3646. cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
  3647. env->prog);
  3648. if (cnt >= ARRAY_SIZE(insn_buf)) {
  3649. verbose("bpf verifier is misconfigured\n");
  3650. return -EINVAL;
  3651. } else if (cnt) {
  3652. new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
  3653. if (!new_prog)
  3654. return -ENOMEM;
  3655. env->prog = new_prog;
  3656. delta += cnt - 1;
  3657. }
  3658. }
  3659. if (!ops->convert_ctx_access)
  3660. return 0;
  3661. insn = env->prog->insnsi + delta;
  3662. for (i = 0; i < insn_cnt; i++, insn++) {
  3663. if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
  3664. insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
  3665. insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  3666. insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
  3667. type = BPF_READ;
  3668. else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
  3669. insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
  3670. insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  3671. insn->code == (BPF_STX | BPF_MEM | BPF_DW))
  3672. type = BPF_WRITE;
  3673. else
  3674. continue;
  3675. if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
  3676. continue;
  3677. ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
  3678. size = BPF_LDST_BYTES(insn);
  3679. /* If the read access is a narrower load of the field,
  3680. * convert to a 4/8-byte load, to minimum program type specific
  3681. * convert_ctx_access changes. If conversion is successful,
  3682. * we will apply proper mask to the result.
  3683. */
  3684. is_narrower_load = size < ctx_field_size;
  3685. if (is_narrower_load) {
  3686. u32 off = insn->off;
  3687. u8 size_code;
  3688. if (type == BPF_WRITE) {
  3689. verbose("bpf verifier narrow ctx access misconfigured\n");
  3690. return -EINVAL;
  3691. }
  3692. size_code = BPF_H;
  3693. if (ctx_field_size == 4)
  3694. size_code = BPF_W;
  3695. else if (ctx_field_size == 8)
  3696. size_code = BPF_DW;
  3697. insn->off = off & ~(ctx_field_size - 1);
  3698. insn->code = BPF_LDX | BPF_MEM | size_code;
  3699. }
  3700. target_size = 0;
  3701. cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
  3702. &target_size);
  3703. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
  3704. (ctx_field_size && !target_size)) {
  3705. verbose("bpf verifier is misconfigured\n");
  3706. return -EINVAL;
  3707. }
  3708. if (is_narrower_load && size < target_size) {
  3709. if (ctx_field_size <= 4)
  3710. insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
  3711. (1 << size * 8) - 1);
  3712. else
  3713. insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
  3714. (1 << size * 8) - 1);
  3715. }
  3716. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  3717. if (!new_prog)
  3718. return -ENOMEM;
  3719. delta += cnt - 1;
  3720. /* keep walking new program and skip insns we just inserted */
  3721. env->prog = new_prog;
  3722. insn = new_prog->insnsi + i + delta;
  3723. }
  3724. return 0;
  3725. }
  3726. /* fixup insn->imm field of bpf_call instructions
  3727. * and inline eligible helpers as explicit sequence of BPF instructions
  3728. *
  3729. * this function is called after eBPF program passed verification
  3730. */
  3731. static int fixup_bpf_calls(struct bpf_verifier_env *env)
  3732. {
  3733. struct bpf_prog *prog = env->prog;
  3734. struct bpf_insn *insn = prog->insnsi;
  3735. const struct bpf_func_proto *fn;
  3736. const int insn_cnt = prog->len;
  3737. struct bpf_insn insn_buf[16];
  3738. struct bpf_prog *new_prog;
  3739. struct bpf_map *map_ptr;
  3740. int i, cnt, delta = 0;
  3741. for (i = 0; i < insn_cnt; i++, insn++) {
  3742. if (insn->code != (BPF_JMP | BPF_CALL))
  3743. continue;
  3744. if (insn->imm == BPF_FUNC_get_route_realm)
  3745. prog->dst_needed = 1;
  3746. if (insn->imm == BPF_FUNC_get_prandom_u32)
  3747. bpf_user_rnd_init_once();
  3748. if (insn->imm == BPF_FUNC_tail_call) {
  3749. /* If we tail call into other programs, we
  3750. * cannot make any assumptions since they can
  3751. * be replaced dynamically during runtime in
  3752. * the program array.
  3753. */
  3754. prog->cb_access = 1;
  3755. env->prog->aux->stack_depth = MAX_BPF_STACK;
  3756. /* mark bpf_tail_call as different opcode to avoid
  3757. * conditional branch in the interpeter for every normal
  3758. * call and to prevent accidental JITing by JIT compiler
  3759. * that doesn't support bpf_tail_call yet
  3760. */
  3761. insn->imm = 0;
  3762. insn->code = BPF_JMP | BPF_TAIL_CALL;
  3763. continue;
  3764. }
  3765. if (ebpf_jit_enabled() && insn->imm == BPF_FUNC_map_lookup_elem) {
  3766. map_ptr = env->insn_aux_data[i + delta].map_ptr;
  3767. if (map_ptr == BPF_MAP_PTR_POISON ||
  3768. !map_ptr->ops->map_gen_lookup)
  3769. goto patch_call_imm;
  3770. cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
  3771. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  3772. verbose("bpf verifier is misconfigured\n");
  3773. return -EINVAL;
  3774. }
  3775. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
  3776. cnt);
  3777. if (!new_prog)
  3778. return -ENOMEM;
  3779. delta += cnt - 1;
  3780. /* keep walking new program and skip insns we just inserted */
  3781. env->prog = prog = new_prog;
  3782. insn = new_prog->insnsi + i + delta;
  3783. continue;
  3784. }
  3785. patch_call_imm:
  3786. fn = prog->aux->ops->get_func_proto(insn->imm);
  3787. /* all functions that have prototype and verifier allowed
  3788. * programs to call them, must be real in-kernel functions
  3789. */
  3790. if (!fn->func) {
  3791. verbose("kernel subsystem misconfigured func %s#%d\n",
  3792. func_id_name(insn->imm), insn->imm);
  3793. return -EFAULT;
  3794. }
  3795. insn->imm = fn->func - __bpf_call_base;
  3796. }
  3797. return 0;
  3798. }
  3799. static void free_states(struct bpf_verifier_env *env)
  3800. {
  3801. struct bpf_verifier_state_list *sl, *sln;
  3802. int i;
  3803. if (!env->explored_states)
  3804. return;
  3805. for (i = 0; i < env->prog->len; i++) {
  3806. sl = env->explored_states[i];
  3807. if (sl)
  3808. while (sl != STATE_LIST_MARK) {
  3809. sln = sl->next;
  3810. kfree(sl);
  3811. sl = sln;
  3812. }
  3813. }
  3814. kfree(env->explored_states);
  3815. }
  3816. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  3817. {
  3818. char __user *log_ubuf = NULL;
  3819. struct bpf_verifier_env *env;
  3820. int ret = -EINVAL;
  3821. /* 'struct bpf_verifier_env' can be global, but since it's not small,
  3822. * allocate/free it every time bpf_check() is called
  3823. */
  3824. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  3825. if (!env)
  3826. return -ENOMEM;
  3827. env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
  3828. (*prog)->len);
  3829. ret = -ENOMEM;
  3830. if (!env->insn_aux_data)
  3831. goto err_free_env;
  3832. env->prog = *prog;
  3833. /* grab the mutex to protect few globals used by verifier */
  3834. mutex_lock(&bpf_verifier_lock);
  3835. if (attr->log_level || attr->log_buf || attr->log_size) {
  3836. /* user requested verbose verifier output
  3837. * and supplied buffer to store the verification trace
  3838. */
  3839. log_level = attr->log_level;
  3840. log_ubuf = (char __user *) (unsigned long) attr->log_buf;
  3841. log_size = attr->log_size;
  3842. log_len = 0;
  3843. ret = -EINVAL;
  3844. /* log_* values have to be sane */
  3845. if (log_size < 128 || log_size > UINT_MAX >> 8 ||
  3846. log_level == 0 || log_ubuf == NULL)
  3847. goto err_unlock;
  3848. ret = -ENOMEM;
  3849. log_buf = vmalloc(log_size);
  3850. if (!log_buf)
  3851. goto err_unlock;
  3852. } else {
  3853. log_level = 0;
  3854. }
  3855. env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
  3856. if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
  3857. env->strict_alignment = true;
  3858. ret = replace_map_fd_with_map_ptr(env);
  3859. if (ret < 0)
  3860. goto skip_full_check;
  3861. env->explored_states = kcalloc(env->prog->len,
  3862. sizeof(struct bpf_verifier_state_list *),
  3863. GFP_USER);
  3864. ret = -ENOMEM;
  3865. if (!env->explored_states)
  3866. goto skip_full_check;
  3867. ret = check_cfg(env);
  3868. if (ret < 0)
  3869. goto skip_full_check;
  3870. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  3871. ret = do_check(env);
  3872. skip_full_check:
  3873. while (pop_stack(env, NULL) >= 0);
  3874. free_states(env);
  3875. if (ret == 0)
  3876. /* program is valid, convert *(u32*)(ctx + off) accesses */
  3877. ret = convert_ctx_accesses(env);
  3878. if (ret == 0)
  3879. ret = fixup_bpf_calls(env);
  3880. if (log_level && log_len >= log_size - 1) {
  3881. BUG_ON(log_len >= log_size);
  3882. /* verifier log exceeded user supplied buffer */
  3883. ret = -ENOSPC;
  3884. /* fall through to return what was recorded */
  3885. }
  3886. /* copy verifier log back to user space including trailing zero */
  3887. if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
  3888. ret = -EFAULT;
  3889. goto free_log_buf;
  3890. }
  3891. if (ret == 0 && env->used_map_cnt) {
  3892. /* if program passed verifier, update used_maps in bpf_prog_info */
  3893. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  3894. sizeof(env->used_maps[0]),
  3895. GFP_KERNEL);
  3896. if (!env->prog->aux->used_maps) {
  3897. ret = -ENOMEM;
  3898. goto free_log_buf;
  3899. }
  3900. memcpy(env->prog->aux->used_maps, env->used_maps,
  3901. sizeof(env->used_maps[0]) * env->used_map_cnt);
  3902. env->prog->aux->used_map_cnt = env->used_map_cnt;
  3903. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  3904. * bpf_ld_imm64 instructions
  3905. */
  3906. convert_pseudo_ld_imm64(env);
  3907. }
  3908. free_log_buf:
  3909. if (log_level)
  3910. vfree(log_buf);
  3911. if (!env->prog->aux->used_maps)
  3912. /* if we didn't copy map pointers into bpf_prog_info, release
  3913. * them now. Otherwise free_bpf_prog_info() will release them.
  3914. */
  3915. release_maps(env);
  3916. *prog = env->prog;
  3917. err_unlock:
  3918. mutex_unlock(&bpf_verifier_lock);
  3919. vfree(env->insn_aux_data);
  3920. err_free_env:
  3921. kfree(env);
  3922. return ret;
  3923. }
  3924. int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
  3925. void *priv)
  3926. {
  3927. struct bpf_verifier_env *env;
  3928. int ret;
  3929. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  3930. if (!env)
  3931. return -ENOMEM;
  3932. env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
  3933. prog->len);
  3934. ret = -ENOMEM;
  3935. if (!env->insn_aux_data)
  3936. goto err_free_env;
  3937. env->prog = prog;
  3938. env->analyzer_ops = ops;
  3939. env->analyzer_priv = priv;
  3940. /* grab the mutex to protect few globals used by verifier */
  3941. mutex_lock(&bpf_verifier_lock);
  3942. log_level = 0;
  3943. env->strict_alignment = false;
  3944. if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
  3945. env->strict_alignment = true;
  3946. env->explored_states = kcalloc(env->prog->len,
  3947. sizeof(struct bpf_verifier_state_list *),
  3948. GFP_KERNEL);
  3949. ret = -ENOMEM;
  3950. if (!env->explored_states)
  3951. goto skip_full_check;
  3952. ret = check_cfg(env);
  3953. if (ret < 0)
  3954. goto skip_full_check;
  3955. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  3956. ret = do_check(env);
  3957. skip_full_check:
  3958. while (pop_stack(env, NULL) >= 0);
  3959. free_states(env);
  3960. mutex_unlock(&bpf_verifier_lock);
  3961. vfree(env->insn_aux_data);
  3962. err_free_env:
  3963. kfree(env);
  3964. return ret;
  3965. }
  3966. EXPORT_SYMBOL_GPL(bpf_analyzer);