verifier.c 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047
  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. #include <linux/bsearch.h>
  24. #include <linux/sort.h>
  25. #include <linux/perf_event.h>
  26. #include "disasm.h"
  27. static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
  28. #define BPF_PROG_TYPE(_id, _name) \
  29. [_id] = & _name ## _verifier_ops,
  30. #define BPF_MAP_TYPE(_id, _ops)
  31. #include <linux/bpf_types.h>
  32. #undef BPF_PROG_TYPE
  33. #undef BPF_MAP_TYPE
  34. };
  35. /* bpf_check() is a static code analyzer that walks eBPF program
  36. * instruction by instruction and updates register/stack state.
  37. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  38. *
  39. * The first pass is depth-first-search to check that the program is a DAG.
  40. * It rejects the following programs:
  41. * - larger than BPF_MAXINSNS insns
  42. * - if loop is present (detected via back-edge)
  43. * - unreachable insns exist (shouldn't be a forest. program = one function)
  44. * - out of bounds or malformed jumps
  45. * The second pass is all possible path descent from the 1st insn.
  46. * Since it's analyzing all pathes through the program, the length of the
  47. * analysis is limited to 64k insn, which may be hit even if total number of
  48. * insn is less then 4K, but there are too many branches that change stack/regs.
  49. * Number of 'branches to be analyzed' is limited to 1k
  50. *
  51. * On entry to each instruction, each register has a type, and the instruction
  52. * changes the types of the registers depending on instruction semantics.
  53. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  54. * copied to R1.
  55. *
  56. * All registers are 64-bit.
  57. * R0 - return register
  58. * R1-R5 argument passing registers
  59. * R6-R9 callee saved registers
  60. * R10 - frame pointer read-only
  61. *
  62. * At the start of BPF program the register R1 contains a pointer to bpf_context
  63. * and has type PTR_TO_CTX.
  64. *
  65. * Verifier tracks arithmetic operations on pointers in case:
  66. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  67. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  68. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  69. * and 2nd arithmetic instruction is pattern matched to recognize
  70. * that it wants to construct a pointer to some element within stack.
  71. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  72. * (and -20 constant is saved for further stack bounds checking).
  73. * Meaning that this reg is a pointer to stack plus known immediate constant.
  74. *
  75. * Most of the time the registers have SCALAR_VALUE type, which
  76. * means the register has some value, but it's not a valid pointer.
  77. * (like pointer plus pointer becomes SCALAR_VALUE type)
  78. *
  79. * When verifier sees load or store instructions the type of base register
  80. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
  81. * types recognized by check_mem_access() function.
  82. *
  83. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  84. * and the range of [ptr, ptr + map's value_size) is accessible.
  85. *
  86. * registers used to pass values to function calls are checked against
  87. * function argument constraints.
  88. *
  89. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  90. * It means that the register type passed to this function must be
  91. * PTR_TO_STACK and it will be used inside the function as
  92. * 'pointer to map element key'
  93. *
  94. * For example the argument constraints for bpf_map_lookup_elem():
  95. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  96. * .arg1_type = ARG_CONST_MAP_PTR,
  97. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  98. *
  99. * ret_type says that this function returns 'pointer to map elem value or null'
  100. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  101. * 2nd argument should be a pointer to stack, which will be used inside
  102. * the helper function as a pointer to map element key.
  103. *
  104. * On the kernel side the helper function looks like:
  105. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  106. * {
  107. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  108. * void *key = (void *) (unsigned long) r2;
  109. * void *value;
  110. *
  111. * here kernel can access 'key' and 'map' pointers safely, knowing that
  112. * [key, key + map->key_size) bytes are valid and were initialized on
  113. * the stack of eBPF program.
  114. * }
  115. *
  116. * Corresponding eBPF program may look like:
  117. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  118. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  119. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  120. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  121. * here verifier looks at prototype of map_lookup_elem() and sees:
  122. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  123. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  124. *
  125. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  126. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  127. * and were initialized prior to this call.
  128. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  129. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  130. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  131. * returns ether pointer to map value or NULL.
  132. *
  133. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  134. * insn, the register holding that pointer in the true branch changes state to
  135. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  136. * branch. See check_cond_jmp_op().
  137. *
  138. * After the call R0 is set to return type of the function and registers R1-R5
  139. * are set to NOT_INIT to indicate that they are no longer readable.
  140. */
  141. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  142. struct bpf_verifier_stack_elem {
  143. /* verifer state is 'st'
  144. * before processing instruction 'insn_idx'
  145. * and after processing instruction 'prev_insn_idx'
  146. */
  147. struct bpf_verifier_state st;
  148. int insn_idx;
  149. int prev_insn_idx;
  150. struct bpf_verifier_stack_elem *next;
  151. };
  152. #define BPF_COMPLEXITY_LIMIT_INSNS 131072
  153. #define BPF_COMPLEXITY_LIMIT_STACK 1024
  154. #define BPF_MAP_PTR_UNPRIV 1UL
  155. #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
  156. POISON_POINTER_DELTA))
  157. #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
  158. static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
  159. {
  160. return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
  161. }
  162. static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
  163. {
  164. return aux->map_state & BPF_MAP_PTR_UNPRIV;
  165. }
  166. static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
  167. const struct bpf_map *map, bool unpriv)
  168. {
  169. BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
  170. unpriv |= bpf_map_ptr_unpriv(aux);
  171. aux->map_state = (unsigned long)map |
  172. (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
  173. }
  174. struct bpf_call_arg_meta {
  175. struct bpf_map *map_ptr;
  176. bool raw_mode;
  177. bool pkt_access;
  178. int regno;
  179. int access_size;
  180. s64 msize_smax_value;
  181. u64 msize_umax_value;
  182. };
  183. static DEFINE_MUTEX(bpf_verifier_lock);
  184. void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
  185. va_list args)
  186. {
  187. unsigned int n;
  188. n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
  189. WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
  190. "verifier log line truncated - local buffer too short\n");
  191. n = min(log->len_total - log->len_used - 1, n);
  192. log->kbuf[n] = '\0';
  193. if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
  194. log->len_used += n;
  195. else
  196. log->ubuf = NULL;
  197. }
  198. /* log_level controls verbosity level of eBPF verifier.
  199. * bpf_verifier_log_write() is used to dump the verification trace to the log,
  200. * so the user can figure out what's wrong with the program
  201. */
  202. __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
  203. const char *fmt, ...)
  204. {
  205. va_list args;
  206. if (!bpf_verifier_log_needed(&env->log))
  207. return;
  208. va_start(args, fmt);
  209. bpf_verifier_vlog(&env->log, fmt, args);
  210. va_end(args);
  211. }
  212. EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
  213. __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
  214. {
  215. struct bpf_verifier_env *env = private_data;
  216. va_list args;
  217. if (!bpf_verifier_log_needed(&env->log))
  218. return;
  219. va_start(args, fmt);
  220. bpf_verifier_vlog(&env->log, fmt, args);
  221. va_end(args);
  222. }
  223. static bool type_is_pkt_pointer(enum bpf_reg_type type)
  224. {
  225. return type == PTR_TO_PACKET ||
  226. type == PTR_TO_PACKET_META;
  227. }
  228. /* string representation of 'enum bpf_reg_type' */
  229. static const char * const reg_type_str[] = {
  230. [NOT_INIT] = "?",
  231. [SCALAR_VALUE] = "inv",
  232. [PTR_TO_CTX] = "ctx",
  233. [CONST_PTR_TO_MAP] = "map_ptr",
  234. [PTR_TO_MAP_VALUE] = "map_value",
  235. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  236. [PTR_TO_STACK] = "fp",
  237. [PTR_TO_PACKET] = "pkt",
  238. [PTR_TO_PACKET_META] = "pkt_meta",
  239. [PTR_TO_PACKET_END] = "pkt_end",
  240. };
  241. static void print_liveness(struct bpf_verifier_env *env,
  242. enum bpf_reg_liveness live)
  243. {
  244. if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
  245. verbose(env, "_");
  246. if (live & REG_LIVE_READ)
  247. verbose(env, "r");
  248. if (live & REG_LIVE_WRITTEN)
  249. verbose(env, "w");
  250. }
  251. static struct bpf_func_state *func(struct bpf_verifier_env *env,
  252. const struct bpf_reg_state *reg)
  253. {
  254. struct bpf_verifier_state *cur = env->cur_state;
  255. return cur->frame[reg->frameno];
  256. }
  257. static void print_verifier_state(struct bpf_verifier_env *env,
  258. const struct bpf_func_state *state)
  259. {
  260. const struct bpf_reg_state *reg;
  261. enum bpf_reg_type t;
  262. int i;
  263. if (state->frameno)
  264. verbose(env, " frame%d:", state->frameno);
  265. for (i = 0; i < MAX_BPF_REG; i++) {
  266. reg = &state->regs[i];
  267. t = reg->type;
  268. if (t == NOT_INIT)
  269. continue;
  270. verbose(env, " R%d", i);
  271. print_liveness(env, reg->live);
  272. verbose(env, "=%s", reg_type_str[t]);
  273. if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
  274. tnum_is_const(reg->var_off)) {
  275. /* reg->off should be 0 for SCALAR_VALUE */
  276. verbose(env, "%lld", reg->var_off.value + reg->off);
  277. if (t == PTR_TO_STACK)
  278. verbose(env, ",call_%d", func(env, reg)->callsite);
  279. } else {
  280. verbose(env, "(id=%d", reg->id);
  281. if (t != SCALAR_VALUE)
  282. verbose(env, ",off=%d", reg->off);
  283. if (type_is_pkt_pointer(t))
  284. verbose(env, ",r=%d", reg->range);
  285. else if (t == CONST_PTR_TO_MAP ||
  286. t == PTR_TO_MAP_VALUE ||
  287. t == PTR_TO_MAP_VALUE_OR_NULL)
  288. verbose(env, ",ks=%d,vs=%d",
  289. reg->map_ptr->key_size,
  290. reg->map_ptr->value_size);
  291. if (tnum_is_const(reg->var_off)) {
  292. /* Typically an immediate SCALAR_VALUE, but
  293. * could be a pointer whose offset is too big
  294. * for reg->off
  295. */
  296. verbose(env, ",imm=%llx", reg->var_off.value);
  297. } else {
  298. if (reg->smin_value != reg->umin_value &&
  299. reg->smin_value != S64_MIN)
  300. verbose(env, ",smin_value=%lld",
  301. (long long)reg->smin_value);
  302. if (reg->smax_value != reg->umax_value &&
  303. reg->smax_value != S64_MAX)
  304. verbose(env, ",smax_value=%lld",
  305. (long long)reg->smax_value);
  306. if (reg->umin_value != 0)
  307. verbose(env, ",umin_value=%llu",
  308. (unsigned long long)reg->umin_value);
  309. if (reg->umax_value != U64_MAX)
  310. verbose(env, ",umax_value=%llu",
  311. (unsigned long long)reg->umax_value);
  312. if (!tnum_is_unknown(reg->var_off)) {
  313. char tn_buf[48];
  314. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  315. verbose(env, ",var_off=%s", tn_buf);
  316. }
  317. }
  318. verbose(env, ")");
  319. }
  320. }
  321. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  322. if (state->stack[i].slot_type[0] == STACK_SPILL) {
  323. verbose(env, " fp%d",
  324. (-i - 1) * BPF_REG_SIZE);
  325. print_liveness(env, state->stack[i].spilled_ptr.live);
  326. verbose(env, "=%s",
  327. reg_type_str[state->stack[i].spilled_ptr.type]);
  328. }
  329. if (state->stack[i].slot_type[0] == STACK_ZERO)
  330. verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
  331. }
  332. verbose(env, "\n");
  333. }
  334. static int copy_stack_state(struct bpf_func_state *dst,
  335. const struct bpf_func_state *src)
  336. {
  337. if (!src->stack)
  338. return 0;
  339. if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
  340. /* internal bug, make state invalid to reject the program */
  341. memset(dst, 0, sizeof(*dst));
  342. return -EFAULT;
  343. }
  344. memcpy(dst->stack, src->stack,
  345. sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
  346. return 0;
  347. }
  348. /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
  349. * make it consume minimal amount of memory. check_stack_write() access from
  350. * the program calls into realloc_func_state() to grow the stack size.
  351. * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
  352. * which this function copies over. It points to previous bpf_verifier_state
  353. * which is never reallocated
  354. */
  355. static int realloc_func_state(struct bpf_func_state *state, int size,
  356. bool copy_old)
  357. {
  358. u32 old_size = state->allocated_stack;
  359. struct bpf_stack_state *new_stack;
  360. int slot = size / BPF_REG_SIZE;
  361. if (size <= old_size || !size) {
  362. if (copy_old)
  363. return 0;
  364. state->allocated_stack = slot * BPF_REG_SIZE;
  365. if (!size && old_size) {
  366. kfree(state->stack);
  367. state->stack = NULL;
  368. }
  369. return 0;
  370. }
  371. new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
  372. GFP_KERNEL);
  373. if (!new_stack)
  374. return -ENOMEM;
  375. if (copy_old) {
  376. if (state->stack)
  377. memcpy(new_stack, state->stack,
  378. sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
  379. memset(new_stack + old_size / BPF_REG_SIZE, 0,
  380. sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
  381. }
  382. state->allocated_stack = slot * BPF_REG_SIZE;
  383. kfree(state->stack);
  384. state->stack = new_stack;
  385. return 0;
  386. }
  387. static void free_func_state(struct bpf_func_state *state)
  388. {
  389. if (!state)
  390. return;
  391. kfree(state->stack);
  392. kfree(state);
  393. }
  394. static void free_verifier_state(struct bpf_verifier_state *state,
  395. bool free_self)
  396. {
  397. int i;
  398. for (i = 0; i <= state->curframe; i++) {
  399. free_func_state(state->frame[i]);
  400. state->frame[i] = NULL;
  401. }
  402. if (free_self)
  403. kfree(state);
  404. }
  405. /* copy verifier state from src to dst growing dst stack space
  406. * when necessary to accommodate larger src stack
  407. */
  408. static int copy_func_state(struct bpf_func_state *dst,
  409. const struct bpf_func_state *src)
  410. {
  411. int err;
  412. err = realloc_func_state(dst, src->allocated_stack, false);
  413. if (err)
  414. return err;
  415. memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
  416. return copy_stack_state(dst, src);
  417. }
  418. static int copy_verifier_state(struct bpf_verifier_state *dst_state,
  419. const struct bpf_verifier_state *src)
  420. {
  421. struct bpf_func_state *dst;
  422. int i, err;
  423. /* if dst has more stack frames then src frame, free them */
  424. for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
  425. free_func_state(dst_state->frame[i]);
  426. dst_state->frame[i] = NULL;
  427. }
  428. dst_state->curframe = src->curframe;
  429. dst_state->parent = src->parent;
  430. for (i = 0; i <= src->curframe; i++) {
  431. dst = dst_state->frame[i];
  432. if (!dst) {
  433. dst = kzalloc(sizeof(*dst), GFP_KERNEL);
  434. if (!dst)
  435. return -ENOMEM;
  436. dst_state->frame[i] = dst;
  437. }
  438. err = copy_func_state(dst, src->frame[i]);
  439. if (err)
  440. return err;
  441. }
  442. return 0;
  443. }
  444. static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
  445. int *insn_idx)
  446. {
  447. struct bpf_verifier_state *cur = env->cur_state;
  448. struct bpf_verifier_stack_elem *elem, *head = env->head;
  449. int err;
  450. if (env->head == NULL)
  451. return -ENOENT;
  452. if (cur) {
  453. err = copy_verifier_state(cur, &head->st);
  454. if (err)
  455. return err;
  456. }
  457. if (insn_idx)
  458. *insn_idx = head->insn_idx;
  459. if (prev_insn_idx)
  460. *prev_insn_idx = head->prev_insn_idx;
  461. elem = head->next;
  462. free_verifier_state(&head->st, false);
  463. kfree(head);
  464. env->head = elem;
  465. env->stack_size--;
  466. return 0;
  467. }
  468. static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
  469. int insn_idx, int prev_insn_idx)
  470. {
  471. struct bpf_verifier_state *cur = env->cur_state;
  472. struct bpf_verifier_stack_elem *elem;
  473. int err;
  474. elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
  475. if (!elem)
  476. goto err;
  477. elem->insn_idx = insn_idx;
  478. elem->prev_insn_idx = prev_insn_idx;
  479. elem->next = env->head;
  480. env->head = elem;
  481. env->stack_size++;
  482. err = copy_verifier_state(&elem->st, cur);
  483. if (err)
  484. goto err;
  485. if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
  486. verbose(env, "BPF program is too complex\n");
  487. goto err;
  488. }
  489. return &elem->st;
  490. err:
  491. free_verifier_state(env->cur_state, true);
  492. env->cur_state = NULL;
  493. /* pop all elements and return */
  494. while (!pop_stack(env, NULL, NULL));
  495. return NULL;
  496. }
  497. #define CALLER_SAVED_REGS 6
  498. static const int caller_saved[CALLER_SAVED_REGS] = {
  499. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  500. };
  501. static void __mark_reg_not_init(struct bpf_reg_state *reg);
  502. /* Mark the unknown part of a register (variable offset or scalar value) as
  503. * known to have the value @imm.
  504. */
  505. static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
  506. {
  507. reg->id = 0;
  508. reg->var_off = tnum_const(imm);
  509. reg->smin_value = (s64)imm;
  510. reg->smax_value = (s64)imm;
  511. reg->umin_value = imm;
  512. reg->umax_value = imm;
  513. }
  514. /* Mark the 'variable offset' part of a register as zero. This should be
  515. * used only on registers holding a pointer type.
  516. */
  517. static void __mark_reg_known_zero(struct bpf_reg_state *reg)
  518. {
  519. __mark_reg_known(reg, 0);
  520. }
  521. static void __mark_reg_const_zero(struct bpf_reg_state *reg)
  522. {
  523. __mark_reg_known(reg, 0);
  524. reg->off = 0;
  525. reg->type = SCALAR_VALUE;
  526. }
  527. static void mark_reg_known_zero(struct bpf_verifier_env *env,
  528. struct bpf_reg_state *regs, u32 regno)
  529. {
  530. if (WARN_ON(regno >= MAX_BPF_REG)) {
  531. verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
  532. /* Something bad happened, let's kill all regs */
  533. for (regno = 0; regno < MAX_BPF_REG; regno++)
  534. __mark_reg_not_init(regs + regno);
  535. return;
  536. }
  537. __mark_reg_known_zero(regs + regno);
  538. }
  539. static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
  540. {
  541. return type_is_pkt_pointer(reg->type);
  542. }
  543. static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
  544. {
  545. return reg_is_pkt_pointer(reg) ||
  546. reg->type == PTR_TO_PACKET_END;
  547. }
  548. /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
  549. static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
  550. enum bpf_reg_type which)
  551. {
  552. /* The register can already have a range from prior markings.
  553. * This is fine as long as it hasn't been advanced from its
  554. * origin.
  555. */
  556. return reg->type == which &&
  557. reg->id == 0 &&
  558. reg->off == 0 &&
  559. tnum_equals_const(reg->var_off, 0);
  560. }
  561. /* Attempts to improve min/max values based on var_off information */
  562. static void __update_reg_bounds(struct bpf_reg_state *reg)
  563. {
  564. /* min signed is max(sign bit) | min(other bits) */
  565. reg->smin_value = max_t(s64, reg->smin_value,
  566. reg->var_off.value | (reg->var_off.mask & S64_MIN));
  567. /* max signed is min(sign bit) | max(other bits) */
  568. reg->smax_value = min_t(s64, reg->smax_value,
  569. reg->var_off.value | (reg->var_off.mask & S64_MAX));
  570. reg->umin_value = max(reg->umin_value, reg->var_off.value);
  571. reg->umax_value = min(reg->umax_value,
  572. reg->var_off.value | reg->var_off.mask);
  573. }
  574. /* Uses signed min/max values to inform unsigned, and vice-versa */
  575. static void __reg_deduce_bounds(struct bpf_reg_state *reg)
  576. {
  577. /* Learn sign from signed bounds.
  578. * If we cannot cross the sign boundary, then signed and unsigned bounds
  579. * are the same, so combine. This works even in the negative case, e.g.
  580. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
  581. */
  582. if (reg->smin_value >= 0 || reg->smax_value < 0) {
  583. reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
  584. reg->umin_value);
  585. reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
  586. reg->umax_value);
  587. return;
  588. }
  589. /* Learn sign from unsigned bounds. Signed bounds cross the sign
  590. * boundary, so we must be careful.
  591. */
  592. if ((s64)reg->umax_value >= 0) {
  593. /* Positive. We can't learn anything from the smin, but smax
  594. * is positive, hence safe.
  595. */
  596. reg->smin_value = reg->umin_value;
  597. reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
  598. reg->umax_value);
  599. } else if ((s64)reg->umin_value < 0) {
  600. /* Negative. We can't learn anything from the smax, but smin
  601. * is negative, hence safe.
  602. */
  603. reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
  604. reg->umin_value);
  605. reg->smax_value = reg->umax_value;
  606. }
  607. }
  608. /* Attempts to improve var_off based on unsigned min/max information */
  609. static void __reg_bound_offset(struct bpf_reg_state *reg)
  610. {
  611. reg->var_off = tnum_intersect(reg->var_off,
  612. tnum_range(reg->umin_value,
  613. reg->umax_value));
  614. }
  615. /* Reset the min/max bounds of a register */
  616. static void __mark_reg_unbounded(struct bpf_reg_state *reg)
  617. {
  618. reg->smin_value = S64_MIN;
  619. reg->smax_value = S64_MAX;
  620. reg->umin_value = 0;
  621. reg->umax_value = U64_MAX;
  622. }
  623. /* Mark a register as having a completely unknown (scalar) value. */
  624. static void __mark_reg_unknown(struct bpf_reg_state *reg)
  625. {
  626. reg->type = SCALAR_VALUE;
  627. reg->id = 0;
  628. reg->off = 0;
  629. reg->var_off = tnum_unknown;
  630. reg->frameno = 0;
  631. __mark_reg_unbounded(reg);
  632. }
  633. static void mark_reg_unknown(struct bpf_verifier_env *env,
  634. struct bpf_reg_state *regs, u32 regno)
  635. {
  636. if (WARN_ON(regno >= MAX_BPF_REG)) {
  637. verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
  638. /* Something bad happened, let's kill all regs except FP */
  639. for (regno = 0; regno < BPF_REG_FP; regno++)
  640. __mark_reg_not_init(regs + regno);
  641. return;
  642. }
  643. __mark_reg_unknown(regs + regno);
  644. }
  645. static void __mark_reg_not_init(struct bpf_reg_state *reg)
  646. {
  647. __mark_reg_unknown(reg);
  648. reg->type = NOT_INIT;
  649. }
  650. static void mark_reg_not_init(struct bpf_verifier_env *env,
  651. struct bpf_reg_state *regs, u32 regno)
  652. {
  653. if (WARN_ON(regno >= MAX_BPF_REG)) {
  654. verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
  655. /* Something bad happened, let's kill all regs except FP */
  656. for (regno = 0; regno < BPF_REG_FP; regno++)
  657. __mark_reg_not_init(regs + regno);
  658. return;
  659. }
  660. __mark_reg_not_init(regs + regno);
  661. }
  662. static void init_reg_state(struct bpf_verifier_env *env,
  663. struct bpf_func_state *state)
  664. {
  665. struct bpf_reg_state *regs = state->regs;
  666. int i;
  667. for (i = 0; i < MAX_BPF_REG; i++) {
  668. mark_reg_not_init(env, regs, i);
  669. regs[i].live = REG_LIVE_NONE;
  670. }
  671. /* frame pointer */
  672. regs[BPF_REG_FP].type = PTR_TO_STACK;
  673. mark_reg_known_zero(env, regs, BPF_REG_FP);
  674. regs[BPF_REG_FP].frameno = state->frameno;
  675. /* 1st arg to a function */
  676. regs[BPF_REG_1].type = PTR_TO_CTX;
  677. mark_reg_known_zero(env, regs, BPF_REG_1);
  678. }
  679. #define BPF_MAIN_FUNC (-1)
  680. static void init_func_state(struct bpf_verifier_env *env,
  681. struct bpf_func_state *state,
  682. int callsite, int frameno, int subprogno)
  683. {
  684. state->callsite = callsite;
  685. state->frameno = frameno;
  686. state->subprogno = subprogno;
  687. init_reg_state(env, state);
  688. }
  689. enum reg_arg_type {
  690. SRC_OP, /* register is used as source operand */
  691. DST_OP, /* register is used as destination operand */
  692. DST_OP_NO_MARK /* same as above, check only, don't mark */
  693. };
  694. static int cmp_subprogs(const void *a, const void *b)
  695. {
  696. return ((struct bpf_subprog_info *)a)->start -
  697. ((struct bpf_subprog_info *)b)->start;
  698. }
  699. static int find_subprog(struct bpf_verifier_env *env, int off)
  700. {
  701. struct bpf_subprog_info *p;
  702. p = bsearch(&off, env->subprog_info, env->subprog_cnt,
  703. sizeof(env->subprog_info[0]), cmp_subprogs);
  704. if (!p)
  705. return -ENOENT;
  706. return p - env->subprog_info;
  707. }
  708. static int add_subprog(struct bpf_verifier_env *env, int off)
  709. {
  710. int insn_cnt = env->prog->len;
  711. int ret;
  712. if (off >= insn_cnt || off < 0) {
  713. verbose(env, "call to invalid destination\n");
  714. return -EINVAL;
  715. }
  716. ret = find_subprog(env, off);
  717. if (ret >= 0)
  718. return 0;
  719. if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
  720. verbose(env, "too many subprograms\n");
  721. return -E2BIG;
  722. }
  723. env->subprog_info[env->subprog_cnt++].start = off;
  724. sort(env->subprog_info, env->subprog_cnt,
  725. sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
  726. return 0;
  727. }
  728. static int check_subprogs(struct bpf_verifier_env *env)
  729. {
  730. int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
  731. struct bpf_subprog_info *subprog = env->subprog_info;
  732. struct bpf_insn *insn = env->prog->insnsi;
  733. int insn_cnt = env->prog->len;
  734. /* Add entry function. */
  735. ret = add_subprog(env, 0);
  736. if (ret < 0)
  737. return ret;
  738. /* determine subprog starts. The end is one before the next starts */
  739. for (i = 0; i < insn_cnt; i++) {
  740. if (insn[i].code != (BPF_JMP | BPF_CALL))
  741. continue;
  742. if (insn[i].src_reg != BPF_PSEUDO_CALL)
  743. continue;
  744. if (!env->allow_ptr_leaks) {
  745. verbose(env, "function calls to other bpf functions are allowed for root only\n");
  746. return -EPERM;
  747. }
  748. if (bpf_prog_is_dev_bound(env->prog->aux)) {
  749. verbose(env, "function calls in offloaded programs are not supported yet\n");
  750. return -EINVAL;
  751. }
  752. ret = add_subprog(env, i + insn[i].imm + 1);
  753. if (ret < 0)
  754. return ret;
  755. }
  756. /* Add a fake 'exit' subprog which could simplify subprog iteration
  757. * logic. 'subprog_cnt' should not be increased.
  758. */
  759. subprog[env->subprog_cnt].start = insn_cnt;
  760. if (env->log.level > 1)
  761. for (i = 0; i < env->subprog_cnt; i++)
  762. verbose(env, "func#%d @%d\n", i, subprog[i].start);
  763. /* now check that all jumps are within the same subprog */
  764. subprog_start = subprog[cur_subprog].start;
  765. subprog_end = subprog[cur_subprog + 1].start;
  766. for (i = 0; i < insn_cnt; i++) {
  767. u8 code = insn[i].code;
  768. if (BPF_CLASS(code) != BPF_JMP)
  769. goto next;
  770. if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
  771. goto next;
  772. off = i + insn[i].off + 1;
  773. if (off < subprog_start || off >= subprog_end) {
  774. verbose(env, "jump out of range from insn %d to %d\n", i, off);
  775. return -EINVAL;
  776. }
  777. next:
  778. if (i == subprog_end - 1) {
  779. /* to avoid fall-through from one subprog into another
  780. * the last insn of the subprog should be either exit
  781. * or unconditional jump back
  782. */
  783. if (code != (BPF_JMP | BPF_EXIT) &&
  784. code != (BPF_JMP | BPF_JA)) {
  785. verbose(env, "last insn is not an exit or jmp\n");
  786. return -EINVAL;
  787. }
  788. subprog_start = subprog_end;
  789. cur_subprog++;
  790. if (cur_subprog < env->subprog_cnt)
  791. subprog_end = subprog[cur_subprog + 1].start;
  792. }
  793. }
  794. return 0;
  795. }
  796. static
  797. struct bpf_verifier_state *skip_callee(struct bpf_verifier_env *env,
  798. const struct bpf_verifier_state *state,
  799. struct bpf_verifier_state *parent,
  800. u32 regno)
  801. {
  802. struct bpf_verifier_state *tmp = NULL;
  803. /* 'parent' could be a state of caller and
  804. * 'state' could be a state of callee. In such case
  805. * parent->curframe < state->curframe
  806. * and it's ok for r1 - r5 registers
  807. *
  808. * 'parent' could be a callee's state after it bpf_exit-ed.
  809. * In such case parent->curframe > state->curframe
  810. * and it's ok for r0 only
  811. */
  812. if (parent->curframe == state->curframe ||
  813. (parent->curframe < state->curframe &&
  814. regno >= BPF_REG_1 && regno <= BPF_REG_5) ||
  815. (parent->curframe > state->curframe &&
  816. regno == BPF_REG_0))
  817. return parent;
  818. if (parent->curframe > state->curframe &&
  819. regno >= BPF_REG_6) {
  820. /* for callee saved regs we have to skip the whole chain
  821. * of states that belong to callee and mark as LIVE_READ
  822. * the registers before the call
  823. */
  824. tmp = parent;
  825. while (tmp && tmp->curframe != state->curframe) {
  826. tmp = tmp->parent;
  827. }
  828. if (!tmp)
  829. goto bug;
  830. parent = tmp;
  831. } else {
  832. goto bug;
  833. }
  834. return parent;
  835. bug:
  836. verbose(env, "verifier bug regno %d tmp %p\n", regno, tmp);
  837. verbose(env, "regno %d parent frame %d current frame %d\n",
  838. regno, parent->curframe, state->curframe);
  839. return NULL;
  840. }
  841. static int mark_reg_read(struct bpf_verifier_env *env,
  842. const struct bpf_verifier_state *state,
  843. struct bpf_verifier_state *parent,
  844. u32 regno)
  845. {
  846. bool writes = parent == state->parent; /* Observe write marks */
  847. if (regno == BPF_REG_FP)
  848. /* We don't need to worry about FP liveness because it's read-only */
  849. return 0;
  850. while (parent) {
  851. /* if read wasn't screened by an earlier write ... */
  852. if (writes && state->frame[state->curframe]->regs[regno].live & REG_LIVE_WRITTEN)
  853. break;
  854. parent = skip_callee(env, state, parent, regno);
  855. if (!parent)
  856. return -EFAULT;
  857. /* ... then we depend on parent's value */
  858. parent->frame[parent->curframe]->regs[regno].live |= REG_LIVE_READ;
  859. state = parent;
  860. parent = state->parent;
  861. writes = true;
  862. }
  863. return 0;
  864. }
  865. static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
  866. enum reg_arg_type t)
  867. {
  868. struct bpf_verifier_state *vstate = env->cur_state;
  869. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  870. struct bpf_reg_state *regs = state->regs;
  871. if (regno >= MAX_BPF_REG) {
  872. verbose(env, "R%d is invalid\n", regno);
  873. return -EINVAL;
  874. }
  875. if (t == SRC_OP) {
  876. /* check whether register used as source operand can be read */
  877. if (regs[regno].type == NOT_INIT) {
  878. verbose(env, "R%d !read_ok\n", regno);
  879. return -EACCES;
  880. }
  881. return mark_reg_read(env, vstate, vstate->parent, regno);
  882. } else {
  883. /* check whether register used as dest operand can be written to */
  884. if (regno == BPF_REG_FP) {
  885. verbose(env, "frame pointer is read only\n");
  886. return -EACCES;
  887. }
  888. regs[regno].live |= REG_LIVE_WRITTEN;
  889. if (t == DST_OP)
  890. mark_reg_unknown(env, regs, regno);
  891. }
  892. return 0;
  893. }
  894. static bool is_spillable_regtype(enum bpf_reg_type type)
  895. {
  896. switch (type) {
  897. case PTR_TO_MAP_VALUE:
  898. case PTR_TO_MAP_VALUE_OR_NULL:
  899. case PTR_TO_STACK:
  900. case PTR_TO_CTX:
  901. case PTR_TO_PACKET:
  902. case PTR_TO_PACKET_META:
  903. case PTR_TO_PACKET_END:
  904. case CONST_PTR_TO_MAP:
  905. return true;
  906. default:
  907. return false;
  908. }
  909. }
  910. /* Does this register contain a constant zero? */
  911. static bool register_is_null(struct bpf_reg_state *reg)
  912. {
  913. return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
  914. }
  915. /* check_stack_read/write functions track spill/fill of registers,
  916. * stack boundary and alignment are checked in check_mem_access()
  917. */
  918. static int check_stack_write(struct bpf_verifier_env *env,
  919. struct bpf_func_state *state, /* func where register points to */
  920. int off, int size, int value_regno, int insn_idx)
  921. {
  922. struct bpf_func_state *cur; /* state of the current function */
  923. int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
  924. enum bpf_reg_type type;
  925. err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
  926. true);
  927. if (err)
  928. return err;
  929. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  930. * so it's aligned access and [off, off + size) are within stack limits
  931. */
  932. if (!env->allow_ptr_leaks &&
  933. state->stack[spi].slot_type[0] == STACK_SPILL &&
  934. size != BPF_REG_SIZE) {
  935. verbose(env, "attempt to corrupt spilled pointer on stack\n");
  936. return -EACCES;
  937. }
  938. cur = env->cur_state->frame[env->cur_state->curframe];
  939. if (value_regno >= 0 &&
  940. is_spillable_regtype((type = cur->regs[value_regno].type))) {
  941. /* register containing pointer is being spilled into stack */
  942. if (size != BPF_REG_SIZE) {
  943. verbose(env, "invalid size of register spill\n");
  944. return -EACCES;
  945. }
  946. if (state != cur && type == PTR_TO_STACK) {
  947. verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
  948. return -EINVAL;
  949. }
  950. /* save register state */
  951. state->stack[spi].spilled_ptr = cur->regs[value_regno];
  952. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  953. for (i = 0; i < BPF_REG_SIZE; i++) {
  954. if (state->stack[spi].slot_type[i] == STACK_MISC &&
  955. !env->allow_ptr_leaks) {
  956. int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
  957. int soff = (-spi - 1) * BPF_REG_SIZE;
  958. /* detected reuse of integer stack slot with a pointer
  959. * which means either llvm is reusing stack slot or
  960. * an attacker is trying to exploit CVE-2018-3639
  961. * (speculative store bypass)
  962. * Have to sanitize that slot with preemptive
  963. * store of zero.
  964. */
  965. if (*poff && *poff != soff) {
  966. /* disallow programs where single insn stores
  967. * into two different stack slots, since verifier
  968. * cannot sanitize them
  969. */
  970. verbose(env,
  971. "insn %d cannot access two stack slots fp%d and fp%d",
  972. insn_idx, *poff, soff);
  973. return -EINVAL;
  974. }
  975. *poff = soff;
  976. }
  977. state->stack[spi].slot_type[i] = STACK_SPILL;
  978. }
  979. } else {
  980. u8 type = STACK_MISC;
  981. /* regular write of data into stack */
  982. state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
  983. /* only mark the slot as written if all 8 bytes were written
  984. * otherwise read propagation may incorrectly stop too soon
  985. * when stack slots are partially written.
  986. * This heuristic means that read propagation will be
  987. * conservative, since it will add reg_live_read marks
  988. * to stack slots all the way to first state when programs
  989. * writes+reads less than 8 bytes
  990. */
  991. if (size == BPF_REG_SIZE)
  992. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  993. /* when we zero initialize stack slots mark them as such */
  994. if (value_regno >= 0 &&
  995. register_is_null(&cur->regs[value_regno]))
  996. type = STACK_ZERO;
  997. for (i = 0; i < size; i++)
  998. state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
  999. type;
  1000. }
  1001. return 0;
  1002. }
  1003. /* registers of every function are unique and mark_reg_read() propagates
  1004. * the liveness in the following cases:
  1005. * - from callee into caller for R1 - R5 that were used as arguments
  1006. * - from caller into callee for R0 that used as result of the call
  1007. * - from caller to the same caller skipping states of the callee for R6 - R9,
  1008. * since R6 - R9 are callee saved by implicit function prologue and
  1009. * caller's R6 != callee's R6, so when we propagate liveness up to
  1010. * parent states we need to skip callee states for R6 - R9.
  1011. *
  1012. * stack slot marking is different, since stacks of caller and callee are
  1013. * accessible in both (since caller can pass a pointer to caller's stack to
  1014. * callee which can pass it to another function), hence mark_stack_slot_read()
  1015. * has to propagate the stack liveness to all parent states at given frame number.
  1016. * Consider code:
  1017. * f1() {
  1018. * ptr = fp - 8;
  1019. * *ptr = ctx;
  1020. * call f2 {
  1021. * .. = *ptr;
  1022. * }
  1023. * .. = *ptr;
  1024. * }
  1025. * First *ptr is reading from f1's stack and mark_stack_slot_read() has
  1026. * to mark liveness at the f1's frame and not f2's frame.
  1027. * Second *ptr is also reading from f1's stack and mark_stack_slot_read() has
  1028. * to propagate liveness to f2 states at f1's frame level and further into
  1029. * f1 states at f1's frame level until write into that stack slot
  1030. */
  1031. static void mark_stack_slot_read(struct bpf_verifier_env *env,
  1032. const struct bpf_verifier_state *state,
  1033. struct bpf_verifier_state *parent,
  1034. int slot, int frameno)
  1035. {
  1036. bool writes = parent == state->parent; /* Observe write marks */
  1037. while (parent) {
  1038. if (parent->frame[frameno]->allocated_stack <= slot * BPF_REG_SIZE)
  1039. /* since LIVE_WRITTEN mark is only done for full 8-byte
  1040. * write the read marks are conservative and parent
  1041. * state may not even have the stack allocated. In such case
  1042. * end the propagation, since the loop reached beginning
  1043. * of the function
  1044. */
  1045. break;
  1046. /* if read wasn't screened by an earlier write ... */
  1047. if (writes && state->frame[frameno]->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
  1048. break;
  1049. /* ... then we depend on parent's value */
  1050. parent->frame[frameno]->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
  1051. state = parent;
  1052. parent = state->parent;
  1053. writes = true;
  1054. }
  1055. }
  1056. static int check_stack_read(struct bpf_verifier_env *env,
  1057. struct bpf_func_state *reg_state /* func where register points to */,
  1058. int off, int size, int value_regno)
  1059. {
  1060. struct bpf_verifier_state *vstate = env->cur_state;
  1061. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  1062. int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
  1063. u8 *stype;
  1064. if (reg_state->allocated_stack <= slot) {
  1065. verbose(env, "invalid read from stack off %d+0 size %d\n",
  1066. off, size);
  1067. return -EACCES;
  1068. }
  1069. stype = reg_state->stack[spi].slot_type;
  1070. if (stype[0] == STACK_SPILL) {
  1071. if (size != BPF_REG_SIZE) {
  1072. verbose(env, "invalid size of register spill\n");
  1073. return -EACCES;
  1074. }
  1075. for (i = 1; i < BPF_REG_SIZE; i++) {
  1076. if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
  1077. verbose(env, "corrupted spill memory\n");
  1078. return -EACCES;
  1079. }
  1080. }
  1081. if (value_regno >= 0) {
  1082. /* restore register state from stack */
  1083. state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
  1084. /* mark reg as written since spilled pointer state likely
  1085. * has its liveness marks cleared by is_state_visited()
  1086. * which resets stack/reg liveness for state transitions
  1087. */
  1088. state->regs[value_regno].live |= REG_LIVE_WRITTEN;
  1089. }
  1090. mark_stack_slot_read(env, vstate, vstate->parent, spi,
  1091. reg_state->frameno);
  1092. return 0;
  1093. } else {
  1094. int zeros = 0;
  1095. for (i = 0; i < size; i++) {
  1096. if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
  1097. continue;
  1098. if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
  1099. zeros++;
  1100. continue;
  1101. }
  1102. verbose(env, "invalid read from stack off %d+%d size %d\n",
  1103. off, i, size);
  1104. return -EACCES;
  1105. }
  1106. mark_stack_slot_read(env, vstate, vstate->parent, spi,
  1107. reg_state->frameno);
  1108. if (value_regno >= 0) {
  1109. if (zeros == size) {
  1110. /* any size read into register is zero extended,
  1111. * so the whole register == const_zero
  1112. */
  1113. __mark_reg_const_zero(&state->regs[value_regno]);
  1114. } else {
  1115. /* have read misc data from the stack */
  1116. mark_reg_unknown(env, state->regs, value_regno);
  1117. }
  1118. state->regs[value_regno].live |= REG_LIVE_WRITTEN;
  1119. }
  1120. return 0;
  1121. }
  1122. }
  1123. /* check read/write into map element returned by bpf_map_lookup_elem() */
  1124. static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
  1125. int size, bool zero_size_allowed)
  1126. {
  1127. struct bpf_reg_state *regs = cur_regs(env);
  1128. struct bpf_map *map = regs[regno].map_ptr;
  1129. if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
  1130. off + size > map->value_size) {
  1131. verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
  1132. map->value_size, off, size);
  1133. return -EACCES;
  1134. }
  1135. return 0;
  1136. }
  1137. /* check read/write into a map element with possible variable offset */
  1138. static int check_map_access(struct bpf_verifier_env *env, u32 regno,
  1139. int off, int size, bool zero_size_allowed)
  1140. {
  1141. struct bpf_verifier_state *vstate = env->cur_state;
  1142. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  1143. struct bpf_reg_state *reg = &state->regs[regno];
  1144. int err;
  1145. /* We may have adjusted the register to this map value, so we
  1146. * need to try adding each of min_value and max_value to off
  1147. * to make sure our theoretical access will be safe.
  1148. */
  1149. if (env->log.level)
  1150. print_verifier_state(env, state);
  1151. /* The minimum value is only important with signed
  1152. * comparisons where we can't assume the floor of a
  1153. * value is 0. If we are using signed variables for our
  1154. * index'es we need to make sure that whatever we use
  1155. * will have a set floor within our range.
  1156. */
  1157. if (reg->smin_value < 0) {
  1158. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  1159. regno);
  1160. return -EACCES;
  1161. }
  1162. err = __check_map_access(env, regno, reg->smin_value + off, size,
  1163. zero_size_allowed);
  1164. if (err) {
  1165. verbose(env, "R%d min value is outside of the array range\n",
  1166. regno);
  1167. return err;
  1168. }
  1169. /* If we haven't set a max value then we need to bail since we can't be
  1170. * sure we won't do bad things.
  1171. * If reg->umax_value + off could overflow, treat that as unbounded too.
  1172. */
  1173. if (reg->umax_value >= BPF_MAX_VAR_OFF) {
  1174. verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
  1175. regno);
  1176. return -EACCES;
  1177. }
  1178. err = __check_map_access(env, regno, reg->umax_value + off, size,
  1179. zero_size_allowed);
  1180. if (err)
  1181. verbose(env, "R%d max value is outside of the array range\n",
  1182. regno);
  1183. return err;
  1184. }
  1185. #define MAX_PACKET_OFF 0xffff
  1186. static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
  1187. const struct bpf_call_arg_meta *meta,
  1188. enum bpf_access_type t)
  1189. {
  1190. switch (env->prog->type) {
  1191. case BPF_PROG_TYPE_LWT_IN:
  1192. case BPF_PROG_TYPE_LWT_OUT:
  1193. case BPF_PROG_TYPE_LWT_SEG6LOCAL:
  1194. case BPF_PROG_TYPE_SK_REUSEPORT:
  1195. /* dst_input() and dst_output() can't write for now */
  1196. if (t == BPF_WRITE)
  1197. return false;
  1198. /* fallthrough */
  1199. case BPF_PROG_TYPE_SCHED_CLS:
  1200. case BPF_PROG_TYPE_SCHED_ACT:
  1201. case BPF_PROG_TYPE_XDP:
  1202. case BPF_PROG_TYPE_LWT_XMIT:
  1203. case BPF_PROG_TYPE_SK_SKB:
  1204. case BPF_PROG_TYPE_SK_MSG:
  1205. if (meta)
  1206. return meta->pkt_access;
  1207. env->seen_direct_write = true;
  1208. return true;
  1209. default:
  1210. return false;
  1211. }
  1212. }
  1213. static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
  1214. int off, int size, bool zero_size_allowed)
  1215. {
  1216. struct bpf_reg_state *regs = cur_regs(env);
  1217. struct bpf_reg_state *reg = &regs[regno];
  1218. if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
  1219. (u64)off + size > reg->range) {
  1220. verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
  1221. off, size, regno, reg->id, reg->off, reg->range);
  1222. return -EACCES;
  1223. }
  1224. return 0;
  1225. }
  1226. static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
  1227. int size, bool zero_size_allowed)
  1228. {
  1229. struct bpf_reg_state *regs = cur_regs(env);
  1230. struct bpf_reg_state *reg = &regs[regno];
  1231. int err;
  1232. /* We may have added a variable offset to the packet pointer; but any
  1233. * reg->range we have comes after that. We are only checking the fixed
  1234. * offset.
  1235. */
  1236. /* We don't allow negative numbers, because we aren't tracking enough
  1237. * detail to prove they're safe.
  1238. */
  1239. if (reg->smin_value < 0) {
  1240. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  1241. regno);
  1242. return -EACCES;
  1243. }
  1244. err = __check_packet_access(env, regno, off, size, zero_size_allowed);
  1245. if (err) {
  1246. verbose(env, "R%d offset is outside of the packet\n", regno);
  1247. return err;
  1248. }
  1249. return err;
  1250. }
  1251. /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
  1252. static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
  1253. enum bpf_access_type t, enum bpf_reg_type *reg_type)
  1254. {
  1255. struct bpf_insn_access_aux info = {
  1256. .reg_type = *reg_type,
  1257. };
  1258. if (env->ops->is_valid_access &&
  1259. env->ops->is_valid_access(off, size, t, env->prog, &info)) {
  1260. /* A non zero info.ctx_field_size indicates that this field is a
  1261. * candidate for later verifier transformation to load the whole
  1262. * field and then apply a mask when accessed with a narrower
  1263. * access than actual ctx access size. A zero info.ctx_field_size
  1264. * will only allow for whole field access and rejects any other
  1265. * type of narrower access.
  1266. */
  1267. *reg_type = info.reg_type;
  1268. env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
  1269. /* remember the offset of last byte accessed in ctx */
  1270. if (env->prog->aux->max_ctx_offset < off + size)
  1271. env->prog->aux->max_ctx_offset = off + size;
  1272. return 0;
  1273. }
  1274. verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
  1275. return -EACCES;
  1276. }
  1277. static bool __is_pointer_value(bool allow_ptr_leaks,
  1278. const struct bpf_reg_state *reg)
  1279. {
  1280. if (allow_ptr_leaks)
  1281. return false;
  1282. return reg->type != SCALAR_VALUE;
  1283. }
  1284. static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
  1285. {
  1286. return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
  1287. }
  1288. static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
  1289. {
  1290. const struct bpf_reg_state *reg = cur_regs(env) + regno;
  1291. return reg->type == PTR_TO_CTX;
  1292. }
  1293. static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
  1294. {
  1295. const struct bpf_reg_state *reg = cur_regs(env) + regno;
  1296. return type_is_pkt_pointer(reg->type);
  1297. }
  1298. static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
  1299. const struct bpf_reg_state *reg,
  1300. int off, int size, bool strict)
  1301. {
  1302. struct tnum reg_off;
  1303. int ip_align;
  1304. /* Byte size accesses are always allowed. */
  1305. if (!strict || size == 1)
  1306. return 0;
  1307. /* For platforms that do not have a Kconfig enabling
  1308. * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
  1309. * NET_IP_ALIGN is universally set to '2'. And on platforms
  1310. * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
  1311. * to this code only in strict mode where we want to emulate
  1312. * the NET_IP_ALIGN==2 checking. Therefore use an
  1313. * unconditional IP align value of '2'.
  1314. */
  1315. ip_align = 2;
  1316. reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
  1317. if (!tnum_is_aligned(reg_off, size)) {
  1318. char tn_buf[48];
  1319. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1320. verbose(env,
  1321. "misaligned packet access off %d+%s+%d+%d size %d\n",
  1322. ip_align, tn_buf, reg->off, off, size);
  1323. return -EACCES;
  1324. }
  1325. return 0;
  1326. }
  1327. static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
  1328. const struct bpf_reg_state *reg,
  1329. const char *pointer_desc,
  1330. int off, int size, bool strict)
  1331. {
  1332. struct tnum reg_off;
  1333. /* Byte size accesses are always allowed. */
  1334. if (!strict || size == 1)
  1335. return 0;
  1336. reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
  1337. if (!tnum_is_aligned(reg_off, size)) {
  1338. char tn_buf[48];
  1339. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1340. verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
  1341. pointer_desc, tn_buf, reg->off, off, size);
  1342. return -EACCES;
  1343. }
  1344. return 0;
  1345. }
  1346. static int check_ptr_alignment(struct bpf_verifier_env *env,
  1347. const struct bpf_reg_state *reg, int off,
  1348. int size, bool strict_alignment_once)
  1349. {
  1350. bool strict = env->strict_alignment || strict_alignment_once;
  1351. const char *pointer_desc = "";
  1352. switch (reg->type) {
  1353. case PTR_TO_PACKET:
  1354. case PTR_TO_PACKET_META:
  1355. /* Special case, because of NET_IP_ALIGN. Given metadata sits
  1356. * right in front, treat it the very same way.
  1357. */
  1358. return check_pkt_ptr_alignment(env, reg, off, size, strict);
  1359. case PTR_TO_MAP_VALUE:
  1360. pointer_desc = "value ";
  1361. break;
  1362. case PTR_TO_CTX:
  1363. pointer_desc = "context ";
  1364. break;
  1365. case PTR_TO_STACK:
  1366. pointer_desc = "stack ";
  1367. /* The stack spill tracking logic in check_stack_write()
  1368. * and check_stack_read() relies on stack accesses being
  1369. * aligned.
  1370. */
  1371. strict = true;
  1372. break;
  1373. default:
  1374. break;
  1375. }
  1376. return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
  1377. strict);
  1378. }
  1379. static int update_stack_depth(struct bpf_verifier_env *env,
  1380. const struct bpf_func_state *func,
  1381. int off)
  1382. {
  1383. u16 stack = env->subprog_info[func->subprogno].stack_depth;
  1384. if (stack >= -off)
  1385. return 0;
  1386. /* update known max for given subprogram */
  1387. env->subprog_info[func->subprogno].stack_depth = -off;
  1388. return 0;
  1389. }
  1390. /* starting from main bpf function walk all instructions of the function
  1391. * and recursively walk all callees that given function can call.
  1392. * Ignore jump and exit insns.
  1393. * Since recursion is prevented by check_cfg() this algorithm
  1394. * only needs a local stack of MAX_CALL_FRAMES to remember callsites
  1395. */
  1396. static int check_max_stack_depth(struct bpf_verifier_env *env)
  1397. {
  1398. int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
  1399. struct bpf_subprog_info *subprog = env->subprog_info;
  1400. struct bpf_insn *insn = env->prog->insnsi;
  1401. int ret_insn[MAX_CALL_FRAMES];
  1402. int ret_prog[MAX_CALL_FRAMES];
  1403. process_func:
  1404. /* round up to 32-bytes, since this is granularity
  1405. * of interpreter stack size
  1406. */
  1407. depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
  1408. if (depth > MAX_BPF_STACK) {
  1409. verbose(env, "combined stack size of %d calls is %d. Too large\n",
  1410. frame + 1, depth);
  1411. return -EACCES;
  1412. }
  1413. continue_func:
  1414. subprog_end = subprog[idx + 1].start;
  1415. for (; i < subprog_end; i++) {
  1416. if (insn[i].code != (BPF_JMP | BPF_CALL))
  1417. continue;
  1418. if (insn[i].src_reg != BPF_PSEUDO_CALL)
  1419. continue;
  1420. /* remember insn and function to return to */
  1421. ret_insn[frame] = i + 1;
  1422. ret_prog[frame] = idx;
  1423. /* find the callee */
  1424. i = i + insn[i].imm + 1;
  1425. idx = find_subprog(env, i);
  1426. if (idx < 0) {
  1427. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  1428. i);
  1429. return -EFAULT;
  1430. }
  1431. frame++;
  1432. if (frame >= MAX_CALL_FRAMES) {
  1433. WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
  1434. return -EFAULT;
  1435. }
  1436. goto process_func;
  1437. }
  1438. /* end of for() loop means the last insn of the 'subprog'
  1439. * was reached. Doesn't matter whether it was JA or EXIT
  1440. */
  1441. if (frame == 0)
  1442. return 0;
  1443. depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
  1444. frame--;
  1445. i = ret_insn[frame];
  1446. idx = ret_prog[frame];
  1447. goto continue_func;
  1448. }
  1449. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  1450. static int get_callee_stack_depth(struct bpf_verifier_env *env,
  1451. const struct bpf_insn *insn, int idx)
  1452. {
  1453. int start = idx + insn->imm + 1, subprog;
  1454. subprog = find_subprog(env, start);
  1455. if (subprog < 0) {
  1456. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  1457. start);
  1458. return -EFAULT;
  1459. }
  1460. return env->subprog_info[subprog].stack_depth;
  1461. }
  1462. #endif
  1463. static int check_ctx_reg(struct bpf_verifier_env *env,
  1464. const struct bpf_reg_state *reg, int regno)
  1465. {
  1466. /* Access to ctx or passing it to a helper is only allowed in
  1467. * its original, unmodified form.
  1468. */
  1469. if (reg->off) {
  1470. verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
  1471. regno, reg->off);
  1472. return -EACCES;
  1473. }
  1474. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  1475. char tn_buf[48];
  1476. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1477. verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
  1478. return -EACCES;
  1479. }
  1480. return 0;
  1481. }
  1482. /* truncate register to smaller size (in bytes)
  1483. * must be called with size < BPF_REG_SIZE
  1484. */
  1485. static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
  1486. {
  1487. u64 mask;
  1488. /* clear high bits in bit representation */
  1489. reg->var_off = tnum_cast(reg->var_off, size);
  1490. /* fix arithmetic bounds */
  1491. mask = ((u64)1 << (size * 8)) - 1;
  1492. if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
  1493. reg->umin_value &= mask;
  1494. reg->umax_value &= mask;
  1495. } else {
  1496. reg->umin_value = 0;
  1497. reg->umax_value = mask;
  1498. }
  1499. reg->smin_value = reg->umin_value;
  1500. reg->smax_value = reg->umax_value;
  1501. }
  1502. /* check whether memory at (regno + off) is accessible for t = (read | write)
  1503. * if t==write, value_regno is a register which value is stored into memory
  1504. * if t==read, value_regno is a register which will receive the value from memory
  1505. * if t==write && value_regno==-1, some unknown value is stored into memory
  1506. * if t==read && value_regno==-1, don't care what we read from memory
  1507. */
  1508. static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
  1509. int off, int bpf_size, enum bpf_access_type t,
  1510. int value_regno, bool strict_alignment_once)
  1511. {
  1512. struct bpf_reg_state *regs = cur_regs(env);
  1513. struct bpf_reg_state *reg = regs + regno;
  1514. struct bpf_func_state *state;
  1515. int size, err = 0;
  1516. size = bpf_size_to_bytes(bpf_size);
  1517. if (size < 0)
  1518. return size;
  1519. /* alignment checks will add in reg->off themselves */
  1520. err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
  1521. if (err)
  1522. return err;
  1523. /* for access checks, reg->off is just part of off */
  1524. off += reg->off;
  1525. if (reg->type == PTR_TO_MAP_VALUE) {
  1526. if (t == BPF_WRITE && value_regno >= 0 &&
  1527. is_pointer_value(env, value_regno)) {
  1528. verbose(env, "R%d leaks addr into map\n", value_regno);
  1529. return -EACCES;
  1530. }
  1531. err = check_map_access(env, regno, off, size, false);
  1532. if (!err && t == BPF_READ && value_regno >= 0)
  1533. mark_reg_unknown(env, regs, value_regno);
  1534. } else if (reg->type == PTR_TO_CTX) {
  1535. enum bpf_reg_type reg_type = SCALAR_VALUE;
  1536. if (t == BPF_WRITE && value_regno >= 0 &&
  1537. is_pointer_value(env, value_regno)) {
  1538. verbose(env, "R%d leaks addr into ctx\n", value_regno);
  1539. return -EACCES;
  1540. }
  1541. err = check_ctx_reg(env, reg, regno);
  1542. if (err < 0)
  1543. return err;
  1544. err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
  1545. if (!err && t == BPF_READ && value_regno >= 0) {
  1546. /* ctx access returns either a scalar, or a
  1547. * PTR_TO_PACKET[_META,_END]. In the latter
  1548. * case, we know the offset is zero.
  1549. */
  1550. if (reg_type == SCALAR_VALUE)
  1551. mark_reg_unknown(env, regs, value_regno);
  1552. else
  1553. mark_reg_known_zero(env, regs,
  1554. value_regno);
  1555. regs[value_regno].id = 0;
  1556. regs[value_regno].off = 0;
  1557. regs[value_regno].range = 0;
  1558. regs[value_regno].type = reg_type;
  1559. }
  1560. } else if (reg->type == PTR_TO_STACK) {
  1561. /* stack accesses must be at a fixed offset, so that we can
  1562. * determine what type of data were returned.
  1563. * See check_stack_read().
  1564. */
  1565. if (!tnum_is_const(reg->var_off)) {
  1566. char tn_buf[48];
  1567. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1568. verbose(env, "variable stack access var_off=%s off=%d size=%d",
  1569. tn_buf, off, size);
  1570. return -EACCES;
  1571. }
  1572. off += reg->var_off.value;
  1573. if (off >= 0 || off < -MAX_BPF_STACK) {
  1574. verbose(env, "invalid stack off=%d size=%d\n", off,
  1575. size);
  1576. return -EACCES;
  1577. }
  1578. state = func(env, reg);
  1579. err = update_stack_depth(env, state, off);
  1580. if (err)
  1581. return err;
  1582. if (t == BPF_WRITE)
  1583. err = check_stack_write(env, state, off, size,
  1584. value_regno, insn_idx);
  1585. else
  1586. err = check_stack_read(env, state, off, size,
  1587. value_regno);
  1588. } else if (reg_is_pkt_pointer(reg)) {
  1589. if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
  1590. verbose(env, "cannot write into packet\n");
  1591. return -EACCES;
  1592. }
  1593. if (t == BPF_WRITE && value_regno >= 0 &&
  1594. is_pointer_value(env, value_regno)) {
  1595. verbose(env, "R%d leaks addr into packet\n",
  1596. value_regno);
  1597. return -EACCES;
  1598. }
  1599. err = check_packet_access(env, regno, off, size, false);
  1600. if (!err && t == BPF_READ && value_regno >= 0)
  1601. mark_reg_unknown(env, regs, value_regno);
  1602. } else {
  1603. verbose(env, "R%d invalid mem access '%s'\n", regno,
  1604. reg_type_str[reg->type]);
  1605. return -EACCES;
  1606. }
  1607. if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
  1608. regs[value_regno].type == SCALAR_VALUE) {
  1609. /* b/h/w load zero-extends, mark upper bits as known 0 */
  1610. coerce_reg_to_size(&regs[value_regno], size);
  1611. }
  1612. return err;
  1613. }
  1614. static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
  1615. {
  1616. int err;
  1617. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  1618. insn->imm != 0) {
  1619. verbose(env, "BPF_XADD uses reserved fields\n");
  1620. return -EINVAL;
  1621. }
  1622. /* check src1 operand */
  1623. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  1624. if (err)
  1625. return err;
  1626. /* check src2 operand */
  1627. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  1628. if (err)
  1629. return err;
  1630. if (is_pointer_value(env, insn->src_reg)) {
  1631. verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
  1632. return -EACCES;
  1633. }
  1634. if (is_ctx_reg(env, insn->dst_reg) ||
  1635. is_pkt_reg(env, insn->dst_reg)) {
  1636. verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
  1637. insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
  1638. "context" : "packet");
  1639. return -EACCES;
  1640. }
  1641. /* check whether atomic_add can read the memory */
  1642. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  1643. BPF_SIZE(insn->code), BPF_READ, -1, true);
  1644. if (err)
  1645. return err;
  1646. /* check whether atomic_add can write into the same memory */
  1647. return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  1648. BPF_SIZE(insn->code), BPF_WRITE, -1, true);
  1649. }
  1650. /* when register 'regno' is passed into function that will read 'access_size'
  1651. * bytes from that pointer, make sure that it's within stack boundary
  1652. * and all elements of stack are initialized.
  1653. * Unlike most pointer bounds-checking functions, this one doesn't take an
  1654. * 'off' argument, so it has to add in reg->off itself.
  1655. */
  1656. static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
  1657. int access_size, bool zero_size_allowed,
  1658. struct bpf_call_arg_meta *meta)
  1659. {
  1660. struct bpf_reg_state *reg = cur_regs(env) + regno;
  1661. struct bpf_func_state *state = func(env, reg);
  1662. int off, i, slot, spi;
  1663. if (reg->type != PTR_TO_STACK) {
  1664. /* Allow zero-byte read from NULL, regardless of pointer type */
  1665. if (zero_size_allowed && access_size == 0 &&
  1666. register_is_null(reg))
  1667. return 0;
  1668. verbose(env, "R%d type=%s expected=%s\n", regno,
  1669. reg_type_str[reg->type],
  1670. reg_type_str[PTR_TO_STACK]);
  1671. return -EACCES;
  1672. }
  1673. /* Only allow fixed-offset stack reads */
  1674. if (!tnum_is_const(reg->var_off)) {
  1675. char tn_buf[48];
  1676. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1677. verbose(env, "invalid variable stack read R%d var_off=%s\n",
  1678. regno, tn_buf);
  1679. return -EACCES;
  1680. }
  1681. off = reg->off + reg->var_off.value;
  1682. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  1683. access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
  1684. verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
  1685. regno, off, access_size);
  1686. return -EACCES;
  1687. }
  1688. if (meta && meta->raw_mode) {
  1689. meta->access_size = access_size;
  1690. meta->regno = regno;
  1691. return 0;
  1692. }
  1693. for (i = 0; i < access_size; i++) {
  1694. u8 *stype;
  1695. slot = -(off + i) - 1;
  1696. spi = slot / BPF_REG_SIZE;
  1697. if (state->allocated_stack <= slot)
  1698. goto err;
  1699. stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
  1700. if (*stype == STACK_MISC)
  1701. goto mark;
  1702. if (*stype == STACK_ZERO) {
  1703. /* helper can write anything into the stack */
  1704. *stype = STACK_MISC;
  1705. goto mark;
  1706. }
  1707. err:
  1708. verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
  1709. off, i, access_size);
  1710. return -EACCES;
  1711. mark:
  1712. /* reading any byte out of 8-byte 'spill_slot' will cause
  1713. * the whole slot to be marked as 'read'
  1714. */
  1715. mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
  1716. spi, state->frameno);
  1717. }
  1718. return update_stack_depth(env, state, off);
  1719. }
  1720. static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
  1721. int access_size, bool zero_size_allowed,
  1722. struct bpf_call_arg_meta *meta)
  1723. {
  1724. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  1725. switch (reg->type) {
  1726. case PTR_TO_PACKET:
  1727. case PTR_TO_PACKET_META:
  1728. return check_packet_access(env, regno, reg->off, access_size,
  1729. zero_size_allowed);
  1730. case PTR_TO_MAP_VALUE:
  1731. return check_map_access(env, regno, reg->off, access_size,
  1732. zero_size_allowed);
  1733. default: /* scalar_value|ptr_to_stack or invalid ptr */
  1734. return check_stack_boundary(env, regno, access_size,
  1735. zero_size_allowed, meta);
  1736. }
  1737. }
  1738. static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
  1739. {
  1740. return type == ARG_PTR_TO_MEM ||
  1741. type == ARG_PTR_TO_MEM_OR_NULL ||
  1742. type == ARG_PTR_TO_UNINIT_MEM;
  1743. }
  1744. static bool arg_type_is_mem_size(enum bpf_arg_type type)
  1745. {
  1746. return type == ARG_CONST_SIZE ||
  1747. type == ARG_CONST_SIZE_OR_ZERO;
  1748. }
  1749. static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
  1750. enum bpf_arg_type arg_type,
  1751. struct bpf_call_arg_meta *meta)
  1752. {
  1753. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  1754. enum bpf_reg_type expected_type, type = reg->type;
  1755. int err = 0;
  1756. if (arg_type == ARG_DONTCARE)
  1757. return 0;
  1758. err = check_reg_arg(env, regno, SRC_OP);
  1759. if (err)
  1760. return err;
  1761. if (arg_type == ARG_ANYTHING) {
  1762. if (is_pointer_value(env, regno)) {
  1763. verbose(env, "R%d leaks addr into helper function\n",
  1764. regno);
  1765. return -EACCES;
  1766. }
  1767. return 0;
  1768. }
  1769. if (type_is_pkt_pointer(type) &&
  1770. !may_access_direct_pkt_data(env, meta, BPF_READ)) {
  1771. verbose(env, "helper access to the packet is not allowed\n");
  1772. return -EACCES;
  1773. }
  1774. if (arg_type == ARG_PTR_TO_MAP_KEY ||
  1775. arg_type == ARG_PTR_TO_MAP_VALUE) {
  1776. expected_type = PTR_TO_STACK;
  1777. if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
  1778. type != expected_type)
  1779. goto err_type;
  1780. } else if (arg_type == ARG_CONST_SIZE ||
  1781. arg_type == ARG_CONST_SIZE_OR_ZERO) {
  1782. expected_type = SCALAR_VALUE;
  1783. if (type != expected_type)
  1784. goto err_type;
  1785. } else if (arg_type == ARG_CONST_MAP_PTR) {
  1786. expected_type = CONST_PTR_TO_MAP;
  1787. if (type != expected_type)
  1788. goto err_type;
  1789. } else if (arg_type == ARG_PTR_TO_CTX) {
  1790. expected_type = PTR_TO_CTX;
  1791. if (type != expected_type)
  1792. goto err_type;
  1793. err = check_ctx_reg(env, reg, regno);
  1794. if (err < 0)
  1795. return err;
  1796. } else if (arg_type_is_mem_ptr(arg_type)) {
  1797. expected_type = PTR_TO_STACK;
  1798. /* One exception here. In case function allows for NULL to be
  1799. * passed in as argument, it's a SCALAR_VALUE type. Final test
  1800. * happens during stack boundary checking.
  1801. */
  1802. if (register_is_null(reg) &&
  1803. arg_type == ARG_PTR_TO_MEM_OR_NULL)
  1804. /* final test in check_stack_boundary() */;
  1805. else if (!type_is_pkt_pointer(type) &&
  1806. type != PTR_TO_MAP_VALUE &&
  1807. type != expected_type)
  1808. goto err_type;
  1809. meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
  1810. } else {
  1811. verbose(env, "unsupported arg_type %d\n", arg_type);
  1812. return -EFAULT;
  1813. }
  1814. if (arg_type == ARG_CONST_MAP_PTR) {
  1815. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  1816. meta->map_ptr = reg->map_ptr;
  1817. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  1818. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  1819. * check that [key, key + map->key_size) are within
  1820. * stack limits and initialized
  1821. */
  1822. if (!meta->map_ptr) {
  1823. /* in function declaration map_ptr must come before
  1824. * map_key, so that it's verified and known before
  1825. * we have to check map_key here. Otherwise it means
  1826. * that kernel subsystem misconfigured verifier
  1827. */
  1828. verbose(env, "invalid map_ptr to access map->key\n");
  1829. return -EACCES;
  1830. }
  1831. err = check_helper_mem_access(env, regno,
  1832. meta->map_ptr->key_size, false,
  1833. NULL);
  1834. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  1835. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  1836. * check [value, value + map->value_size) validity
  1837. */
  1838. if (!meta->map_ptr) {
  1839. /* kernel subsystem misconfigured verifier */
  1840. verbose(env, "invalid map_ptr to access map->value\n");
  1841. return -EACCES;
  1842. }
  1843. err = check_helper_mem_access(env, regno,
  1844. meta->map_ptr->value_size, false,
  1845. NULL);
  1846. } else if (arg_type_is_mem_size(arg_type)) {
  1847. bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
  1848. /* remember the mem_size which may be used later
  1849. * to refine return values.
  1850. */
  1851. meta->msize_smax_value = reg->smax_value;
  1852. meta->msize_umax_value = reg->umax_value;
  1853. /* The register is SCALAR_VALUE; the access check
  1854. * happens using its boundaries.
  1855. */
  1856. if (!tnum_is_const(reg->var_off))
  1857. /* For unprivileged variable accesses, disable raw
  1858. * mode so that the program is required to
  1859. * initialize all the memory that the helper could
  1860. * just partially fill up.
  1861. */
  1862. meta = NULL;
  1863. if (reg->smin_value < 0) {
  1864. verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
  1865. regno);
  1866. return -EACCES;
  1867. }
  1868. if (reg->umin_value == 0) {
  1869. err = check_helper_mem_access(env, regno - 1, 0,
  1870. zero_size_allowed,
  1871. meta);
  1872. if (err)
  1873. return err;
  1874. }
  1875. if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
  1876. verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
  1877. regno);
  1878. return -EACCES;
  1879. }
  1880. err = check_helper_mem_access(env, regno - 1,
  1881. reg->umax_value,
  1882. zero_size_allowed, meta);
  1883. }
  1884. return err;
  1885. err_type:
  1886. verbose(env, "R%d type=%s expected=%s\n", regno,
  1887. reg_type_str[type], reg_type_str[expected_type]);
  1888. return -EACCES;
  1889. }
  1890. static int check_map_func_compatibility(struct bpf_verifier_env *env,
  1891. struct bpf_map *map, int func_id)
  1892. {
  1893. if (!map)
  1894. return 0;
  1895. /* We need a two way check, first is from map perspective ... */
  1896. switch (map->map_type) {
  1897. case BPF_MAP_TYPE_PROG_ARRAY:
  1898. if (func_id != BPF_FUNC_tail_call)
  1899. goto error;
  1900. break;
  1901. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  1902. if (func_id != BPF_FUNC_perf_event_read &&
  1903. func_id != BPF_FUNC_perf_event_output &&
  1904. func_id != BPF_FUNC_perf_event_read_value)
  1905. goto error;
  1906. break;
  1907. case BPF_MAP_TYPE_STACK_TRACE:
  1908. if (func_id != BPF_FUNC_get_stackid)
  1909. goto error;
  1910. break;
  1911. case BPF_MAP_TYPE_CGROUP_ARRAY:
  1912. if (func_id != BPF_FUNC_skb_under_cgroup &&
  1913. func_id != BPF_FUNC_current_task_under_cgroup)
  1914. goto error;
  1915. break;
  1916. case BPF_MAP_TYPE_CGROUP_STORAGE:
  1917. if (func_id != BPF_FUNC_get_local_storage)
  1918. goto error;
  1919. break;
  1920. /* devmap returns a pointer to a live net_device ifindex that we cannot
  1921. * allow to be modified from bpf side. So do not allow lookup elements
  1922. * for now.
  1923. */
  1924. case BPF_MAP_TYPE_DEVMAP:
  1925. if (func_id != BPF_FUNC_redirect_map)
  1926. goto error;
  1927. break;
  1928. /* Restrict bpf side of cpumap and xskmap, open when use-cases
  1929. * appear.
  1930. */
  1931. case BPF_MAP_TYPE_CPUMAP:
  1932. case BPF_MAP_TYPE_XSKMAP:
  1933. if (func_id != BPF_FUNC_redirect_map)
  1934. goto error;
  1935. break;
  1936. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  1937. case BPF_MAP_TYPE_HASH_OF_MAPS:
  1938. if (func_id != BPF_FUNC_map_lookup_elem)
  1939. goto error;
  1940. break;
  1941. case BPF_MAP_TYPE_SOCKMAP:
  1942. if (func_id != BPF_FUNC_sk_redirect_map &&
  1943. func_id != BPF_FUNC_sock_map_update &&
  1944. func_id != BPF_FUNC_map_delete_elem &&
  1945. func_id != BPF_FUNC_msg_redirect_map)
  1946. goto error;
  1947. break;
  1948. case BPF_MAP_TYPE_SOCKHASH:
  1949. if (func_id != BPF_FUNC_sk_redirect_hash &&
  1950. func_id != BPF_FUNC_sock_hash_update &&
  1951. func_id != BPF_FUNC_map_delete_elem &&
  1952. func_id != BPF_FUNC_msg_redirect_hash)
  1953. goto error;
  1954. break;
  1955. case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
  1956. if (func_id != BPF_FUNC_sk_select_reuseport)
  1957. goto error;
  1958. break;
  1959. default:
  1960. break;
  1961. }
  1962. /* ... and second from the function itself. */
  1963. switch (func_id) {
  1964. case BPF_FUNC_tail_call:
  1965. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  1966. goto error;
  1967. if (env->subprog_cnt > 1) {
  1968. verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
  1969. return -EINVAL;
  1970. }
  1971. break;
  1972. case BPF_FUNC_perf_event_read:
  1973. case BPF_FUNC_perf_event_output:
  1974. case BPF_FUNC_perf_event_read_value:
  1975. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  1976. goto error;
  1977. break;
  1978. case BPF_FUNC_get_stackid:
  1979. if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
  1980. goto error;
  1981. break;
  1982. case BPF_FUNC_current_task_under_cgroup:
  1983. case BPF_FUNC_skb_under_cgroup:
  1984. if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
  1985. goto error;
  1986. break;
  1987. case BPF_FUNC_redirect_map:
  1988. if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
  1989. map->map_type != BPF_MAP_TYPE_CPUMAP &&
  1990. map->map_type != BPF_MAP_TYPE_XSKMAP)
  1991. goto error;
  1992. break;
  1993. case BPF_FUNC_sk_redirect_map:
  1994. case BPF_FUNC_msg_redirect_map:
  1995. case BPF_FUNC_sock_map_update:
  1996. if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
  1997. goto error;
  1998. break;
  1999. case BPF_FUNC_sk_redirect_hash:
  2000. case BPF_FUNC_msg_redirect_hash:
  2001. case BPF_FUNC_sock_hash_update:
  2002. if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
  2003. goto error;
  2004. break;
  2005. case BPF_FUNC_get_local_storage:
  2006. if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE)
  2007. goto error;
  2008. break;
  2009. case BPF_FUNC_sk_select_reuseport:
  2010. if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
  2011. goto error;
  2012. break;
  2013. default:
  2014. break;
  2015. }
  2016. return 0;
  2017. error:
  2018. verbose(env, "cannot pass map_type %d into func %s#%d\n",
  2019. map->map_type, func_id_name(func_id), func_id);
  2020. return -EINVAL;
  2021. }
  2022. static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
  2023. {
  2024. int count = 0;
  2025. if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
  2026. count++;
  2027. if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
  2028. count++;
  2029. if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
  2030. count++;
  2031. if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
  2032. count++;
  2033. if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
  2034. count++;
  2035. /* We only support one arg being in raw mode at the moment,
  2036. * which is sufficient for the helper functions we have
  2037. * right now.
  2038. */
  2039. return count <= 1;
  2040. }
  2041. static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
  2042. enum bpf_arg_type arg_next)
  2043. {
  2044. return (arg_type_is_mem_ptr(arg_curr) &&
  2045. !arg_type_is_mem_size(arg_next)) ||
  2046. (!arg_type_is_mem_ptr(arg_curr) &&
  2047. arg_type_is_mem_size(arg_next));
  2048. }
  2049. static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
  2050. {
  2051. /* bpf_xxx(..., buf, len) call will access 'len'
  2052. * bytes from memory 'buf'. Both arg types need
  2053. * to be paired, so make sure there's no buggy
  2054. * helper function specification.
  2055. */
  2056. if (arg_type_is_mem_size(fn->arg1_type) ||
  2057. arg_type_is_mem_ptr(fn->arg5_type) ||
  2058. check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
  2059. check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
  2060. check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
  2061. check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
  2062. return false;
  2063. return true;
  2064. }
  2065. static int check_func_proto(const struct bpf_func_proto *fn)
  2066. {
  2067. return check_raw_mode_ok(fn) &&
  2068. check_arg_pair_ok(fn) ? 0 : -EINVAL;
  2069. }
  2070. /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
  2071. * are now invalid, so turn them into unknown SCALAR_VALUE.
  2072. */
  2073. static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
  2074. struct bpf_func_state *state)
  2075. {
  2076. struct bpf_reg_state *regs = state->regs, *reg;
  2077. int i;
  2078. for (i = 0; i < MAX_BPF_REG; i++)
  2079. if (reg_is_pkt_pointer_any(&regs[i]))
  2080. mark_reg_unknown(env, regs, i);
  2081. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  2082. if (state->stack[i].slot_type[0] != STACK_SPILL)
  2083. continue;
  2084. reg = &state->stack[i].spilled_ptr;
  2085. if (reg_is_pkt_pointer_any(reg))
  2086. __mark_reg_unknown(reg);
  2087. }
  2088. }
  2089. static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
  2090. {
  2091. struct bpf_verifier_state *vstate = env->cur_state;
  2092. int i;
  2093. for (i = 0; i <= vstate->curframe; i++)
  2094. __clear_all_pkt_pointers(env, vstate->frame[i]);
  2095. }
  2096. static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  2097. int *insn_idx)
  2098. {
  2099. struct bpf_verifier_state *state = env->cur_state;
  2100. struct bpf_func_state *caller, *callee;
  2101. int i, subprog, target_insn;
  2102. if (state->curframe + 1 >= MAX_CALL_FRAMES) {
  2103. verbose(env, "the call stack of %d frames is too deep\n",
  2104. state->curframe + 2);
  2105. return -E2BIG;
  2106. }
  2107. target_insn = *insn_idx + insn->imm;
  2108. subprog = find_subprog(env, target_insn + 1);
  2109. if (subprog < 0) {
  2110. verbose(env, "verifier bug. No program starts at insn %d\n",
  2111. target_insn + 1);
  2112. return -EFAULT;
  2113. }
  2114. caller = state->frame[state->curframe];
  2115. if (state->frame[state->curframe + 1]) {
  2116. verbose(env, "verifier bug. Frame %d already allocated\n",
  2117. state->curframe + 1);
  2118. return -EFAULT;
  2119. }
  2120. callee = kzalloc(sizeof(*callee), GFP_KERNEL);
  2121. if (!callee)
  2122. return -ENOMEM;
  2123. state->frame[state->curframe + 1] = callee;
  2124. /* callee cannot access r0, r6 - r9 for reading and has to write
  2125. * into its own stack before reading from it.
  2126. * callee can read/write into caller's stack
  2127. */
  2128. init_func_state(env, callee,
  2129. /* remember the callsite, it will be used by bpf_exit */
  2130. *insn_idx /* callsite */,
  2131. state->curframe + 1 /* frameno within this callchain */,
  2132. subprog /* subprog number within this prog */);
  2133. /* copy r1 - r5 args that callee can access */
  2134. for (i = BPF_REG_1; i <= BPF_REG_5; i++)
  2135. callee->regs[i] = caller->regs[i];
  2136. /* after the call regsiters r0 - r5 were scratched */
  2137. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  2138. mark_reg_not_init(env, caller->regs, caller_saved[i]);
  2139. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  2140. }
  2141. /* only increment it after check_reg_arg() finished */
  2142. state->curframe++;
  2143. /* and go analyze first insn of the callee */
  2144. *insn_idx = target_insn;
  2145. if (env->log.level) {
  2146. verbose(env, "caller:\n");
  2147. print_verifier_state(env, caller);
  2148. verbose(env, "callee:\n");
  2149. print_verifier_state(env, callee);
  2150. }
  2151. return 0;
  2152. }
  2153. static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
  2154. {
  2155. struct bpf_verifier_state *state = env->cur_state;
  2156. struct bpf_func_state *caller, *callee;
  2157. struct bpf_reg_state *r0;
  2158. callee = state->frame[state->curframe];
  2159. r0 = &callee->regs[BPF_REG_0];
  2160. if (r0->type == PTR_TO_STACK) {
  2161. /* technically it's ok to return caller's stack pointer
  2162. * (or caller's caller's pointer) back to the caller,
  2163. * since these pointers are valid. Only current stack
  2164. * pointer will be invalid as soon as function exits,
  2165. * but let's be conservative
  2166. */
  2167. verbose(env, "cannot return stack pointer to the caller\n");
  2168. return -EINVAL;
  2169. }
  2170. state->curframe--;
  2171. caller = state->frame[state->curframe];
  2172. /* return to the caller whatever r0 had in the callee */
  2173. caller->regs[BPF_REG_0] = *r0;
  2174. *insn_idx = callee->callsite + 1;
  2175. if (env->log.level) {
  2176. verbose(env, "returning from callee:\n");
  2177. print_verifier_state(env, callee);
  2178. verbose(env, "to caller at %d:\n", *insn_idx);
  2179. print_verifier_state(env, caller);
  2180. }
  2181. /* clear everything in the callee */
  2182. free_func_state(callee);
  2183. state->frame[state->curframe + 1] = NULL;
  2184. return 0;
  2185. }
  2186. static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
  2187. int func_id,
  2188. struct bpf_call_arg_meta *meta)
  2189. {
  2190. struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
  2191. if (ret_type != RET_INTEGER ||
  2192. (func_id != BPF_FUNC_get_stack &&
  2193. func_id != BPF_FUNC_probe_read_str))
  2194. return;
  2195. ret_reg->smax_value = meta->msize_smax_value;
  2196. ret_reg->umax_value = meta->msize_umax_value;
  2197. __reg_deduce_bounds(ret_reg);
  2198. __reg_bound_offset(ret_reg);
  2199. }
  2200. static int
  2201. record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
  2202. int func_id, int insn_idx)
  2203. {
  2204. struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
  2205. if (func_id != BPF_FUNC_tail_call &&
  2206. func_id != BPF_FUNC_map_lookup_elem &&
  2207. func_id != BPF_FUNC_map_update_elem &&
  2208. func_id != BPF_FUNC_map_delete_elem)
  2209. return 0;
  2210. if (meta->map_ptr == NULL) {
  2211. verbose(env, "kernel subsystem misconfigured verifier\n");
  2212. return -EINVAL;
  2213. }
  2214. if (!BPF_MAP_PTR(aux->map_state))
  2215. bpf_map_ptr_store(aux, meta->map_ptr,
  2216. meta->map_ptr->unpriv_array);
  2217. else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
  2218. bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
  2219. meta->map_ptr->unpriv_array);
  2220. return 0;
  2221. }
  2222. static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
  2223. {
  2224. const struct bpf_func_proto *fn = NULL;
  2225. struct bpf_reg_state *regs;
  2226. struct bpf_call_arg_meta meta;
  2227. bool changes_data;
  2228. int i, err;
  2229. /* find function prototype */
  2230. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  2231. verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
  2232. func_id);
  2233. return -EINVAL;
  2234. }
  2235. if (env->ops->get_func_proto)
  2236. fn = env->ops->get_func_proto(func_id, env->prog);
  2237. if (!fn) {
  2238. verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
  2239. func_id);
  2240. return -EINVAL;
  2241. }
  2242. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  2243. if (!env->prog->gpl_compatible && fn->gpl_only) {
  2244. verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
  2245. return -EINVAL;
  2246. }
  2247. /* With LD_ABS/IND some JITs save/restore skb from r1. */
  2248. changes_data = bpf_helper_changes_pkt_data(fn->func);
  2249. if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
  2250. verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
  2251. func_id_name(func_id), func_id);
  2252. return -EINVAL;
  2253. }
  2254. memset(&meta, 0, sizeof(meta));
  2255. meta.pkt_access = fn->pkt_access;
  2256. err = check_func_proto(fn);
  2257. if (err) {
  2258. verbose(env, "kernel subsystem misconfigured func %s#%d\n",
  2259. func_id_name(func_id), func_id);
  2260. return err;
  2261. }
  2262. /* check args */
  2263. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
  2264. if (err)
  2265. return err;
  2266. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
  2267. if (err)
  2268. return err;
  2269. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
  2270. if (err)
  2271. return err;
  2272. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
  2273. if (err)
  2274. return err;
  2275. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
  2276. if (err)
  2277. return err;
  2278. err = record_func_map(env, &meta, func_id, insn_idx);
  2279. if (err)
  2280. return err;
  2281. /* Mark slots with STACK_MISC in case of raw mode, stack offset
  2282. * is inferred from register state.
  2283. */
  2284. for (i = 0; i < meta.access_size; i++) {
  2285. err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
  2286. BPF_WRITE, -1, false);
  2287. if (err)
  2288. return err;
  2289. }
  2290. regs = cur_regs(env);
  2291. /* check that flags argument in get_local_storage(map, flags) is 0,
  2292. * this is required because get_local_storage() can't return an error.
  2293. */
  2294. if (func_id == BPF_FUNC_get_local_storage &&
  2295. !register_is_null(&regs[BPF_REG_2])) {
  2296. verbose(env, "get_local_storage() doesn't support non-zero flags\n");
  2297. return -EINVAL;
  2298. }
  2299. /* reset caller saved regs */
  2300. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  2301. mark_reg_not_init(env, regs, caller_saved[i]);
  2302. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  2303. }
  2304. /* update return register (already marked as written above) */
  2305. if (fn->ret_type == RET_INTEGER) {
  2306. /* sets type to SCALAR_VALUE */
  2307. mark_reg_unknown(env, regs, BPF_REG_0);
  2308. } else if (fn->ret_type == RET_VOID) {
  2309. regs[BPF_REG_0].type = NOT_INIT;
  2310. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
  2311. fn->ret_type == RET_PTR_TO_MAP_VALUE) {
  2312. if (fn->ret_type == RET_PTR_TO_MAP_VALUE)
  2313. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
  2314. else
  2315. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  2316. /* There is no offset yet applied, variable or fixed */
  2317. mark_reg_known_zero(env, regs, BPF_REG_0);
  2318. regs[BPF_REG_0].off = 0;
  2319. /* remember map_ptr, so that check_map_access()
  2320. * can check 'value_size' boundary of memory access
  2321. * to map element returned from bpf_map_lookup_elem()
  2322. */
  2323. if (meta.map_ptr == NULL) {
  2324. verbose(env,
  2325. "kernel subsystem misconfigured verifier\n");
  2326. return -EINVAL;
  2327. }
  2328. regs[BPF_REG_0].map_ptr = meta.map_ptr;
  2329. regs[BPF_REG_0].id = ++env->id_gen;
  2330. } else {
  2331. verbose(env, "unknown return type %d of func %s#%d\n",
  2332. fn->ret_type, func_id_name(func_id), func_id);
  2333. return -EINVAL;
  2334. }
  2335. do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
  2336. err = check_map_func_compatibility(env, meta.map_ptr, func_id);
  2337. if (err)
  2338. return err;
  2339. if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
  2340. const char *err_str;
  2341. #ifdef CONFIG_PERF_EVENTS
  2342. err = get_callchain_buffers(sysctl_perf_event_max_stack);
  2343. err_str = "cannot get callchain buffer for func %s#%d\n";
  2344. #else
  2345. err = -ENOTSUPP;
  2346. err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
  2347. #endif
  2348. if (err) {
  2349. verbose(env, err_str, func_id_name(func_id), func_id);
  2350. return err;
  2351. }
  2352. env->prog->has_callchain_buf = true;
  2353. }
  2354. if (changes_data)
  2355. clear_all_pkt_pointers(env);
  2356. return 0;
  2357. }
  2358. static bool signed_add_overflows(s64 a, s64 b)
  2359. {
  2360. /* Do the add in u64, where overflow is well-defined */
  2361. s64 res = (s64)((u64)a + (u64)b);
  2362. if (b < 0)
  2363. return res > a;
  2364. return res < a;
  2365. }
  2366. static bool signed_sub_overflows(s64 a, s64 b)
  2367. {
  2368. /* Do the sub in u64, where overflow is well-defined */
  2369. s64 res = (s64)((u64)a - (u64)b);
  2370. if (b < 0)
  2371. return res < a;
  2372. return res > a;
  2373. }
  2374. static bool check_reg_sane_offset(struct bpf_verifier_env *env,
  2375. const struct bpf_reg_state *reg,
  2376. enum bpf_reg_type type)
  2377. {
  2378. bool known = tnum_is_const(reg->var_off);
  2379. s64 val = reg->var_off.value;
  2380. s64 smin = reg->smin_value;
  2381. if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
  2382. verbose(env, "math between %s pointer and %lld is not allowed\n",
  2383. reg_type_str[type], val);
  2384. return false;
  2385. }
  2386. if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
  2387. verbose(env, "%s pointer offset %d is not allowed\n",
  2388. reg_type_str[type], reg->off);
  2389. return false;
  2390. }
  2391. if (smin == S64_MIN) {
  2392. verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
  2393. reg_type_str[type]);
  2394. return false;
  2395. }
  2396. if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
  2397. verbose(env, "value %lld makes %s pointer be out of bounds\n",
  2398. smin, reg_type_str[type]);
  2399. return false;
  2400. }
  2401. return true;
  2402. }
  2403. /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
  2404. * Caller should also handle BPF_MOV case separately.
  2405. * If we return -EACCES, caller may want to try again treating pointer as a
  2406. * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
  2407. */
  2408. static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
  2409. struct bpf_insn *insn,
  2410. const struct bpf_reg_state *ptr_reg,
  2411. const struct bpf_reg_state *off_reg)
  2412. {
  2413. struct bpf_verifier_state *vstate = env->cur_state;
  2414. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2415. struct bpf_reg_state *regs = state->regs, *dst_reg;
  2416. bool known = tnum_is_const(off_reg->var_off);
  2417. s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
  2418. smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
  2419. u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
  2420. umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
  2421. u8 opcode = BPF_OP(insn->code);
  2422. u32 dst = insn->dst_reg;
  2423. dst_reg = &regs[dst];
  2424. if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
  2425. smin_val > smax_val || umin_val > umax_val) {
  2426. /* Taint dst register if offset had invalid bounds derived from
  2427. * e.g. dead branches.
  2428. */
  2429. __mark_reg_unknown(dst_reg);
  2430. return 0;
  2431. }
  2432. if (BPF_CLASS(insn->code) != BPF_ALU64) {
  2433. /* 32-bit ALU ops on pointers produce (meaningless) scalars */
  2434. verbose(env,
  2435. "R%d 32-bit pointer arithmetic prohibited\n",
  2436. dst);
  2437. return -EACCES;
  2438. }
  2439. if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  2440. verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
  2441. dst);
  2442. return -EACCES;
  2443. }
  2444. if (ptr_reg->type == CONST_PTR_TO_MAP) {
  2445. verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
  2446. dst);
  2447. return -EACCES;
  2448. }
  2449. if (ptr_reg->type == PTR_TO_PACKET_END) {
  2450. verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
  2451. dst);
  2452. return -EACCES;
  2453. }
  2454. /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
  2455. * The id may be overwritten later if we create a new variable offset.
  2456. */
  2457. dst_reg->type = ptr_reg->type;
  2458. dst_reg->id = ptr_reg->id;
  2459. if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
  2460. !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
  2461. return -EINVAL;
  2462. switch (opcode) {
  2463. case BPF_ADD:
  2464. /* We can take a fixed offset as long as it doesn't overflow
  2465. * the s32 'off' field
  2466. */
  2467. if (known && (ptr_reg->off + smin_val ==
  2468. (s64)(s32)(ptr_reg->off + smin_val))) {
  2469. /* pointer += K. Accumulate it into fixed offset */
  2470. dst_reg->smin_value = smin_ptr;
  2471. dst_reg->smax_value = smax_ptr;
  2472. dst_reg->umin_value = umin_ptr;
  2473. dst_reg->umax_value = umax_ptr;
  2474. dst_reg->var_off = ptr_reg->var_off;
  2475. dst_reg->off = ptr_reg->off + smin_val;
  2476. dst_reg->range = ptr_reg->range;
  2477. break;
  2478. }
  2479. /* A new variable offset is created. Note that off_reg->off
  2480. * == 0, since it's a scalar.
  2481. * dst_reg gets the pointer type and since some positive
  2482. * integer value was added to the pointer, give it a new 'id'
  2483. * if it's a PTR_TO_PACKET.
  2484. * this creates a new 'base' pointer, off_reg (variable) gets
  2485. * added into the variable offset, and we copy the fixed offset
  2486. * from ptr_reg.
  2487. */
  2488. if (signed_add_overflows(smin_ptr, smin_val) ||
  2489. signed_add_overflows(smax_ptr, smax_val)) {
  2490. dst_reg->smin_value = S64_MIN;
  2491. dst_reg->smax_value = S64_MAX;
  2492. } else {
  2493. dst_reg->smin_value = smin_ptr + smin_val;
  2494. dst_reg->smax_value = smax_ptr + smax_val;
  2495. }
  2496. if (umin_ptr + umin_val < umin_ptr ||
  2497. umax_ptr + umax_val < umax_ptr) {
  2498. dst_reg->umin_value = 0;
  2499. dst_reg->umax_value = U64_MAX;
  2500. } else {
  2501. dst_reg->umin_value = umin_ptr + umin_val;
  2502. dst_reg->umax_value = umax_ptr + umax_val;
  2503. }
  2504. dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
  2505. dst_reg->off = ptr_reg->off;
  2506. if (reg_is_pkt_pointer(ptr_reg)) {
  2507. dst_reg->id = ++env->id_gen;
  2508. /* something was added to pkt_ptr, set range to zero */
  2509. dst_reg->range = 0;
  2510. }
  2511. break;
  2512. case BPF_SUB:
  2513. if (dst_reg == off_reg) {
  2514. /* scalar -= pointer. Creates an unknown scalar */
  2515. verbose(env, "R%d tried to subtract pointer from scalar\n",
  2516. dst);
  2517. return -EACCES;
  2518. }
  2519. /* We don't allow subtraction from FP, because (according to
  2520. * test_verifier.c test "invalid fp arithmetic", JITs might not
  2521. * be able to deal with it.
  2522. */
  2523. if (ptr_reg->type == PTR_TO_STACK) {
  2524. verbose(env, "R%d subtraction from stack pointer prohibited\n",
  2525. dst);
  2526. return -EACCES;
  2527. }
  2528. if (known && (ptr_reg->off - smin_val ==
  2529. (s64)(s32)(ptr_reg->off - smin_val))) {
  2530. /* pointer -= K. Subtract it from fixed offset */
  2531. dst_reg->smin_value = smin_ptr;
  2532. dst_reg->smax_value = smax_ptr;
  2533. dst_reg->umin_value = umin_ptr;
  2534. dst_reg->umax_value = umax_ptr;
  2535. dst_reg->var_off = ptr_reg->var_off;
  2536. dst_reg->id = ptr_reg->id;
  2537. dst_reg->off = ptr_reg->off - smin_val;
  2538. dst_reg->range = ptr_reg->range;
  2539. break;
  2540. }
  2541. /* A new variable offset is created. If the subtrahend is known
  2542. * nonnegative, then any reg->range we had before is still good.
  2543. */
  2544. if (signed_sub_overflows(smin_ptr, smax_val) ||
  2545. signed_sub_overflows(smax_ptr, smin_val)) {
  2546. /* Overflow possible, we know nothing */
  2547. dst_reg->smin_value = S64_MIN;
  2548. dst_reg->smax_value = S64_MAX;
  2549. } else {
  2550. dst_reg->smin_value = smin_ptr - smax_val;
  2551. dst_reg->smax_value = smax_ptr - smin_val;
  2552. }
  2553. if (umin_ptr < umax_val) {
  2554. /* Overflow possible, we know nothing */
  2555. dst_reg->umin_value = 0;
  2556. dst_reg->umax_value = U64_MAX;
  2557. } else {
  2558. /* Cannot overflow (as long as bounds are consistent) */
  2559. dst_reg->umin_value = umin_ptr - umax_val;
  2560. dst_reg->umax_value = umax_ptr - umin_val;
  2561. }
  2562. dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
  2563. dst_reg->off = ptr_reg->off;
  2564. if (reg_is_pkt_pointer(ptr_reg)) {
  2565. dst_reg->id = ++env->id_gen;
  2566. /* something was added to pkt_ptr, set range to zero */
  2567. if (smin_val < 0)
  2568. dst_reg->range = 0;
  2569. }
  2570. break;
  2571. case BPF_AND:
  2572. case BPF_OR:
  2573. case BPF_XOR:
  2574. /* bitwise ops on pointers are troublesome, prohibit. */
  2575. verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
  2576. dst, bpf_alu_string[opcode >> 4]);
  2577. return -EACCES;
  2578. default:
  2579. /* other operators (e.g. MUL,LSH) produce non-pointer results */
  2580. verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
  2581. dst, bpf_alu_string[opcode >> 4]);
  2582. return -EACCES;
  2583. }
  2584. if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
  2585. return -EINVAL;
  2586. __update_reg_bounds(dst_reg);
  2587. __reg_deduce_bounds(dst_reg);
  2588. __reg_bound_offset(dst_reg);
  2589. return 0;
  2590. }
  2591. /* WARNING: This function does calculations on 64-bit values, but the actual
  2592. * execution may occur on 32-bit values. Therefore, things like bitshifts
  2593. * need extra checks in the 32-bit case.
  2594. */
  2595. static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
  2596. struct bpf_insn *insn,
  2597. struct bpf_reg_state *dst_reg,
  2598. struct bpf_reg_state src_reg)
  2599. {
  2600. struct bpf_reg_state *regs = cur_regs(env);
  2601. u8 opcode = BPF_OP(insn->code);
  2602. bool src_known, dst_known;
  2603. s64 smin_val, smax_val;
  2604. u64 umin_val, umax_val;
  2605. u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
  2606. smin_val = src_reg.smin_value;
  2607. smax_val = src_reg.smax_value;
  2608. umin_val = src_reg.umin_value;
  2609. umax_val = src_reg.umax_value;
  2610. src_known = tnum_is_const(src_reg.var_off);
  2611. dst_known = tnum_is_const(dst_reg->var_off);
  2612. if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
  2613. smin_val > smax_val || umin_val > umax_val) {
  2614. /* Taint dst register if offset had invalid bounds derived from
  2615. * e.g. dead branches.
  2616. */
  2617. __mark_reg_unknown(dst_reg);
  2618. return 0;
  2619. }
  2620. if (!src_known &&
  2621. opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
  2622. __mark_reg_unknown(dst_reg);
  2623. return 0;
  2624. }
  2625. switch (opcode) {
  2626. case BPF_ADD:
  2627. if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
  2628. signed_add_overflows(dst_reg->smax_value, smax_val)) {
  2629. dst_reg->smin_value = S64_MIN;
  2630. dst_reg->smax_value = S64_MAX;
  2631. } else {
  2632. dst_reg->smin_value += smin_val;
  2633. dst_reg->smax_value += smax_val;
  2634. }
  2635. if (dst_reg->umin_value + umin_val < umin_val ||
  2636. dst_reg->umax_value + umax_val < umax_val) {
  2637. dst_reg->umin_value = 0;
  2638. dst_reg->umax_value = U64_MAX;
  2639. } else {
  2640. dst_reg->umin_value += umin_val;
  2641. dst_reg->umax_value += umax_val;
  2642. }
  2643. dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
  2644. break;
  2645. case BPF_SUB:
  2646. if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
  2647. signed_sub_overflows(dst_reg->smax_value, smin_val)) {
  2648. /* Overflow possible, we know nothing */
  2649. dst_reg->smin_value = S64_MIN;
  2650. dst_reg->smax_value = S64_MAX;
  2651. } else {
  2652. dst_reg->smin_value -= smax_val;
  2653. dst_reg->smax_value -= smin_val;
  2654. }
  2655. if (dst_reg->umin_value < umax_val) {
  2656. /* Overflow possible, we know nothing */
  2657. dst_reg->umin_value = 0;
  2658. dst_reg->umax_value = U64_MAX;
  2659. } else {
  2660. /* Cannot overflow (as long as bounds are consistent) */
  2661. dst_reg->umin_value -= umax_val;
  2662. dst_reg->umax_value -= umin_val;
  2663. }
  2664. dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
  2665. break;
  2666. case BPF_MUL:
  2667. dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
  2668. if (smin_val < 0 || dst_reg->smin_value < 0) {
  2669. /* Ain't nobody got time to multiply that sign */
  2670. __mark_reg_unbounded(dst_reg);
  2671. __update_reg_bounds(dst_reg);
  2672. break;
  2673. }
  2674. /* Both values are positive, so we can work with unsigned and
  2675. * copy the result to signed (unless it exceeds S64_MAX).
  2676. */
  2677. if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
  2678. /* Potential overflow, we know nothing */
  2679. __mark_reg_unbounded(dst_reg);
  2680. /* (except what we can learn from the var_off) */
  2681. __update_reg_bounds(dst_reg);
  2682. break;
  2683. }
  2684. dst_reg->umin_value *= umin_val;
  2685. dst_reg->umax_value *= umax_val;
  2686. if (dst_reg->umax_value > S64_MAX) {
  2687. /* Overflow possible, we know nothing */
  2688. dst_reg->smin_value = S64_MIN;
  2689. dst_reg->smax_value = S64_MAX;
  2690. } else {
  2691. dst_reg->smin_value = dst_reg->umin_value;
  2692. dst_reg->smax_value = dst_reg->umax_value;
  2693. }
  2694. break;
  2695. case BPF_AND:
  2696. if (src_known && dst_known) {
  2697. __mark_reg_known(dst_reg, dst_reg->var_off.value &
  2698. src_reg.var_off.value);
  2699. break;
  2700. }
  2701. /* We get our minimum from the var_off, since that's inherently
  2702. * bitwise. Our maximum is the minimum of the operands' maxima.
  2703. */
  2704. dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
  2705. dst_reg->umin_value = dst_reg->var_off.value;
  2706. dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
  2707. if (dst_reg->smin_value < 0 || smin_val < 0) {
  2708. /* Lose signed bounds when ANDing negative numbers,
  2709. * ain't nobody got time for that.
  2710. */
  2711. dst_reg->smin_value = S64_MIN;
  2712. dst_reg->smax_value = S64_MAX;
  2713. } else {
  2714. /* ANDing two positives gives a positive, so safe to
  2715. * cast result into s64.
  2716. */
  2717. dst_reg->smin_value = dst_reg->umin_value;
  2718. dst_reg->smax_value = dst_reg->umax_value;
  2719. }
  2720. /* We may learn something more from the var_off */
  2721. __update_reg_bounds(dst_reg);
  2722. break;
  2723. case BPF_OR:
  2724. if (src_known && dst_known) {
  2725. __mark_reg_known(dst_reg, dst_reg->var_off.value |
  2726. src_reg.var_off.value);
  2727. break;
  2728. }
  2729. /* We get our maximum from the var_off, and our minimum is the
  2730. * maximum of the operands' minima
  2731. */
  2732. dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
  2733. dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
  2734. dst_reg->umax_value = dst_reg->var_off.value |
  2735. dst_reg->var_off.mask;
  2736. if (dst_reg->smin_value < 0 || smin_val < 0) {
  2737. /* Lose signed bounds when ORing negative numbers,
  2738. * ain't nobody got time for that.
  2739. */
  2740. dst_reg->smin_value = S64_MIN;
  2741. dst_reg->smax_value = S64_MAX;
  2742. } else {
  2743. /* ORing two positives gives a positive, so safe to
  2744. * cast result into s64.
  2745. */
  2746. dst_reg->smin_value = dst_reg->umin_value;
  2747. dst_reg->smax_value = dst_reg->umax_value;
  2748. }
  2749. /* We may learn something more from the var_off */
  2750. __update_reg_bounds(dst_reg);
  2751. break;
  2752. case BPF_LSH:
  2753. if (umax_val >= insn_bitness) {
  2754. /* Shifts greater than 31 or 63 are undefined.
  2755. * This includes shifts by a negative number.
  2756. */
  2757. mark_reg_unknown(env, regs, insn->dst_reg);
  2758. break;
  2759. }
  2760. /* We lose all sign bit information (except what we can pick
  2761. * up from var_off)
  2762. */
  2763. dst_reg->smin_value = S64_MIN;
  2764. dst_reg->smax_value = S64_MAX;
  2765. /* If we might shift our top bit out, then we know nothing */
  2766. if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
  2767. dst_reg->umin_value = 0;
  2768. dst_reg->umax_value = U64_MAX;
  2769. } else {
  2770. dst_reg->umin_value <<= umin_val;
  2771. dst_reg->umax_value <<= umax_val;
  2772. }
  2773. dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
  2774. /* We may learn something more from the var_off */
  2775. __update_reg_bounds(dst_reg);
  2776. break;
  2777. case BPF_RSH:
  2778. if (umax_val >= insn_bitness) {
  2779. /* Shifts greater than 31 or 63 are undefined.
  2780. * This includes shifts by a negative number.
  2781. */
  2782. mark_reg_unknown(env, regs, insn->dst_reg);
  2783. break;
  2784. }
  2785. /* BPF_RSH is an unsigned shift. If the value in dst_reg might
  2786. * be negative, then either:
  2787. * 1) src_reg might be zero, so the sign bit of the result is
  2788. * unknown, so we lose our signed bounds
  2789. * 2) it's known negative, thus the unsigned bounds capture the
  2790. * signed bounds
  2791. * 3) the signed bounds cross zero, so they tell us nothing
  2792. * about the result
  2793. * If the value in dst_reg is known nonnegative, then again the
  2794. * unsigned bounts capture the signed bounds.
  2795. * Thus, in all cases it suffices to blow away our signed bounds
  2796. * and rely on inferring new ones from the unsigned bounds and
  2797. * var_off of the result.
  2798. */
  2799. dst_reg->smin_value = S64_MIN;
  2800. dst_reg->smax_value = S64_MAX;
  2801. dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
  2802. dst_reg->umin_value >>= umax_val;
  2803. dst_reg->umax_value >>= umin_val;
  2804. /* We may learn something more from the var_off */
  2805. __update_reg_bounds(dst_reg);
  2806. break;
  2807. case BPF_ARSH:
  2808. if (umax_val >= insn_bitness) {
  2809. /* Shifts greater than 31 or 63 are undefined.
  2810. * This includes shifts by a negative number.
  2811. */
  2812. mark_reg_unknown(env, regs, insn->dst_reg);
  2813. break;
  2814. }
  2815. /* Upon reaching here, src_known is true and
  2816. * umax_val is equal to umin_val.
  2817. */
  2818. dst_reg->smin_value >>= umin_val;
  2819. dst_reg->smax_value >>= umin_val;
  2820. dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
  2821. /* blow away the dst_reg umin_value/umax_value and rely on
  2822. * dst_reg var_off to refine the result.
  2823. */
  2824. dst_reg->umin_value = 0;
  2825. dst_reg->umax_value = U64_MAX;
  2826. __update_reg_bounds(dst_reg);
  2827. break;
  2828. default:
  2829. mark_reg_unknown(env, regs, insn->dst_reg);
  2830. break;
  2831. }
  2832. if (BPF_CLASS(insn->code) != BPF_ALU64) {
  2833. /* 32-bit ALU ops are (32,32)->32 */
  2834. coerce_reg_to_size(dst_reg, 4);
  2835. coerce_reg_to_size(&src_reg, 4);
  2836. }
  2837. __reg_deduce_bounds(dst_reg);
  2838. __reg_bound_offset(dst_reg);
  2839. return 0;
  2840. }
  2841. /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
  2842. * and var_off.
  2843. */
  2844. static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
  2845. struct bpf_insn *insn)
  2846. {
  2847. struct bpf_verifier_state *vstate = env->cur_state;
  2848. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2849. struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
  2850. struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
  2851. u8 opcode = BPF_OP(insn->code);
  2852. dst_reg = &regs[insn->dst_reg];
  2853. src_reg = NULL;
  2854. if (dst_reg->type != SCALAR_VALUE)
  2855. ptr_reg = dst_reg;
  2856. if (BPF_SRC(insn->code) == BPF_X) {
  2857. src_reg = &regs[insn->src_reg];
  2858. if (src_reg->type != SCALAR_VALUE) {
  2859. if (dst_reg->type != SCALAR_VALUE) {
  2860. /* Combining two pointers by any ALU op yields
  2861. * an arbitrary scalar. Disallow all math except
  2862. * pointer subtraction
  2863. */
  2864. if (opcode == BPF_SUB){
  2865. mark_reg_unknown(env, regs, insn->dst_reg);
  2866. return 0;
  2867. }
  2868. verbose(env, "R%d pointer %s pointer prohibited\n",
  2869. insn->dst_reg,
  2870. bpf_alu_string[opcode >> 4]);
  2871. return -EACCES;
  2872. } else {
  2873. /* scalar += pointer
  2874. * This is legal, but we have to reverse our
  2875. * src/dest handling in computing the range
  2876. */
  2877. return adjust_ptr_min_max_vals(env, insn,
  2878. src_reg, dst_reg);
  2879. }
  2880. } else if (ptr_reg) {
  2881. /* pointer += scalar */
  2882. return adjust_ptr_min_max_vals(env, insn,
  2883. dst_reg, src_reg);
  2884. }
  2885. } else {
  2886. /* Pretend the src is a reg with a known value, since we only
  2887. * need to be able to read from this state.
  2888. */
  2889. off_reg.type = SCALAR_VALUE;
  2890. __mark_reg_known(&off_reg, insn->imm);
  2891. src_reg = &off_reg;
  2892. if (ptr_reg) /* pointer += K */
  2893. return adjust_ptr_min_max_vals(env, insn,
  2894. ptr_reg, src_reg);
  2895. }
  2896. /* Got here implies adding two SCALAR_VALUEs */
  2897. if (WARN_ON_ONCE(ptr_reg)) {
  2898. print_verifier_state(env, state);
  2899. verbose(env, "verifier internal error: unexpected ptr_reg\n");
  2900. return -EINVAL;
  2901. }
  2902. if (WARN_ON(!src_reg)) {
  2903. print_verifier_state(env, state);
  2904. verbose(env, "verifier internal error: no src_reg\n");
  2905. return -EINVAL;
  2906. }
  2907. return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
  2908. }
  2909. /* check validity of 32-bit and 64-bit arithmetic operations */
  2910. static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2911. {
  2912. struct bpf_reg_state *regs = cur_regs(env);
  2913. u8 opcode = BPF_OP(insn->code);
  2914. int err;
  2915. if (opcode == BPF_END || opcode == BPF_NEG) {
  2916. if (opcode == BPF_NEG) {
  2917. if (BPF_SRC(insn->code) != 0 ||
  2918. insn->src_reg != BPF_REG_0 ||
  2919. insn->off != 0 || insn->imm != 0) {
  2920. verbose(env, "BPF_NEG uses reserved fields\n");
  2921. return -EINVAL;
  2922. }
  2923. } else {
  2924. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  2925. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
  2926. BPF_CLASS(insn->code) == BPF_ALU64) {
  2927. verbose(env, "BPF_END uses reserved fields\n");
  2928. return -EINVAL;
  2929. }
  2930. }
  2931. /* check src operand */
  2932. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  2933. if (err)
  2934. return err;
  2935. if (is_pointer_value(env, insn->dst_reg)) {
  2936. verbose(env, "R%d pointer arithmetic prohibited\n",
  2937. insn->dst_reg);
  2938. return -EACCES;
  2939. }
  2940. /* check dest operand */
  2941. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  2942. if (err)
  2943. return err;
  2944. } else if (opcode == BPF_MOV) {
  2945. if (BPF_SRC(insn->code) == BPF_X) {
  2946. if (insn->imm != 0 || insn->off != 0) {
  2947. verbose(env, "BPF_MOV uses reserved fields\n");
  2948. return -EINVAL;
  2949. }
  2950. /* check src operand */
  2951. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  2952. if (err)
  2953. return err;
  2954. } else {
  2955. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  2956. verbose(env, "BPF_MOV uses reserved fields\n");
  2957. return -EINVAL;
  2958. }
  2959. }
  2960. /* check dest operand, mark as required later */
  2961. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  2962. if (err)
  2963. return err;
  2964. if (BPF_SRC(insn->code) == BPF_X) {
  2965. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  2966. /* case: R1 = R2
  2967. * copy register state to dest reg
  2968. */
  2969. regs[insn->dst_reg] = regs[insn->src_reg];
  2970. regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
  2971. } else {
  2972. /* R1 = (u32) R2 */
  2973. if (is_pointer_value(env, insn->src_reg)) {
  2974. verbose(env,
  2975. "R%d partial copy of pointer\n",
  2976. insn->src_reg);
  2977. return -EACCES;
  2978. }
  2979. mark_reg_unknown(env, regs, insn->dst_reg);
  2980. coerce_reg_to_size(&regs[insn->dst_reg], 4);
  2981. }
  2982. } else {
  2983. /* case: R = imm
  2984. * remember the value we stored into this reg
  2985. */
  2986. /* clear any state __mark_reg_known doesn't set */
  2987. mark_reg_unknown(env, regs, insn->dst_reg);
  2988. regs[insn->dst_reg].type = SCALAR_VALUE;
  2989. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  2990. __mark_reg_known(regs + insn->dst_reg,
  2991. insn->imm);
  2992. } else {
  2993. __mark_reg_known(regs + insn->dst_reg,
  2994. (u32)insn->imm);
  2995. }
  2996. }
  2997. } else if (opcode > BPF_END) {
  2998. verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
  2999. return -EINVAL;
  3000. } else { /* all other ALU ops: and, sub, xor, add, ... */
  3001. if (BPF_SRC(insn->code) == BPF_X) {
  3002. if (insn->imm != 0 || insn->off != 0) {
  3003. verbose(env, "BPF_ALU uses reserved fields\n");
  3004. return -EINVAL;
  3005. }
  3006. /* check src1 operand */
  3007. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  3008. if (err)
  3009. return err;
  3010. } else {
  3011. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  3012. verbose(env, "BPF_ALU uses reserved fields\n");
  3013. return -EINVAL;
  3014. }
  3015. }
  3016. /* check src2 operand */
  3017. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  3018. if (err)
  3019. return err;
  3020. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  3021. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  3022. verbose(env, "div by zero\n");
  3023. return -EINVAL;
  3024. }
  3025. if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
  3026. verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
  3027. return -EINVAL;
  3028. }
  3029. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  3030. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  3031. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  3032. if (insn->imm < 0 || insn->imm >= size) {
  3033. verbose(env, "invalid shift %d\n", insn->imm);
  3034. return -EINVAL;
  3035. }
  3036. }
  3037. /* check dest operand */
  3038. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  3039. if (err)
  3040. return err;
  3041. return adjust_reg_min_max_vals(env, insn);
  3042. }
  3043. return 0;
  3044. }
  3045. static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
  3046. struct bpf_reg_state *dst_reg,
  3047. enum bpf_reg_type type,
  3048. bool range_right_open)
  3049. {
  3050. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  3051. struct bpf_reg_state *regs = state->regs, *reg;
  3052. u16 new_range;
  3053. int i, j;
  3054. if (dst_reg->off < 0 ||
  3055. (dst_reg->off == 0 && range_right_open))
  3056. /* This doesn't give us any range */
  3057. return;
  3058. if (dst_reg->umax_value > MAX_PACKET_OFF ||
  3059. dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
  3060. /* Risk of overflow. For instance, ptr + (1<<63) may be less
  3061. * than pkt_end, but that's because it's also less than pkt.
  3062. */
  3063. return;
  3064. new_range = dst_reg->off;
  3065. if (range_right_open)
  3066. new_range--;
  3067. /* Examples for register markings:
  3068. *
  3069. * pkt_data in dst register:
  3070. *
  3071. * r2 = r3;
  3072. * r2 += 8;
  3073. * if (r2 > pkt_end) goto <handle exception>
  3074. * <access okay>
  3075. *
  3076. * r2 = r3;
  3077. * r2 += 8;
  3078. * if (r2 < pkt_end) goto <access okay>
  3079. * <handle exception>
  3080. *
  3081. * Where:
  3082. * r2 == dst_reg, pkt_end == src_reg
  3083. * r2=pkt(id=n,off=8,r=0)
  3084. * r3=pkt(id=n,off=0,r=0)
  3085. *
  3086. * pkt_data in src register:
  3087. *
  3088. * r2 = r3;
  3089. * r2 += 8;
  3090. * if (pkt_end >= r2) goto <access okay>
  3091. * <handle exception>
  3092. *
  3093. * r2 = r3;
  3094. * r2 += 8;
  3095. * if (pkt_end <= r2) goto <handle exception>
  3096. * <access okay>
  3097. *
  3098. * Where:
  3099. * pkt_end == dst_reg, r2 == src_reg
  3100. * r2=pkt(id=n,off=8,r=0)
  3101. * r3=pkt(id=n,off=0,r=0)
  3102. *
  3103. * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
  3104. * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
  3105. * and [r3, r3 + 8-1) respectively is safe to access depending on
  3106. * the check.
  3107. */
  3108. /* If our ids match, then we must have the same max_value. And we
  3109. * don't care about the other reg's fixed offset, since if it's too big
  3110. * the range won't allow anything.
  3111. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
  3112. */
  3113. for (i = 0; i < MAX_BPF_REG; i++)
  3114. if (regs[i].type == type && regs[i].id == dst_reg->id)
  3115. /* keep the maximum range already checked */
  3116. regs[i].range = max(regs[i].range, new_range);
  3117. for (j = 0; j <= vstate->curframe; j++) {
  3118. state = vstate->frame[j];
  3119. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  3120. if (state->stack[i].slot_type[0] != STACK_SPILL)
  3121. continue;
  3122. reg = &state->stack[i].spilled_ptr;
  3123. if (reg->type == type && reg->id == dst_reg->id)
  3124. reg->range = max(reg->range, new_range);
  3125. }
  3126. }
  3127. }
  3128. /* Adjusts the register min/max values in the case that the dst_reg is the
  3129. * variable register that we are working on, and src_reg is a constant or we're
  3130. * simply doing a BPF_K check.
  3131. * In JEQ/JNE cases we also adjust the var_off values.
  3132. */
  3133. static void reg_set_min_max(struct bpf_reg_state *true_reg,
  3134. struct bpf_reg_state *false_reg, u64 val,
  3135. u8 opcode)
  3136. {
  3137. /* If the dst_reg is a pointer, we can't learn anything about its
  3138. * variable offset from the compare (unless src_reg were a pointer into
  3139. * the same object, but we don't bother with that.
  3140. * Since false_reg and true_reg have the same type by construction, we
  3141. * only need to check one of them for pointerness.
  3142. */
  3143. if (__is_pointer_value(false, false_reg))
  3144. return;
  3145. switch (opcode) {
  3146. case BPF_JEQ:
  3147. /* If this is false then we know nothing Jon Snow, but if it is
  3148. * true then we know for sure.
  3149. */
  3150. __mark_reg_known(true_reg, val);
  3151. break;
  3152. case BPF_JNE:
  3153. /* If this is true we know nothing Jon Snow, but if it is false
  3154. * we know the value for sure;
  3155. */
  3156. __mark_reg_known(false_reg, val);
  3157. break;
  3158. case BPF_JGT:
  3159. false_reg->umax_value = min(false_reg->umax_value, val);
  3160. true_reg->umin_value = max(true_reg->umin_value, val + 1);
  3161. break;
  3162. case BPF_JSGT:
  3163. false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
  3164. true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
  3165. break;
  3166. case BPF_JLT:
  3167. false_reg->umin_value = max(false_reg->umin_value, val);
  3168. true_reg->umax_value = min(true_reg->umax_value, val - 1);
  3169. break;
  3170. case BPF_JSLT:
  3171. false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
  3172. true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
  3173. break;
  3174. case BPF_JGE:
  3175. false_reg->umax_value = min(false_reg->umax_value, val - 1);
  3176. true_reg->umin_value = max(true_reg->umin_value, val);
  3177. break;
  3178. case BPF_JSGE:
  3179. false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
  3180. true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
  3181. break;
  3182. case BPF_JLE:
  3183. false_reg->umin_value = max(false_reg->umin_value, val + 1);
  3184. true_reg->umax_value = min(true_reg->umax_value, val);
  3185. break;
  3186. case BPF_JSLE:
  3187. false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
  3188. true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
  3189. break;
  3190. default:
  3191. break;
  3192. }
  3193. __reg_deduce_bounds(false_reg);
  3194. __reg_deduce_bounds(true_reg);
  3195. /* We might have learned some bits from the bounds. */
  3196. __reg_bound_offset(false_reg);
  3197. __reg_bound_offset(true_reg);
  3198. /* Intersecting with the old var_off might have improved our bounds
  3199. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  3200. * then new var_off is (0; 0x7f...fc) which improves our umax.
  3201. */
  3202. __update_reg_bounds(false_reg);
  3203. __update_reg_bounds(true_reg);
  3204. }
  3205. /* Same as above, but for the case that dst_reg holds a constant and src_reg is
  3206. * the variable reg.
  3207. */
  3208. static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
  3209. struct bpf_reg_state *false_reg, u64 val,
  3210. u8 opcode)
  3211. {
  3212. if (__is_pointer_value(false, false_reg))
  3213. return;
  3214. switch (opcode) {
  3215. case BPF_JEQ:
  3216. /* If this is false then we know nothing Jon Snow, but if it is
  3217. * true then we know for sure.
  3218. */
  3219. __mark_reg_known(true_reg, val);
  3220. break;
  3221. case BPF_JNE:
  3222. /* If this is true we know nothing Jon Snow, but if it is false
  3223. * we know the value for sure;
  3224. */
  3225. __mark_reg_known(false_reg, val);
  3226. break;
  3227. case BPF_JGT:
  3228. true_reg->umax_value = min(true_reg->umax_value, val - 1);
  3229. false_reg->umin_value = max(false_reg->umin_value, val);
  3230. break;
  3231. case BPF_JSGT:
  3232. true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
  3233. false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
  3234. break;
  3235. case BPF_JLT:
  3236. true_reg->umin_value = max(true_reg->umin_value, val + 1);
  3237. false_reg->umax_value = min(false_reg->umax_value, val);
  3238. break;
  3239. case BPF_JSLT:
  3240. true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
  3241. false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
  3242. break;
  3243. case BPF_JGE:
  3244. true_reg->umax_value = min(true_reg->umax_value, val);
  3245. false_reg->umin_value = max(false_reg->umin_value, val + 1);
  3246. break;
  3247. case BPF_JSGE:
  3248. true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
  3249. false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
  3250. break;
  3251. case BPF_JLE:
  3252. true_reg->umin_value = max(true_reg->umin_value, val);
  3253. false_reg->umax_value = min(false_reg->umax_value, val - 1);
  3254. break;
  3255. case BPF_JSLE:
  3256. true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
  3257. false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
  3258. break;
  3259. default:
  3260. break;
  3261. }
  3262. __reg_deduce_bounds(false_reg);
  3263. __reg_deduce_bounds(true_reg);
  3264. /* We might have learned some bits from the bounds. */
  3265. __reg_bound_offset(false_reg);
  3266. __reg_bound_offset(true_reg);
  3267. /* Intersecting with the old var_off might have improved our bounds
  3268. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  3269. * then new var_off is (0; 0x7f...fc) which improves our umax.
  3270. */
  3271. __update_reg_bounds(false_reg);
  3272. __update_reg_bounds(true_reg);
  3273. }
  3274. /* Regs are known to be equal, so intersect their min/max/var_off */
  3275. static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
  3276. struct bpf_reg_state *dst_reg)
  3277. {
  3278. src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
  3279. dst_reg->umin_value);
  3280. src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
  3281. dst_reg->umax_value);
  3282. src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
  3283. dst_reg->smin_value);
  3284. src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
  3285. dst_reg->smax_value);
  3286. src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
  3287. dst_reg->var_off);
  3288. /* We might have learned new bounds from the var_off. */
  3289. __update_reg_bounds(src_reg);
  3290. __update_reg_bounds(dst_reg);
  3291. /* We might have learned something about the sign bit. */
  3292. __reg_deduce_bounds(src_reg);
  3293. __reg_deduce_bounds(dst_reg);
  3294. /* We might have learned some bits from the bounds. */
  3295. __reg_bound_offset(src_reg);
  3296. __reg_bound_offset(dst_reg);
  3297. /* Intersecting with the old var_off might have improved our bounds
  3298. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  3299. * then new var_off is (0; 0x7f...fc) which improves our umax.
  3300. */
  3301. __update_reg_bounds(src_reg);
  3302. __update_reg_bounds(dst_reg);
  3303. }
  3304. static void reg_combine_min_max(struct bpf_reg_state *true_src,
  3305. struct bpf_reg_state *true_dst,
  3306. struct bpf_reg_state *false_src,
  3307. struct bpf_reg_state *false_dst,
  3308. u8 opcode)
  3309. {
  3310. switch (opcode) {
  3311. case BPF_JEQ:
  3312. __reg_combine_min_max(true_src, true_dst);
  3313. break;
  3314. case BPF_JNE:
  3315. __reg_combine_min_max(false_src, false_dst);
  3316. break;
  3317. }
  3318. }
  3319. static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
  3320. bool is_null)
  3321. {
  3322. struct bpf_reg_state *reg = &regs[regno];
  3323. if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
  3324. /* Old offset (both fixed and variable parts) should
  3325. * have been known-zero, because we don't allow pointer
  3326. * arithmetic on pointers that might be NULL.
  3327. */
  3328. if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
  3329. !tnum_equals_const(reg->var_off, 0) ||
  3330. reg->off)) {
  3331. __mark_reg_known_zero(reg);
  3332. reg->off = 0;
  3333. }
  3334. if (is_null) {
  3335. reg->type = SCALAR_VALUE;
  3336. } else if (reg->map_ptr->inner_map_meta) {
  3337. reg->type = CONST_PTR_TO_MAP;
  3338. reg->map_ptr = reg->map_ptr->inner_map_meta;
  3339. } else {
  3340. reg->type = PTR_TO_MAP_VALUE;
  3341. }
  3342. /* We don't need id from this point onwards anymore, thus we
  3343. * should better reset it, so that state pruning has chances
  3344. * to take effect.
  3345. */
  3346. reg->id = 0;
  3347. }
  3348. }
  3349. /* The logic is similar to find_good_pkt_pointers(), both could eventually
  3350. * be folded together at some point.
  3351. */
  3352. static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
  3353. bool is_null)
  3354. {
  3355. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  3356. struct bpf_reg_state *regs = state->regs;
  3357. u32 id = regs[regno].id;
  3358. int i, j;
  3359. for (i = 0; i < MAX_BPF_REG; i++)
  3360. mark_map_reg(regs, i, id, is_null);
  3361. for (j = 0; j <= vstate->curframe; j++) {
  3362. state = vstate->frame[j];
  3363. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  3364. if (state->stack[i].slot_type[0] != STACK_SPILL)
  3365. continue;
  3366. mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
  3367. }
  3368. }
  3369. }
  3370. static bool try_match_pkt_pointers(const struct bpf_insn *insn,
  3371. struct bpf_reg_state *dst_reg,
  3372. struct bpf_reg_state *src_reg,
  3373. struct bpf_verifier_state *this_branch,
  3374. struct bpf_verifier_state *other_branch)
  3375. {
  3376. if (BPF_SRC(insn->code) != BPF_X)
  3377. return false;
  3378. switch (BPF_OP(insn->code)) {
  3379. case BPF_JGT:
  3380. if ((dst_reg->type == PTR_TO_PACKET &&
  3381. src_reg->type == PTR_TO_PACKET_END) ||
  3382. (dst_reg->type == PTR_TO_PACKET_META &&
  3383. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  3384. /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
  3385. find_good_pkt_pointers(this_branch, dst_reg,
  3386. dst_reg->type, false);
  3387. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  3388. src_reg->type == PTR_TO_PACKET) ||
  3389. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  3390. src_reg->type == PTR_TO_PACKET_META)) {
  3391. /* pkt_end > pkt_data', pkt_data > pkt_meta' */
  3392. find_good_pkt_pointers(other_branch, src_reg,
  3393. src_reg->type, true);
  3394. } else {
  3395. return false;
  3396. }
  3397. break;
  3398. case BPF_JLT:
  3399. if ((dst_reg->type == PTR_TO_PACKET &&
  3400. src_reg->type == PTR_TO_PACKET_END) ||
  3401. (dst_reg->type == PTR_TO_PACKET_META &&
  3402. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  3403. /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
  3404. find_good_pkt_pointers(other_branch, dst_reg,
  3405. dst_reg->type, true);
  3406. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  3407. src_reg->type == PTR_TO_PACKET) ||
  3408. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  3409. src_reg->type == PTR_TO_PACKET_META)) {
  3410. /* pkt_end < pkt_data', pkt_data > pkt_meta' */
  3411. find_good_pkt_pointers(this_branch, src_reg,
  3412. src_reg->type, false);
  3413. } else {
  3414. return false;
  3415. }
  3416. break;
  3417. case BPF_JGE:
  3418. if ((dst_reg->type == PTR_TO_PACKET &&
  3419. src_reg->type == PTR_TO_PACKET_END) ||
  3420. (dst_reg->type == PTR_TO_PACKET_META &&
  3421. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  3422. /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
  3423. find_good_pkt_pointers(this_branch, dst_reg,
  3424. dst_reg->type, true);
  3425. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  3426. src_reg->type == PTR_TO_PACKET) ||
  3427. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  3428. src_reg->type == PTR_TO_PACKET_META)) {
  3429. /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
  3430. find_good_pkt_pointers(other_branch, src_reg,
  3431. src_reg->type, false);
  3432. } else {
  3433. return false;
  3434. }
  3435. break;
  3436. case BPF_JLE:
  3437. if ((dst_reg->type == PTR_TO_PACKET &&
  3438. src_reg->type == PTR_TO_PACKET_END) ||
  3439. (dst_reg->type == PTR_TO_PACKET_META &&
  3440. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  3441. /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
  3442. find_good_pkt_pointers(other_branch, dst_reg,
  3443. dst_reg->type, false);
  3444. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  3445. src_reg->type == PTR_TO_PACKET) ||
  3446. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  3447. src_reg->type == PTR_TO_PACKET_META)) {
  3448. /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
  3449. find_good_pkt_pointers(this_branch, src_reg,
  3450. src_reg->type, true);
  3451. } else {
  3452. return false;
  3453. }
  3454. break;
  3455. default:
  3456. return false;
  3457. }
  3458. return true;
  3459. }
  3460. static int check_cond_jmp_op(struct bpf_verifier_env *env,
  3461. struct bpf_insn *insn, int *insn_idx)
  3462. {
  3463. struct bpf_verifier_state *this_branch = env->cur_state;
  3464. struct bpf_verifier_state *other_branch;
  3465. struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
  3466. struct bpf_reg_state *dst_reg, *other_branch_regs;
  3467. u8 opcode = BPF_OP(insn->code);
  3468. int err;
  3469. if (opcode > BPF_JSLE) {
  3470. verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
  3471. return -EINVAL;
  3472. }
  3473. if (BPF_SRC(insn->code) == BPF_X) {
  3474. if (insn->imm != 0) {
  3475. verbose(env, "BPF_JMP uses reserved fields\n");
  3476. return -EINVAL;
  3477. }
  3478. /* check src1 operand */
  3479. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  3480. if (err)
  3481. return err;
  3482. if (is_pointer_value(env, insn->src_reg)) {
  3483. verbose(env, "R%d pointer comparison prohibited\n",
  3484. insn->src_reg);
  3485. return -EACCES;
  3486. }
  3487. } else {
  3488. if (insn->src_reg != BPF_REG_0) {
  3489. verbose(env, "BPF_JMP uses reserved fields\n");
  3490. return -EINVAL;
  3491. }
  3492. }
  3493. /* check src2 operand */
  3494. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  3495. if (err)
  3496. return err;
  3497. dst_reg = &regs[insn->dst_reg];
  3498. /* detect if R == 0 where R was initialized to zero earlier */
  3499. if (BPF_SRC(insn->code) == BPF_K &&
  3500. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  3501. dst_reg->type == SCALAR_VALUE &&
  3502. tnum_is_const(dst_reg->var_off)) {
  3503. if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
  3504. (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
  3505. /* if (imm == imm) goto pc+off;
  3506. * only follow the goto, ignore fall-through
  3507. */
  3508. *insn_idx += insn->off;
  3509. return 0;
  3510. } else {
  3511. /* if (imm != imm) goto pc+off;
  3512. * only follow fall-through branch, since
  3513. * that's where the program will go
  3514. */
  3515. return 0;
  3516. }
  3517. }
  3518. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  3519. if (!other_branch)
  3520. return -EFAULT;
  3521. other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
  3522. /* detect if we are comparing against a constant value so we can adjust
  3523. * our min/max values for our dst register.
  3524. * this is only legit if both are scalars (or pointers to the same
  3525. * object, I suppose, but we don't support that right now), because
  3526. * otherwise the different base pointers mean the offsets aren't
  3527. * comparable.
  3528. */
  3529. if (BPF_SRC(insn->code) == BPF_X) {
  3530. if (dst_reg->type == SCALAR_VALUE &&
  3531. regs[insn->src_reg].type == SCALAR_VALUE) {
  3532. if (tnum_is_const(regs[insn->src_reg].var_off))
  3533. reg_set_min_max(&other_branch_regs[insn->dst_reg],
  3534. dst_reg, regs[insn->src_reg].var_off.value,
  3535. opcode);
  3536. else if (tnum_is_const(dst_reg->var_off))
  3537. reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
  3538. &regs[insn->src_reg],
  3539. dst_reg->var_off.value, opcode);
  3540. else if (opcode == BPF_JEQ || opcode == BPF_JNE)
  3541. /* Comparing for equality, we can combine knowledge */
  3542. reg_combine_min_max(&other_branch_regs[insn->src_reg],
  3543. &other_branch_regs[insn->dst_reg],
  3544. &regs[insn->src_reg],
  3545. &regs[insn->dst_reg], opcode);
  3546. }
  3547. } else if (dst_reg->type == SCALAR_VALUE) {
  3548. reg_set_min_max(&other_branch_regs[insn->dst_reg],
  3549. dst_reg, insn->imm, opcode);
  3550. }
  3551. /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
  3552. if (BPF_SRC(insn->code) == BPF_K &&
  3553. insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  3554. dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  3555. /* Mark all identical map registers in each branch as either
  3556. * safe or unknown depending R == 0 or R != 0 conditional.
  3557. */
  3558. mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
  3559. mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
  3560. } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
  3561. this_branch, other_branch) &&
  3562. is_pointer_value(env, insn->dst_reg)) {
  3563. verbose(env, "R%d pointer comparison prohibited\n",
  3564. insn->dst_reg);
  3565. return -EACCES;
  3566. }
  3567. if (env->log.level)
  3568. print_verifier_state(env, this_branch->frame[this_branch->curframe]);
  3569. return 0;
  3570. }
  3571. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  3572. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  3573. {
  3574. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  3575. return (struct bpf_map *) (unsigned long) imm64;
  3576. }
  3577. /* verify BPF_LD_IMM64 instruction */
  3578. static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
  3579. {
  3580. struct bpf_reg_state *regs = cur_regs(env);
  3581. int err;
  3582. if (BPF_SIZE(insn->code) != BPF_DW) {
  3583. verbose(env, "invalid BPF_LD_IMM insn\n");
  3584. return -EINVAL;
  3585. }
  3586. if (insn->off != 0) {
  3587. verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
  3588. return -EINVAL;
  3589. }
  3590. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  3591. if (err)
  3592. return err;
  3593. if (insn->src_reg == 0) {
  3594. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  3595. regs[insn->dst_reg].type = SCALAR_VALUE;
  3596. __mark_reg_known(&regs[insn->dst_reg], imm);
  3597. return 0;
  3598. }
  3599. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  3600. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  3601. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  3602. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  3603. return 0;
  3604. }
  3605. static bool may_access_skb(enum bpf_prog_type type)
  3606. {
  3607. switch (type) {
  3608. case BPF_PROG_TYPE_SOCKET_FILTER:
  3609. case BPF_PROG_TYPE_SCHED_CLS:
  3610. case BPF_PROG_TYPE_SCHED_ACT:
  3611. return true;
  3612. default:
  3613. return false;
  3614. }
  3615. }
  3616. /* verify safety of LD_ABS|LD_IND instructions:
  3617. * - they can only appear in the programs where ctx == skb
  3618. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  3619. * preserve R6-R9, and store return value into R0
  3620. *
  3621. * Implicit input:
  3622. * ctx == skb == R6 == CTX
  3623. *
  3624. * Explicit input:
  3625. * SRC == any register
  3626. * IMM == 32-bit immediate
  3627. *
  3628. * Output:
  3629. * R0 - 8/16/32-bit skb data converted to cpu endianness
  3630. */
  3631. static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
  3632. {
  3633. struct bpf_reg_state *regs = cur_regs(env);
  3634. u8 mode = BPF_MODE(insn->code);
  3635. int i, err;
  3636. if (!may_access_skb(env->prog->type)) {
  3637. verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
  3638. return -EINVAL;
  3639. }
  3640. if (!env->ops->gen_ld_abs) {
  3641. verbose(env, "bpf verifier is misconfigured\n");
  3642. return -EINVAL;
  3643. }
  3644. if (env->subprog_cnt > 1) {
  3645. /* when program has LD_ABS insn JITs and interpreter assume
  3646. * that r1 == ctx == skb which is not the case for callees
  3647. * that can have arbitrary arguments. It's problematic
  3648. * for main prog as well since JITs would need to analyze
  3649. * all functions in order to make proper register save/restore
  3650. * decisions in the main prog. Hence disallow LD_ABS with calls
  3651. */
  3652. verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
  3653. return -EINVAL;
  3654. }
  3655. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  3656. BPF_SIZE(insn->code) == BPF_DW ||
  3657. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  3658. verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
  3659. return -EINVAL;
  3660. }
  3661. /* check whether implicit source operand (register R6) is readable */
  3662. err = check_reg_arg(env, BPF_REG_6, SRC_OP);
  3663. if (err)
  3664. return err;
  3665. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  3666. verbose(env,
  3667. "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  3668. return -EINVAL;
  3669. }
  3670. if (mode == BPF_IND) {
  3671. /* check explicit source operand */
  3672. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  3673. if (err)
  3674. return err;
  3675. }
  3676. /* reset caller saved regs to unreadable */
  3677. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  3678. mark_reg_not_init(env, regs, caller_saved[i]);
  3679. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  3680. }
  3681. /* mark destination R0 register as readable, since it contains
  3682. * the value fetched from the packet.
  3683. * Already marked as written above.
  3684. */
  3685. mark_reg_unknown(env, regs, BPF_REG_0);
  3686. return 0;
  3687. }
  3688. static int check_return_code(struct bpf_verifier_env *env)
  3689. {
  3690. struct bpf_reg_state *reg;
  3691. struct tnum range = tnum_range(0, 1);
  3692. switch (env->prog->type) {
  3693. case BPF_PROG_TYPE_CGROUP_SKB:
  3694. case BPF_PROG_TYPE_CGROUP_SOCK:
  3695. case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
  3696. case BPF_PROG_TYPE_SOCK_OPS:
  3697. case BPF_PROG_TYPE_CGROUP_DEVICE:
  3698. break;
  3699. default:
  3700. return 0;
  3701. }
  3702. reg = cur_regs(env) + BPF_REG_0;
  3703. if (reg->type != SCALAR_VALUE) {
  3704. verbose(env, "At program exit the register R0 is not a known value (%s)\n",
  3705. reg_type_str[reg->type]);
  3706. return -EINVAL;
  3707. }
  3708. if (!tnum_in(range, reg->var_off)) {
  3709. verbose(env, "At program exit the register R0 ");
  3710. if (!tnum_is_unknown(reg->var_off)) {
  3711. char tn_buf[48];
  3712. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  3713. verbose(env, "has value %s", tn_buf);
  3714. } else {
  3715. verbose(env, "has unknown scalar value");
  3716. }
  3717. verbose(env, " should have been 0 or 1\n");
  3718. return -EINVAL;
  3719. }
  3720. return 0;
  3721. }
  3722. /* non-recursive DFS pseudo code
  3723. * 1 procedure DFS-iterative(G,v):
  3724. * 2 label v as discovered
  3725. * 3 let S be a stack
  3726. * 4 S.push(v)
  3727. * 5 while S is not empty
  3728. * 6 t <- S.pop()
  3729. * 7 if t is what we're looking for:
  3730. * 8 return t
  3731. * 9 for all edges e in G.adjacentEdges(t) do
  3732. * 10 if edge e is already labelled
  3733. * 11 continue with the next edge
  3734. * 12 w <- G.adjacentVertex(t,e)
  3735. * 13 if vertex w is not discovered and not explored
  3736. * 14 label e as tree-edge
  3737. * 15 label w as discovered
  3738. * 16 S.push(w)
  3739. * 17 continue at 5
  3740. * 18 else if vertex w is discovered
  3741. * 19 label e as back-edge
  3742. * 20 else
  3743. * 21 // vertex w is explored
  3744. * 22 label e as forward- or cross-edge
  3745. * 23 label t as explored
  3746. * 24 S.pop()
  3747. *
  3748. * convention:
  3749. * 0x10 - discovered
  3750. * 0x11 - discovered and fall-through edge labelled
  3751. * 0x12 - discovered and fall-through and branch edges labelled
  3752. * 0x20 - explored
  3753. */
  3754. enum {
  3755. DISCOVERED = 0x10,
  3756. EXPLORED = 0x20,
  3757. FALLTHROUGH = 1,
  3758. BRANCH = 2,
  3759. };
  3760. #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
  3761. static int *insn_stack; /* stack of insns to process */
  3762. static int cur_stack; /* current stack index */
  3763. static int *insn_state;
  3764. /* t, w, e - match pseudo-code above:
  3765. * t - index of current instruction
  3766. * w - next instruction
  3767. * e - edge
  3768. */
  3769. static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
  3770. {
  3771. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  3772. return 0;
  3773. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  3774. return 0;
  3775. if (w < 0 || w >= env->prog->len) {
  3776. verbose(env, "jump out of range from insn %d to %d\n", t, w);
  3777. return -EINVAL;
  3778. }
  3779. if (e == BRANCH)
  3780. /* mark branch target for state pruning */
  3781. env->explored_states[w] = STATE_LIST_MARK;
  3782. if (insn_state[w] == 0) {
  3783. /* tree-edge */
  3784. insn_state[t] = DISCOVERED | e;
  3785. insn_state[w] = DISCOVERED;
  3786. if (cur_stack >= env->prog->len)
  3787. return -E2BIG;
  3788. insn_stack[cur_stack++] = w;
  3789. return 1;
  3790. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  3791. verbose(env, "back-edge from insn %d to %d\n", t, w);
  3792. return -EINVAL;
  3793. } else if (insn_state[w] == EXPLORED) {
  3794. /* forward- or cross-edge */
  3795. insn_state[t] = DISCOVERED | e;
  3796. } else {
  3797. verbose(env, "insn state internal bug\n");
  3798. return -EFAULT;
  3799. }
  3800. return 0;
  3801. }
  3802. /* non-recursive depth-first-search to detect loops in BPF program
  3803. * loop == back-edge in directed graph
  3804. */
  3805. static int check_cfg(struct bpf_verifier_env *env)
  3806. {
  3807. struct bpf_insn *insns = env->prog->insnsi;
  3808. int insn_cnt = env->prog->len;
  3809. int ret = 0;
  3810. int i, t;
  3811. ret = check_subprogs(env);
  3812. if (ret < 0)
  3813. return ret;
  3814. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  3815. if (!insn_state)
  3816. return -ENOMEM;
  3817. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  3818. if (!insn_stack) {
  3819. kfree(insn_state);
  3820. return -ENOMEM;
  3821. }
  3822. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  3823. insn_stack[0] = 0; /* 0 is the first instruction */
  3824. cur_stack = 1;
  3825. peek_stack:
  3826. if (cur_stack == 0)
  3827. goto check_state;
  3828. t = insn_stack[cur_stack - 1];
  3829. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  3830. u8 opcode = BPF_OP(insns[t].code);
  3831. if (opcode == BPF_EXIT) {
  3832. goto mark_explored;
  3833. } else if (opcode == BPF_CALL) {
  3834. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  3835. if (ret == 1)
  3836. goto peek_stack;
  3837. else if (ret < 0)
  3838. goto err_free;
  3839. if (t + 1 < insn_cnt)
  3840. env->explored_states[t + 1] = STATE_LIST_MARK;
  3841. if (insns[t].src_reg == BPF_PSEUDO_CALL) {
  3842. env->explored_states[t] = STATE_LIST_MARK;
  3843. ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
  3844. if (ret == 1)
  3845. goto peek_stack;
  3846. else if (ret < 0)
  3847. goto err_free;
  3848. }
  3849. } else if (opcode == BPF_JA) {
  3850. if (BPF_SRC(insns[t].code) != BPF_K) {
  3851. ret = -EINVAL;
  3852. goto err_free;
  3853. }
  3854. /* unconditional jump with single edge */
  3855. ret = push_insn(t, t + insns[t].off + 1,
  3856. FALLTHROUGH, env);
  3857. if (ret == 1)
  3858. goto peek_stack;
  3859. else if (ret < 0)
  3860. goto err_free;
  3861. /* tell verifier to check for equivalent states
  3862. * after every call and jump
  3863. */
  3864. if (t + 1 < insn_cnt)
  3865. env->explored_states[t + 1] = STATE_LIST_MARK;
  3866. } else {
  3867. /* conditional jump with two edges */
  3868. env->explored_states[t] = STATE_LIST_MARK;
  3869. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  3870. if (ret == 1)
  3871. goto peek_stack;
  3872. else if (ret < 0)
  3873. goto err_free;
  3874. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  3875. if (ret == 1)
  3876. goto peek_stack;
  3877. else if (ret < 0)
  3878. goto err_free;
  3879. }
  3880. } else {
  3881. /* all other non-branch instructions with single
  3882. * fall-through edge
  3883. */
  3884. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  3885. if (ret == 1)
  3886. goto peek_stack;
  3887. else if (ret < 0)
  3888. goto err_free;
  3889. }
  3890. mark_explored:
  3891. insn_state[t] = EXPLORED;
  3892. if (cur_stack-- <= 0) {
  3893. verbose(env, "pop stack internal bug\n");
  3894. ret = -EFAULT;
  3895. goto err_free;
  3896. }
  3897. goto peek_stack;
  3898. check_state:
  3899. for (i = 0; i < insn_cnt; i++) {
  3900. if (insn_state[i] != EXPLORED) {
  3901. verbose(env, "unreachable insn %d\n", i);
  3902. ret = -EINVAL;
  3903. goto err_free;
  3904. }
  3905. }
  3906. ret = 0; /* cfg looks good */
  3907. err_free:
  3908. kfree(insn_state);
  3909. kfree(insn_stack);
  3910. return ret;
  3911. }
  3912. /* check %cur's range satisfies %old's */
  3913. static bool range_within(struct bpf_reg_state *old,
  3914. struct bpf_reg_state *cur)
  3915. {
  3916. return old->umin_value <= cur->umin_value &&
  3917. old->umax_value >= cur->umax_value &&
  3918. old->smin_value <= cur->smin_value &&
  3919. old->smax_value >= cur->smax_value;
  3920. }
  3921. /* Maximum number of register states that can exist at once */
  3922. #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
  3923. struct idpair {
  3924. u32 old;
  3925. u32 cur;
  3926. };
  3927. /* If in the old state two registers had the same id, then they need to have
  3928. * the same id in the new state as well. But that id could be different from
  3929. * the old state, so we need to track the mapping from old to new ids.
  3930. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
  3931. * regs with old id 5 must also have new id 9 for the new state to be safe. But
  3932. * regs with a different old id could still have new id 9, we don't care about
  3933. * that.
  3934. * So we look through our idmap to see if this old id has been seen before. If
  3935. * so, we require the new id to match; otherwise, we add the id pair to the map.
  3936. */
  3937. static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
  3938. {
  3939. unsigned int i;
  3940. for (i = 0; i < ID_MAP_SIZE; i++) {
  3941. if (!idmap[i].old) {
  3942. /* Reached an empty slot; haven't seen this id before */
  3943. idmap[i].old = old_id;
  3944. idmap[i].cur = cur_id;
  3945. return true;
  3946. }
  3947. if (idmap[i].old == old_id)
  3948. return idmap[i].cur == cur_id;
  3949. }
  3950. /* We ran out of idmap slots, which should be impossible */
  3951. WARN_ON_ONCE(1);
  3952. return false;
  3953. }
  3954. /* Returns true if (rold safe implies rcur safe) */
  3955. static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
  3956. struct idpair *idmap)
  3957. {
  3958. bool equal;
  3959. if (!(rold->live & REG_LIVE_READ))
  3960. /* explored state didn't use this */
  3961. return true;
  3962. equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
  3963. if (rold->type == PTR_TO_STACK)
  3964. /* two stack pointers are equal only if they're pointing to
  3965. * the same stack frame, since fp-8 in foo != fp-8 in bar
  3966. */
  3967. return equal && rold->frameno == rcur->frameno;
  3968. if (equal)
  3969. return true;
  3970. if (rold->type == NOT_INIT)
  3971. /* explored state can't have used this */
  3972. return true;
  3973. if (rcur->type == NOT_INIT)
  3974. return false;
  3975. switch (rold->type) {
  3976. case SCALAR_VALUE:
  3977. if (rcur->type == SCALAR_VALUE) {
  3978. /* new val must satisfy old val knowledge */
  3979. return range_within(rold, rcur) &&
  3980. tnum_in(rold->var_off, rcur->var_off);
  3981. } else {
  3982. /* We're trying to use a pointer in place of a scalar.
  3983. * Even if the scalar was unbounded, this could lead to
  3984. * pointer leaks because scalars are allowed to leak
  3985. * while pointers are not. We could make this safe in
  3986. * special cases if root is calling us, but it's
  3987. * probably not worth the hassle.
  3988. */
  3989. return false;
  3990. }
  3991. case PTR_TO_MAP_VALUE:
  3992. /* If the new min/max/var_off satisfy the old ones and
  3993. * everything else matches, we are OK.
  3994. * We don't care about the 'id' value, because nothing
  3995. * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
  3996. */
  3997. return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
  3998. range_within(rold, rcur) &&
  3999. tnum_in(rold->var_off, rcur->var_off);
  4000. case PTR_TO_MAP_VALUE_OR_NULL:
  4001. /* a PTR_TO_MAP_VALUE could be safe to use as a
  4002. * PTR_TO_MAP_VALUE_OR_NULL into the same map.
  4003. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
  4004. * checked, doing so could have affected others with the same
  4005. * id, and we can't check for that because we lost the id when
  4006. * we converted to a PTR_TO_MAP_VALUE.
  4007. */
  4008. if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
  4009. return false;
  4010. if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
  4011. return false;
  4012. /* Check our ids match any regs they're supposed to */
  4013. return check_ids(rold->id, rcur->id, idmap);
  4014. case PTR_TO_PACKET_META:
  4015. case PTR_TO_PACKET:
  4016. if (rcur->type != rold->type)
  4017. return false;
  4018. /* We must have at least as much range as the old ptr
  4019. * did, so that any accesses which were safe before are
  4020. * still safe. This is true even if old range < old off,
  4021. * since someone could have accessed through (ptr - k), or
  4022. * even done ptr -= k in a register, to get a safe access.
  4023. */
  4024. if (rold->range > rcur->range)
  4025. return false;
  4026. /* If the offsets don't match, we can't trust our alignment;
  4027. * nor can we be sure that we won't fall out of range.
  4028. */
  4029. if (rold->off != rcur->off)
  4030. return false;
  4031. /* id relations must be preserved */
  4032. if (rold->id && !check_ids(rold->id, rcur->id, idmap))
  4033. return false;
  4034. /* new val must satisfy old val knowledge */
  4035. return range_within(rold, rcur) &&
  4036. tnum_in(rold->var_off, rcur->var_off);
  4037. case PTR_TO_CTX:
  4038. case CONST_PTR_TO_MAP:
  4039. case PTR_TO_PACKET_END:
  4040. /* Only valid matches are exact, which memcmp() above
  4041. * would have accepted
  4042. */
  4043. default:
  4044. /* Don't know what's going on, just say it's not safe */
  4045. return false;
  4046. }
  4047. /* Shouldn't get here; if we do, say it's not safe */
  4048. WARN_ON_ONCE(1);
  4049. return false;
  4050. }
  4051. static bool stacksafe(struct bpf_func_state *old,
  4052. struct bpf_func_state *cur,
  4053. struct idpair *idmap)
  4054. {
  4055. int i, spi;
  4056. /* if explored stack has more populated slots than current stack
  4057. * such stacks are not equivalent
  4058. */
  4059. if (old->allocated_stack > cur->allocated_stack)
  4060. return false;
  4061. /* walk slots of the explored stack and ignore any additional
  4062. * slots in the current stack, since explored(safe) state
  4063. * didn't use them
  4064. */
  4065. for (i = 0; i < old->allocated_stack; i++) {
  4066. spi = i / BPF_REG_SIZE;
  4067. if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
  4068. /* explored state didn't use this */
  4069. continue;
  4070. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
  4071. continue;
  4072. /* if old state was safe with misc data in the stack
  4073. * it will be safe with zero-initialized stack.
  4074. * The opposite is not true
  4075. */
  4076. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
  4077. cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
  4078. continue;
  4079. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
  4080. cur->stack[spi].slot_type[i % BPF_REG_SIZE])
  4081. /* Ex: old explored (safe) state has STACK_SPILL in
  4082. * this stack slot, but current has has STACK_MISC ->
  4083. * this verifier states are not equivalent,
  4084. * return false to continue verification of this path
  4085. */
  4086. return false;
  4087. if (i % BPF_REG_SIZE)
  4088. continue;
  4089. if (old->stack[spi].slot_type[0] != STACK_SPILL)
  4090. continue;
  4091. if (!regsafe(&old->stack[spi].spilled_ptr,
  4092. &cur->stack[spi].spilled_ptr,
  4093. idmap))
  4094. /* when explored and current stack slot are both storing
  4095. * spilled registers, check that stored pointers types
  4096. * are the same as well.
  4097. * Ex: explored safe path could have stored
  4098. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
  4099. * but current path has stored:
  4100. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
  4101. * such verifier states are not equivalent.
  4102. * return false to continue verification of this path
  4103. */
  4104. return false;
  4105. }
  4106. return true;
  4107. }
  4108. /* compare two verifier states
  4109. *
  4110. * all states stored in state_list are known to be valid, since
  4111. * verifier reached 'bpf_exit' instruction through them
  4112. *
  4113. * this function is called when verifier exploring different branches of
  4114. * execution popped from the state stack. If it sees an old state that has
  4115. * more strict register state and more strict stack state then this execution
  4116. * branch doesn't need to be explored further, since verifier already
  4117. * concluded that more strict state leads to valid finish.
  4118. *
  4119. * Therefore two states are equivalent if register state is more conservative
  4120. * and explored stack state is more conservative than the current one.
  4121. * Example:
  4122. * explored current
  4123. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  4124. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  4125. *
  4126. * In other words if current stack state (one being explored) has more
  4127. * valid slots than old one that already passed validation, it means
  4128. * the verifier can stop exploring and conclude that current state is valid too
  4129. *
  4130. * Similarly with registers. If explored state has register type as invalid
  4131. * whereas register type in current state is meaningful, it means that
  4132. * the current state will reach 'bpf_exit' instruction safely
  4133. */
  4134. static bool func_states_equal(struct bpf_func_state *old,
  4135. struct bpf_func_state *cur)
  4136. {
  4137. struct idpair *idmap;
  4138. bool ret = false;
  4139. int i;
  4140. idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
  4141. /* If we failed to allocate the idmap, just say it's not safe */
  4142. if (!idmap)
  4143. return false;
  4144. for (i = 0; i < MAX_BPF_REG; i++) {
  4145. if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
  4146. goto out_free;
  4147. }
  4148. if (!stacksafe(old, cur, idmap))
  4149. goto out_free;
  4150. ret = true;
  4151. out_free:
  4152. kfree(idmap);
  4153. return ret;
  4154. }
  4155. static bool states_equal(struct bpf_verifier_env *env,
  4156. struct bpf_verifier_state *old,
  4157. struct bpf_verifier_state *cur)
  4158. {
  4159. int i;
  4160. if (old->curframe != cur->curframe)
  4161. return false;
  4162. /* for states to be equal callsites have to be the same
  4163. * and all frame states need to be equivalent
  4164. */
  4165. for (i = 0; i <= old->curframe; i++) {
  4166. if (old->frame[i]->callsite != cur->frame[i]->callsite)
  4167. return false;
  4168. if (!func_states_equal(old->frame[i], cur->frame[i]))
  4169. return false;
  4170. }
  4171. return true;
  4172. }
  4173. /* A write screens off any subsequent reads; but write marks come from the
  4174. * straight-line code between a state and its parent. When we arrive at an
  4175. * equivalent state (jump target or such) we didn't arrive by the straight-line
  4176. * code, so read marks in the state must propagate to the parent regardless
  4177. * of the state's write marks. That's what 'parent == state->parent' comparison
  4178. * in mark_reg_read() and mark_stack_slot_read() is for.
  4179. */
  4180. static int propagate_liveness(struct bpf_verifier_env *env,
  4181. const struct bpf_verifier_state *vstate,
  4182. struct bpf_verifier_state *vparent)
  4183. {
  4184. int i, frame, err = 0;
  4185. struct bpf_func_state *state, *parent;
  4186. if (vparent->curframe != vstate->curframe) {
  4187. WARN(1, "propagate_live: parent frame %d current frame %d\n",
  4188. vparent->curframe, vstate->curframe);
  4189. return -EFAULT;
  4190. }
  4191. /* Propagate read liveness of registers... */
  4192. BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
  4193. /* We don't need to worry about FP liveness because it's read-only */
  4194. for (i = 0; i < BPF_REG_FP; i++) {
  4195. if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
  4196. continue;
  4197. if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
  4198. err = mark_reg_read(env, vstate, vparent, i);
  4199. if (err)
  4200. return err;
  4201. }
  4202. }
  4203. /* ... and stack slots */
  4204. for (frame = 0; frame <= vstate->curframe; frame++) {
  4205. state = vstate->frame[frame];
  4206. parent = vparent->frame[frame];
  4207. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
  4208. i < parent->allocated_stack / BPF_REG_SIZE; i++) {
  4209. if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
  4210. continue;
  4211. if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
  4212. mark_stack_slot_read(env, vstate, vparent, i, frame);
  4213. }
  4214. }
  4215. return err;
  4216. }
  4217. static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
  4218. {
  4219. struct bpf_verifier_state_list *new_sl;
  4220. struct bpf_verifier_state_list *sl;
  4221. struct bpf_verifier_state *cur = env->cur_state;
  4222. int i, j, err;
  4223. sl = env->explored_states[insn_idx];
  4224. if (!sl)
  4225. /* this 'insn_idx' instruction wasn't marked, so we will not
  4226. * be doing state search here
  4227. */
  4228. return 0;
  4229. while (sl != STATE_LIST_MARK) {
  4230. if (states_equal(env, &sl->state, cur)) {
  4231. /* reached equivalent register/stack state,
  4232. * prune the search.
  4233. * Registers read by the continuation are read by us.
  4234. * If we have any write marks in env->cur_state, they
  4235. * will prevent corresponding reads in the continuation
  4236. * from reaching our parent (an explored_state). Our
  4237. * own state will get the read marks recorded, but
  4238. * they'll be immediately forgotten as we're pruning
  4239. * this state and will pop a new one.
  4240. */
  4241. err = propagate_liveness(env, &sl->state, cur);
  4242. if (err)
  4243. return err;
  4244. return 1;
  4245. }
  4246. sl = sl->next;
  4247. }
  4248. /* there were no equivalent states, remember current one.
  4249. * technically the current state is not proven to be safe yet,
  4250. * but it will either reach outer most bpf_exit (which means it's safe)
  4251. * or it will be rejected. Since there are no loops, we won't be
  4252. * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
  4253. * again on the way to bpf_exit
  4254. */
  4255. new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
  4256. if (!new_sl)
  4257. return -ENOMEM;
  4258. /* add new state to the head of linked list */
  4259. err = copy_verifier_state(&new_sl->state, cur);
  4260. if (err) {
  4261. free_verifier_state(&new_sl->state, false);
  4262. kfree(new_sl);
  4263. return err;
  4264. }
  4265. new_sl->next = env->explored_states[insn_idx];
  4266. env->explored_states[insn_idx] = new_sl;
  4267. /* connect new state to parentage chain */
  4268. cur->parent = &new_sl->state;
  4269. /* clear write marks in current state: the writes we did are not writes
  4270. * our child did, so they don't screen off its reads from us.
  4271. * (There are no read marks in current state, because reads always mark
  4272. * their parent and current state never has children yet. Only
  4273. * explored_states can get read marks.)
  4274. */
  4275. for (i = 0; i < BPF_REG_FP; i++)
  4276. cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
  4277. /* all stack frames are accessible from callee, clear them all */
  4278. for (j = 0; j <= cur->curframe; j++) {
  4279. struct bpf_func_state *frame = cur->frame[j];
  4280. for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
  4281. frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
  4282. }
  4283. return 0;
  4284. }
  4285. static int do_check(struct bpf_verifier_env *env)
  4286. {
  4287. struct bpf_verifier_state *state;
  4288. struct bpf_insn *insns = env->prog->insnsi;
  4289. struct bpf_reg_state *regs;
  4290. int insn_cnt = env->prog->len, i;
  4291. int insn_idx, prev_insn_idx = 0;
  4292. int insn_processed = 0;
  4293. bool do_print_state = false;
  4294. state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
  4295. if (!state)
  4296. return -ENOMEM;
  4297. state->curframe = 0;
  4298. state->parent = NULL;
  4299. state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
  4300. if (!state->frame[0]) {
  4301. kfree(state);
  4302. return -ENOMEM;
  4303. }
  4304. env->cur_state = state;
  4305. init_func_state(env, state->frame[0],
  4306. BPF_MAIN_FUNC /* callsite */,
  4307. 0 /* frameno */,
  4308. 0 /* subprogno, zero == main subprog */);
  4309. insn_idx = 0;
  4310. for (;;) {
  4311. struct bpf_insn *insn;
  4312. u8 class;
  4313. int err;
  4314. if (insn_idx >= insn_cnt) {
  4315. verbose(env, "invalid insn idx %d insn_cnt %d\n",
  4316. insn_idx, insn_cnt);
  4317. return -EFAULT;
  4318. }
  4319. insn = &insns[insn_idx];
  4320. class = BPF_CLASS(insn->code);
  4321. if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
  4322. verbose(env,
  4323. "BPF program is too large. Processed %d insn\n",
  4324. insn_processed);
  4325. return -E2BIG;
  4326. }
  4327. err = is_state_visited(env, insn_idx);
  4328. if (err < 0)
  4329. return err;
  4330. if (err == 1) {
  4331. /* found equivalent state, can prune the search */
  4332. if (env->log.level) {
  4333. if (do_print_state)
  4334. verbose(env, "\nfrom %d to %d: safe\n",
  4335. prev_insn_idx, insn_idx);
  4336. else
  4337. verbose(env, "%d: safe\n", insn_idx);
  4338. }
  4339. goto process_bpf_exit;
  4340. }
  4341. if (need_resched())
  4342. cond_resched();
  4343. if (env->log.level > 1 || (env->log.level && do_print_state)) {
  4344. if (env->log.level > 1)
  4345. verbose(env, "%d:", insn_idx);
  4346. else
  4347. verbose(env, "\nfrom %d to %d:",
  4348. prev_insn_idx, insn_idx);
  4349. print_verifier_state(env, state->frame[state->curframe]);
  4350. do_print_state = false;
  4351. }
  4352. if (env->log.level) {
  4353. const struct bpf_insn_cbs cbs = {
  4354. .cb_print = verbose,
  4355. .private_data = env,
  4356. };
  4357. verbose(env, "%d: ", insn_idx);
  4358. print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
  4359. }
  4360. if (bpf_prog_is_dev_bound(env->prog->aux)) {
  4361. err = bpf_prog_offload_verify_insn(env, insn_idx,
  4362. prev_insn_idx);
  4363. if (err)
  4364. return err;
  4365. }
  4366. regs = cur_regs(env);
  4367. env->insn_aux_data[insn_idx].seen = true;
  4368. if (class == BPF_ALU || class == BPF_ALU64) {
  4369. err = check_alu_op(env, insn);
  4370. if (err)
  4371. return err;
  4372. } else if (class == BPF_LDX) {
  4373. enum bpf_reg_type *prev_src_type, src_reg_type;
  4374. /* check for reserved fields is already done */
  4375. /* check src operand */
  4376. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  4377. if (err)
  4378. return err;
  4379. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  4380. if (err)
  4381. return err;
  4382. src_reg_type = regs[insn->src_reg].type;
  4383. /* check that memory (src_reg + off) is readable,
  4384. * the state of dst_reg will be updated by this func
  4385. */
  4386. err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
  4387. BPF_SIZE(insn->code), BPF_READ,
  4388. insn->dst_reg, false);
  4389. if (err)
  4390. return err;
  4391. prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
  4392. if (*prev_src_type == NOT_INIT) {
  4393. /* saw a valid insn
  4394. * dst_reg = *(u32 *)(src_reg + off)
  4395. * save type to validate intersecting paths
  4396. */
  4397. *prev_src_type = src_reg_type;
  4398. } else if (src_reg_type != *prev_src_type &&
  4399. (src_reg_type == PTR_TO_CTX ||
  4400. *prev_src_type == PTR_TO_CTX)) {
  4401. /* ABuser program is trying to use the same insn
  4402. * dst_reg = *(u32*) (src_reg + off)
  4403. * with different pointer types:
  4404. * src_reg == ctx in one branch and
  4405. * src_reg == stack|map in some other branch.
  4406. * Reject it.
  4407. */
  4408. verbose(env, "same insn cannot be used with different pointers\n");
  4409. return -EINVAL;
  4410. }
  4411. } else if (class == BPF_STX) {
  4412. enum bpf_reg_type *prev_dst_type, dst_reg_type;
  4413. if (BPF_MODE(insn->code) == BPF_XADD) {
  4414. err = check_xadd(env, insn_idx, insn);
  4415. if (err)
  4416. return err;
  4417. insn_idx++;
  4418. continue;
  4419. }
  4420. /* check src1 operand */
  4421. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  4422. if (err)
  4423. return err;
  4424. /* check src2 operand */
  4425. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  4426. if (err)
  4427. return err;
  4428. dst_reg_type = regs[insn->dst_reg].type;
  4429. /* check that memory (dst_reg + off) is writeable */
  4430. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  4431. BPF_SIZE(insn->code), BPF_WRITE,
  4432. insn->src_reg, false);
  4433. if (err)
  4434. return err;
  4435. prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
  4436. if (*prev_dst_type == NOT_INIT) {
  4437. *prev_dst_type = dst_reg_type;
  4438. } else if (dst_reg_type != *prev_dst_type &&
  4439. (dst_reg_type == PTR_TO_CTX ||
  4440. *prev_dst_type == PTR_TO_CTX)) {
  4441. verbose(env, "same insn cannot be used with different pointers\n");
  4442. return -EINVAL;
  4443. }
  4444. } else if (class == BPF_ST) {
  4445. if (BPF_MODE(insn->code) != BPF_MEM ||
  4446. insn->src_reg != BPF_REG_0) {
  4447. verbose(env, "BPF_ST uses reserved fields\n");
  4448. return -EINVAL;
  4449. }
  4450. /* check src operand */
  4451. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  4452. if (err)
  4453. return err;
  4454. if (is_ctx_reg(env, insn->dst_reg)) {
  4455. verbose(env, "BPF_ST stores into R%d context is not allowed\n",
  4456. insn->dst_reg);
  4457. return -EACCES;
  4458. }
  4459. /* check that memory (dst_reg + off) is writeable */
  4460. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  4461. BPF_SIZE(insn->code), BPF_WRITE,
  4462. -1, false);
  4463. if (err)
  4464. return err;
  4465. } else if (class == BPF_JMP) {
  4466. u8 opcode = BPF_OP(insn->code);
  4467. if (opcode == BPF_CALL) {
  4468. if (BPF_SRC(insn->code) != BPF_K ||
  4469. insn->off != 0 ||
  4470. (insn->src_reg != BPF_REG_0 &&
  4471. insn->src_reg != BPF_PSEUDO_CALL) ||
  4472. insn->dst_reg != BPF_REG_0) {
  4473. verbose(env, "BPF_CALL uses reserved fields\n");
  4474. return -EINVAL;
  4475. }
  4476. if (insn->src_reg == BPF_PSEUDO_CALL)
  4477. err = check_func_call(env, insn, &insn_idx);
  4478. else
  4479. err = check_helper_call(env, insn->imm, insn_idx);
  4480. if (err)
  4481. return err;
  4482. } else if (opcode == BPF_JA) {
  4483. if (BPF_SRC(insn->code) != BPF_K ||
  4484. insn->imm != 0 ||
  4485. insn->src_reg != BPF_REG_0 ||
  4486. insn->dst_reg != BPF_REG_0) {
  4487. verbose(env, "BPF_JA uses reserved fields\n");
  4488. return -EINVAL;
  4489. }
  4490. insn_idx += insn->off + 1;
  4491. continue;
  4492. } else if (opcode == BPF_EXIT) {
  4493. if (BPF_SRC(insn->code) != BPF_K ||
  4494. insn->imm != 0 ||
  4495. insn->src_reg != BPF_REG_0 ||
  4496. insn->dst_reg != BPF_REG_0) {
  4497. verbose(env, "BPF_EXIT uses reserved fields\n");
  4498. return -EINVAL;
  4499. }
  4500. if (state->curframe) {
  4501. /* exit from nested function */
  4502. prev_insn_idx = insn_idx;
  4503. err = prepare_func_exit(env, &insn_idx);
  4504. if (err)
  4505. return err;
  4506. do_print_state = true;
  4507. continue;
  4508. }
  4509. /* eBPF calling convetion is such that R0 is used
  4510. * to return the value from eBPF program.
  4511. * Make sure that it's readable at this time
  4512. * of bpf_exit, which means that program wrote
  4513. * something into it earlier
  4514. */
  4515. err = check_reg_arg(env, BPF_REG_0, SRC_OP);
  4516. if (err)
  4517. return err;
  4518. if (is_pointer_value(env, BPF_REG_0)) {
  4519. verbose(env, "R0 leaks addr as return value\n");
  4520. return -EACCES;
  4521. }
  4522. err = check_return_code(env);
  4523. if (err)
  4524. return err;
  4525. process_bpf_exit:
  4526. err = pop_stack(env, &prev_insn_idx, &insn_idx);
  4527. if (err < 0) {
  4528. if (err != -ENOENT)
  4529. return err;
  4530. break;
  4531. } else {
  4532. do_print_state = true;
  4533. continue;
  4534. }
  4535. } else {
  4536. err = check_cond_jmp_op(env, insn, &insn_idx);
  4537. if (err)
  4538. return err;
  4539. }
  4540. } else if (class == BPF_LD) {
  4541. u8 mode = BPF_MODE(insn->code);
  4542. if (mode == BPF_ABS || mode == BPF_IND) {
  4543. err = check_ld_abs(env, insn);
  4544. if (err)
  4545. return err;
  4546. } else if (mode == BPF_IMM) {
  4547. err = check_ld_imm(env, insn);
  4548. if (err)
  4549. return err;
  4550. insn_idx++;
  4551. env->insn_aux_data[insn_idx].seen = true;
  4552. } else {
  4553. verbose(env, "invalid BPF_LD mode\n");
  4554. return -EINVAL;
  4555. }
  4556. } else {
  4557. verbose(env, "unknown insn class %d\n", class);
  4558. return -EINVAL;
  4559. }
  4560. insn_idx++;
  4561. }
  4562. verbose(env, "processed %d insns (limit %d), stack depth ",
  4563. insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
  4564. for (i = 0; i < env->subprog_cnt; i++) {
  4565. u32 depth = env->subprog_info[i].stack_depth;
  4566. verbose(env, "%d", depth);
  4567. if (i + 1 < env->subprog_cnt)
  4568. verbose(env, "+");
  4569. }
  4570. verbose(env, "\n");
  4571. env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
  4572. return 0;
  4573. }
  4574. static int check_map_prealloc(struct bpf_map *map)
  4575. {
  4576. return (map->map_type != BPF_MAP_TYPE_HASH &&
  4577. map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
  4578. map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
  4579. !(map->map_flags & BPF_F_NO_PREALLOC);
  4580. }
  4581. static int check_map_prog_compatibility(struct bpf_verifier_env *env,
  4582. struct bpf_map *map,
  4583. struct bpf_prog *prog)
  4584. {
  4585. /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
  4586. * preallocated hash maps, since doing memory allocation
  4587. * in overflow_handler can crash depending on where nmi got
  4588. * triggered.
  4589. */
  4590. if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
  4591. if (!check_map_prealloc(map)) {
  4592. verbose(env, "perf_event programs can only use preallocated hash map\n");
  4593. return -EINVAL;
  4594. }
  4595. if (map->inner_map_meta &&
  4596. !check_map_prealloc(map->inner_map_meta)) {
  4597. verbose(env, "perf_event programs can only use preallocated inner hash map\n");
  4598. return -EINVAL;
  4599. }
  4600. }
  4601. if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
  4602. !bpf_offload_prog_map_match(prog, map)) {
  4603. verbose(env, "offload device mismatch between prog and map\n");
  4604. return -EINVAL;
  4605. }
  4606. return 0;
  4607. }
  4608. /* look for pseudo eBPF instructions that access map FDs and
  4609. * replace them with actual map pointers
  4610. */
  4611. static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
  4612. {
  4613. struct bpf_insn *insn = env->prog->insnsi;
  4614. int insn_cnt = env->prog->len;
  4615. int i, j, err;
  4616. err = bpf_prog_calc_tag(env->prog);
  4617. if (err)
  4618. return err;
  4619. for (i = 0; i < insn_cnt; i++, insn++) {
  4620. if (BPF_CLASS(insn->code) == BPF_LDX &&
  4621. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  4622. verbose(env, "BPF_LDX uses reserved fields\n");
  4623. return -EINVAL;
  4624. }
  4625. if (BPF_CLASS(insn->code) == BPF_STX &&
  4626. ((BPF_MODE(insn->code) != BPF_MEM &&
  4627. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  4628. verbose(env, "BPF_STX uses reserved fields\n");
  4629. return -EINVAL;
  4630. }
  4631. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  4632. struct bpf_map *map;
  4633. struct fd f;
  4634. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  4635. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  4636. insn[1].off != 0) {
  4637. verbose(env, "invalid bpf_ld_imm64 insn\n");
  4638. return -EINVAL;
  4639. }
  4640. if (insn->src_reg == 0)
  4641. /* valid generic load 64-bit imm */
  4642. goto next_insn;
  4643. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  4644. verbose(env,
  4645. "unrecognized bpf_ld_imm64 insn\n");
  4646. return -EINVAL;
  4647. }
  4648. f = fdget(insn->imm);
  4649. map = __bpf_map_get(f);
  4650. if (IS_ERR(map)) {
  4651. verbose(env, "fd %d is not pointing to valid bpf_map\n",
  4652. insn->imm);
  4653. return PTR_ERR(map);
  4654. }
  4655. err = check_map_prog_compatibility(env, map, env->prog);
  4656. if (err) {
  4657. fdput(f);
  4658. return err;
  4659. }
  4660. /* store map pointer inside BPF_LD_IMM64 instruction */
  4661. insn[0].imm = (u32) (unsigned long) map;
  4662. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  4663. /* check whether we recorded this map already */
  4664. for (j = 0; j < env->used_map_cnt; j++)
  4665. if (env->used_maps[j] == map) {
  4666. fdput(f);
  4667. goto next_insn;
  4668. }
  4669. if (env->used_map_cnt >= MAX_USED_MAPS) {
  4670. fdput(f);
  4671. return -E2BIG;
  4672. }
  4673. /* hold the map. If the program is rejected by verifier,
  4674. * the map will be released by release_maps() or it
  4675. * will be used by the valid program until it's unloaded
  4676. * and all maps are released in free_used_maps()
  4677. */
  4678. map = bpf_map_inc(map, false);
  4679. if (IS_ERR(map)) {
  4680. fdput(f);
  4681. return PTR_ERR(map);
  4682. }
  4683. env->used_maps[env->used_map_cnt++] = map;
  4684. if (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE &&
  4685. bpf_cgroup_storage_assign(env->prog, map)) {
  4686. verbose(env,
  4687. "only one cgroup storage is allowed\n");
  4688. fdput(f);
  4689. return -EBUSY;
  4690. }
  4691. fdput(f);
  4692. next_insn:
  4693. insn++;
  4694. i++;
  4695. continue;
  4696. }
  4697. /* Basic sanity check before we invest more work here. */
  4698. if (!bpf_opcode_in_insntable(insn->code)) {
  4699. verbose(env, "unknown opcode %02x\n", insn->code);
  4700. return -EINVAL;
  4701. }
  4702. }
  4703. /* now all pseudo BPF_LD_IMM64 instructions load valid
  4704. * 'struct bpf_map *' into a register instead of user map_fd.
  4705. * These pointers will be used later by verifier to validate map access.
  4706. */
  4707. return 0;
  4708. }
  4709. /* drop refcnt of maps used by the rejected program */
  4710. static void release_maps(struct bpf_verifier_env *env)
  4711. {
  4712. int i;
  4713. if (env->prog->aux->cgroup_storage)
  4714. bpf_cgroup_storage_release(env->prog,
  4715. env->prog->aux->cgroup_storage);
  4716. for (i = 0; i < env->used_map_cnt; i++)
  4717. bpf_map_put(env->used_maps[i]);
  4718. }
  4719. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  4720. static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
  4721. {
  4722. struct bpf_insn *insn = env->prog->insnsi;
  4723. int insn_cnt = env->prog->len;
  4724. int i;
  4725. for (i = 0; i < insn_cnt; i++, insn++)
  4726. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  4727. insn->src_reg = 0;
  4728. }
  4729. /* single env->prog->insni[off] instruction was replaced with the range
  4730. * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
  4731. * [0, off) and [off, end) to new locations, so the patched range stays zero
  4732. */
  4733. static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
  4734. u32 off, u32 cnt)
  4735. {
  4736. struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
  4737. int i;
  4738. if (cnt == 1)
  4739. return 0;
  4740. new_data = vzalloc(array_size(prog_len,
  4741. sizeof(struct bpf_insn_aux_data)));
  4742. if (!new_data)
  4743. return -ENOMEM;
  4744. memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
  4745. memcpy(new_data + off + cnt - 1, old_data + off,
  4746. sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
  4747. for (i = off; i < off + cnt - 1; i++)
  4748. new_data[i].seen = true;
  4749. env->insn_aux_data = new_data;
  4750. vfree(old_data);
  4751. return 0;
  4752. }
  4753. static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
  4754. {
  4755. int i;
  4756. if (len == 1)
  4757. return;
  4758. /* NOTE: fake 'exit' subprog should be updated as well. */
  4759. for (i = 0; i <= env->subprog_cnt; i++) {
  4760. if (env->subprog_info[i].start < off)
  4761. continue;
  4762. env->subprog_info[i].start += len - 1;
  4763. }
  4764. }
  4765. static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
  4766. const struct bpf_insn *patch, u32 len)
  4767. {
  4768. struct bpf_prog *new_prog;
  4769. new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
  4770. if (!new_prog)
  4771. return NULL;
  4772. if (adjust_insn_aux_data(env, new_prog->len, off, len))
  4773. return NULL;
  4774. adjust_subprog_starts(env, off, len);
  4775. return new_prog;
  4776. }
  4777. /* The verifier does more data flow analysis than llvm and will not
  4778. * explore branches that are dead at run time. Malicious programs can
  4779. * have dead code too. Therefore replace all dead at-run-time code
  4780. * with 'ja -1'.
  4781. *
  4782. * Just nops are not optimal, e.g. if they would sit at the end of the
  4783. * program and through another bug we would manage to jump there, then
  4784. * we'd execute beyond program memory otherwise. Returning exception
  4785. * code also wouldn't work since we can have subprogs where the dead
  4786. * code could be located.
  4787. */
  4788. static void sanitize_dead_code(struct bpf_verifier_env *env)
  4789. {
  4790. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  4791. struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
  4792. struct bpf_insn *insn = env->prog->insnsi;
  4793. const int insn_cnt = env->prog->len;
  4794. int i;
  4795. for (i = 0; i < insn_cnt; i++) {
  4796. if (aux_data[i].seen)
  4797. continue;
  4798. memcpy(insn + i, &trap, sizeof(trap));
  4799. }
  4800. }
  4801. /* convert load instructions that access fields of 'struct __sk_buff'
  4802. * into sequence of instructions that access fields of 'struct sk_buff'
  4803. */
  4804. static int convert_ctx_accesses(struct bpf_verifier_env *env)
  4805. {
  4806. const struct bpf_verifier_ops *ops = env->ops;
  4807. int i, cnt, size, ctx_field_size, delta = 0;
  4808. const int insn_cnt = env->prog->len;
  4809. struct bpf_insn insn_buf[16], *insn;
  4810. struct bpf_prog *new_prog;
  4811. enum bpf_access_type type;
  4812. bool is_narrower_load;
  4813. u32 target_size;
  4814. if (ops->gen_prologue) {
  4815. cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
  4816. env->prog);
  4817. if (cnt >= ARRAY_SIZE(insn_buf)) {
  4818. verbose(env, "bpf verifier is misconfigured\n");
  4819. return -EINVAL;
  4820. } else if (cnt) {
  4821. new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
  4822. if (!new_prog)
  4823. return -ENOMEM;
  4824. env->prog = new_prog;
  4825. delta += cnt - 1;
  4826. }
  4827. }
  4828. if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
  4829. return 0;
  4830. insn = env->prog->insnsi + delta;
  4831. for (i = 0; i < insn_cnt; i++, insn++) {
  4832. if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
  4833. insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
  4834. insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  4835. insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
  4836. type = BPF_READ;
  4837. else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
  4838. insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
  4839. insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  4840. insn->code == (BPF_STX | BPF_MEM | BPF_DW))
  4841. type = BPF_WRITE;
  4842. else
  4843. continue;
  4844. if (type == BPF_WRITE &&
  4845. env->insn_aux_data[i + delta].sanitize_stack_off) {
  4846. struct bpf_insn patch[] = {
  4847. /* Sanitize suspicious stack slot with zero.
  4848. * There are no memory dependencies for this store,
  4849. * since it's only using frame pointer and immediate
  4850. * constant of zero
  4851. */
  4852. BPF_ST_MEM(BPF_DW, BPF_REG_FP,
  4853. env->insn_aux_data[i + delta].sanitize_stack_off,
  4854. 0),
  4855. /* the original STX instruction will immediately
  4856. * overwrite the same stack slot with appropriate value
  4857. */
  4858. *insn,
  4859. };
  4860. cnt = ARRAY_SIZE(patch);
  4861. new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
  4862. if (!new_prog)
  4863. return -ENOMEM;
  4864. delta += cnt - 1;
  4865. env->prog = new_prog;
  4866. insn = new_prog->insnsi + i + delta;
  4867. continue;
  4868. }
  4869. if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
  4870. continue;
  4871. ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
  4872. size = BPF_LDST_BYTES(insn);
  4873. /* If the read access is a narrower load of the field,
  4874. * convert to a 4/8-byte load, to minimum program type specific
  4875. * convert_ctx_access changes. If conversion is successful,
  4876. * we will apply proper mask to the result.
  4877. */
  4878. is_narrower_load = size < ctx_field_size;
  4879. if (is_narrower_load) {
  4880. u32 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
  4881. u32 off = insn->off;
  4882. u8 size_code;
  4883. if (type == BPF_WRITE) {
  4884. verbose(env, "bpf verifier narrow ctx access misconfigured\n");
  4885. return -EINVAL;
  4886. }
  4887. size_code = BPF_H;
  4888. if (ctx_field_size == 4)
  4889. size_code = BPF_W;
  4890. else if (ctx_field_size == 8)
  4891. size_code = BPF_DW;
  4892. insn->off = off & ~(size_default - 1);
  4893. insn->code = BPF_LDX | BPF_MEM | size_code;
  4894. }
  4895. target_size = 0;
  4896. cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
  4897. &target_size);
  4898. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
  4899. (ctx_field_size && !target_size)) {
  4900. verbose(env, "bpf verifier is misconfigured\n");
  4901. return -EINVAL;
  4902. }
  4903. if (is_narrower_load && size < target_size) {
  4904. if (ctx_field_size <= 4)
  4905. insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
  4906. (1 << size * 8) - 1);
  4907. else
  4908. insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
  4909. (1 << size * 8) - 1);
  4910. }
  4911. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  4912. if (!new_prog)
  4913. return -ENOMEM;
  4914. delta += cnt - 1;
  4915. /* keep walking new program and skip insns we just inserted */
  4916. env->prog = new_prog;
  4917. insn = new_prog->insnsi + i + delta;
  4918. }
  4919. return 0;
  4920. }
  4921. static int jit_subprogs(struct bpf_verifier_env *env)
  4922. {
  4923. struct bpf_prog *prog = env->prog, **func, *tmp;
  4924. int i, j, subprog_start, subprog_end = 0, len, subprog;
  4925. struct bpf_insn *insn;
  4926. void *old_bpf_func;
  4927. int err = -ENOMEM;
  4928. if (env->subprog_cnt <= 1)
  4929. return 0;
  4930. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  4931. if (insn->code != (BPF_JMP | BPF_CALL) ||
  4932. insn->src_reg != BPF_PSEUDO_CALL)
  4933. continue;
  4934. /* Upon error here we cannot fall back to interpreter but
  4935. * need a hard reject of the program. Thus -EFAULT is
  4936. * propagated in any case.
  4937. */
  4938. subprog = find_subprog(env, i + insn->imm + 1);
  4939. if (subprog < 0) {
  4940. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  4941. i + insn->imm + 1);
  4942. return -EFAULT;
  4943. }
  4944. /* temporarily remember subprog id inside insn instead of
  4945. * aux_data, since next loop will split up all insns into funcs
  4946. */
  4947. insn->off = subprog;
  4948. /* remember original imm in case JIT fails and fallback
  4949. * to interpreter will be needed
  4950. */
  4951. env->insn_aux_data[i].call_imm = insn->imm;
  4952. /* point imm to __bpf_call_base+1 from JITs point of view */
  4953. insn->imm = 1;
  4954. }
  4955. func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
  4956. if (!func)
  4957. goto out_undo_insn;
  4958. for (i = 0; i < env->subprog_cnt; i++) {
  4959. subprog_start = subprog_end;
  4960. subprog_end = env->subprog_info[i + 1].start;
  4961. len = subprog_end - subprog_start;
  4962. func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
  4963. if (!func[i])
  4964. goto out_free;
  4965. memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
  4966. len * sizeof(struct bpf_insn));
  4967. func[i]->type = prog->type;
  4968. func[i]->len = len;
  4969. if (bpf_prog_calc_tag(func[i]))
  4970. goto out_free;
  4971. func[i]->is_func = 1;
  4972. /* Use bpf_prog_F_tag to indicate functions in stack traces.
  4973. * Long term would need debug info to populate names
  4974. */
  4975. func[i]->aux->name[0] = 'F';
  4976. func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
  4977. func[i]->jit_requested = 1;
  4978. func[i] = bpf_int_jit_compile(func[i]);
  4979. if (!func[i]->jited) {
  4980. err = -ENOTSUPP;
  4981. goto out_free;
  4982. }
  4983. cond_resched();
  4984. }
  4985. /* at this point all bpf functions were successfully JITed
  4986. * now populate all bpf_calls with correct addresses and
  4987. * run last pass of JIT
  4988. */
  4989. for (i = 0; i < env->subprog_cnt; i++) {
  4990. insn = func[i]->insnsi;
  4991. for (j = 0; j < func[i]->len; j++, insn++) {
  4992. if (insn->code != (BPF_JMP | BPF_CALL) ||
  4993. insn->src_reg != BPF_PSEUDO_CALL)
  4994. continue;
  4995. subprog = insn->off;
  4996. insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
  4997. func[subprog]->bpf_func -
  4998. __bpf_call_base;
  4999. }
  5000. /* we use the aux data to keep a list of the start addresses
  5001. * of the JITed images for each function in the program
  5002. *
  5003. * for some architectures, such as powerpc64, the imm field
  5004. * might not be large enough to hold the offset of the start
  5005. * address of the callee's JITed image from __bpf_call_base
  5006. *
  5007. * in such cases, we can lookup the start address of a callee
  5008. * by using its subprog id, available from the off field of
  5009. * the call instruction, as an index for this list
  5010. */
  5011. func[i]->aux->func = func;
  5012. func[i]->aux->func_cnt = env->subprog_cnt;
  5013. }
  5014. for (i = 0; i < env->subprog_cnt; i++) {
  5015. old_bpf_func = func[i]->bpf_func;
  5016. tmp = bpf_int_jit_compile(func[i]);
  5017. if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
  5018. verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
  5019. err = -ENOTSUPP;
  5020. goto out_free;
  5021. }
  5022. cond_resched();
  5023. }
  5024. /* finally lock prog and jit images for all functions and
  5025. * populate kallsysm
  5026. */
  5027. for (i = 0; i < env->subprog_cnt; i++) {
  5028. bpf_prog_lock_ro(func[i]);
  5029. bpf_prog_kallsyms_add(func[i]);
  5030. }
  5031. /* Last step: make now unused interpreter insns from main
  5032. * prog consistent for later dump requests, so they can
  5033. * later look the same as if they were interpreted only.
  5034. */
  5035. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  5036. if (insn->code != (BPF_JMP | BPF_CALL) ||
  5037. insn->src_reg != BPF_PSEUDO_CALL)
  5038. continue;
  5039. insn->off = env->insn_aux_data[i].call_imm;
  5040. subprog = find_subprog(env, i + insn->off + 1);
  5041. insn->imm = subprog;
  5042. }
  5043. prog->jited = 1;
  5044. prog->bpf_func = func[0]->bpf_func;
  5045. prog->aux->func = func;
  5046. prog->aux->func_cnt = env->subprog_cnt;
  5047. return 0;
  5048. out_free:
  5049. for (i = 0; i < env->subprog_cnt; i++)
  5050. if (func[i])
  5051. bpf_jit_free(func[i]);
  5052. kfree(func);
  5053. out_undo_insn:
  5054. /* cleanup main prog to be interpreted */
  5055. prog->jit_requested = 0;
  5056. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  5057. if (insn->code != (BPF_JMP | BPF_CALL) ||
  5058. insn->src_reg != BPF_PSEUDO_CALL)
  5059. continue;
  5060. insn->off = 0;
  5061. insn->imm = env->insn_aux_data[i].call_imm;
  5062. }
  5063. return err;
  5064. }
  5065. static int fixup_call_args(struct bpf_verifier_env *env)
  5066. {
  5067. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  5068. struct bpf_prog *prog = env->prog;
  5069. struct bpf_insn *insn = prog->insnsi;
  5070. int i, depth;
  5071. #endif
  5072. int err;
  5073. err = 0;
  5074. if (env->prog->jit_requested) {
  5075. err = jit_subprogs(env);
  5076. if (err == 0)
  5077. return 0;
  5078. if (err == -EFAULT)
  5079. return err;
  5080. }
  5081. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  5082. for (i = 0; i < prog->len; i++, insn++) {
  5083. if (insn->code != (BPF_JMP | BPF_CALL) ||
  5084. insn->src_reg != BPF_PSEUDO_CALL)
  5085. continue;
  5086. depth = get_callee_stack_depth(env, insn, i);
  5087. if (depth < 0)
  5088. return depth;
  5089. bpf_patch_call_args(insn, depth);
  5090. }
  5091. err = 0;
  5092. #endif
  5093. return err;
  5094. }
  5095. /* fixup insn->imm field of bpf_call instructions
  5096. * and inline eligible helpers as explicit sequence of BPF instructions
  5097. *
  5098. * this function is called after eBPF program passed verification
  5099. */
  5100. static int fixup_bpf_calls(struct bpf_verifier_env *env)
  5101. {
  5102. struct bpf_prog *prog = env->prog;
  5103. struct bpf_insn *insn = prog->insnsi;
  5104. const struct bpf_func_proto *fn;
  5105. const int insn_cnt = prog->len;
  5106. const struct bpf_map_ops *ops;
  5107. struct bpf_insn_aux_data *aux;
  5108. struct bpf_insn insn_buf[16];
  5109. struct bpf_prog *new_prog;
  5110. struct bpf_map *map_ptr;
  5111. int i, cnt, delta = 0;
  5112. for (i = 0; i < insn_cnt; i++, insn++) {
  5113. if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
  5114. insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
  5115. insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
  5116. insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
  5117. bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
  5118. struct bpf_insn mask_and_div[] = {
  5119. BPF_MOV32_REG(insn->src_reg, insn->src_reg),
  5120. /* Rx div 0 -> 0 */
  5121. BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
  5122. BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
  5123. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  5124. *insn,
  5125. };
  5126. struct bpf_insn mask_and_mod[] = {
  5127. BPF_MOV32_REG(insn->src_reg, insn->src_reg),
  5128. /* Rx mod 0 -> Rx */
  5129. BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
  5130. *insn,
  5131. };
  5132. struct bpf_insn *patchlet;
  5133. if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
  5134. insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
  5135. patchlet = mask_and_div + (is64 ? 1 : 0);
  5136. cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
  5137. } else {
  5138. patchlet = mask_and_mod + (is64 ? 1 : 0);
  5139. cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
  5140. }
  5141. new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
  5142. if (!new_prog)
  5143. return -ENOMEM;
  5144. delta += cnt - 1;
  5145. env->prog = prog = new_prog;
  5146. insn = new_prog->insnsi + i + delta;
  5147. continue;
  5148. }
  5149. if (BPF_CLASS(insn->code) == BPF_LD &&
  5150. (BPF_MODE(insn->code) == BPF_ABS ||
  5151. BPF_MODE(insn->code) == BPF_IND)) {
  5152. cnt = env->ops->gen_ld_abs(insn, insn_buf);
  5153. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  5154. verbose(env, "bpf verifier is misconfigured\n");
  5155. return -EINVAL;
  5156. }
  5157. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  5158. if (!new_prog)
  5159. return -ENOMEM;
  5160. delta += cnt - 1;
  5161. env->prog = prog = new_prog;
  5162. insn = new_prog->insnsi + i + delta;
  5163. continue;
  5164. }
  5165. if (insn->code != (BPF_JMP | BPF_CALL))
  5166. continue;
  5167. if (insn->src_reg == BPF_PSEUDO_CALL)
  5168. continue;
  5169. if (insn->imm == BPF_FUNC_get_route_realm)
  5170. prog->dst_needed = 1;
  5171. if (insn->imm == BPF_FUNC_get_prandom_u32)
  5172. bpf_user_rnd_init_once();
  5173. if (insn->imm == BPF_FUNC_override_return)
  5174. prog->kprobe_override = 1;
  5175. if (insn->imm == BPF_FUNC_tail_call) {
  5176. /* If we tail call into other programs, we
  5177. * cannot make any assumptions since they can
  5178. * be replaced dynamically during runtime in
  5179. * the program array.
  5180. */
  5181. prog->cb_access = 1;
  5182. env->prog->aux->stack_depth = MAX_BPF_STACK;
  5183. /* mark bpf_tail_call as different opcode to avoid
  5184. * conditional branch in the interpeter for every normal
  5185. * call and to prevent accidental JITing by JIT compiler
  5186. * that doesn't support bpf_tail_call yet
  5187. */
  5188. insn->imm = 0;
  5189. insn->code = BPF_JMP | BPF_TAIL_CALL;
  5190. aux = &env->insn_aux_data[i + delta];
  5191. if (!bpf_map_ptr_unpriv(aux))
  5192. continue;
  5193. /* instead of changing every JIT dealing with tail_call
  5194. * emit two extra insns:
  5195. * if (index >= max_entries) goto out;
  5196. * index &= array->index_mask;
  5197. * to avoid out-of-bounds cpu speculation
  5198. */
  5199. if (bpf_map_ptr_poisoned(aux)) {
  5200. verbose(env, "tail_call abusing map_ptr\n");
  5201. return -EINVAL;
  5202. }
  5203. map_ptr = BPF_MAP_PTR(aux->map_state);
  5204. insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
  5205. map_ptr->max_entries, 2);
  5206. insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
  5207. container_of(map_ptr,
  5208. struct bpf_array,
  5209. map)->index_mask);
  5210. insn_buf[2] = *insn;
  5211. cnt = 3;
  5212. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  5213. if (!new_prog)
  5214. return -ENOMEM;
  5215. delta += cnt - 1;
  5216. env->prog = prog = new_prog;
  5217. insn = new_prog->insnsi + i + delta;
  5218. continue;
  5219. }
  5220. /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
  5221. * and other inlining handlers are currently limited to 64 bit
  5222. * only.
  5223. */
  5224. if (prog->jit_requested && BITS_PER_LONG == 64 &&
  5225. (insn->imm == BPF_FUNC_map_lookup_elem ||
  5226. insn->imm == BPF_FUNC_map_update_elem ||
  5227. insn->imm == BPF_FUNC_map_delete_elem)) {
  5228. aux = &env->insn_aux_data[i + delta];
  5229. if (bpf_map_ptr_poisoned(aux))
  5230. goto patch_call_imm;
  5231. map_ptr = BPF_MAP_PTR(aux->map_state);
  5232. ops = map_ptr->ops;
  5233. if (insn->imm == BPF_FUNC_map_lookup_elem &&
  5234. ops->map_gen_lookup) {
  5235. cnt = ops->map_gen_lookup(map_ptr, insn_buf);
  5236. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  5237. verbose(env, "bpf verifier is misconfigured\n");
  5238. return -EINVAL;
  5239. }
  5240. new_prog = bpf_patch_insn_data(env, i + delta,
  5241. insn_buf, cnt);
  5242. if (!new_prog)
  5243. return -ENOMEM;
  5244. delta += cnt - 1;
  5245. env->prog = prog = new_prog;
  5246. insn = new_prog->insnsi + i + delta;
  5247. continue;
  5248. }
  5249. BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
  5250. (void *(*)(struct bpf_map *map, void *key))NULL));
  5251. BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
  5252. (int (*)(struct bpf_map *map, void *key))NULL));
  5253. BUILD_BUG_ON(!__same_type(ops->map_update_elem,
  5254. (int (*)(struct bpf_map *map, void *key, void *value,
  5255. u64 flags))NULL));
  5256. switch (insn->imm) {
  5257. case BPF_FUNC_map_lookup_elem:
  5258. insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
  5259. __bpf_call_base;
  5260. continue;
  5261. case BPF_FUNC_map_update_elem:
  5262. insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
  5263. __bpf_call_base;
  5264. continue;
  5265. case BPF_FUNC_map_delete_elem:
  5266. insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
  5267. __bpf_call_base;
  5268. continue;
  5269. }
  5270. goto patch_call_imm;
  5271. }
  5272. if (insn->imm == BPF_FUNC_redirect_map) {
  5273. /* Note, we cannot use prog directly as imm as subsequent
  5274. * rewrites would still change the prog pointer. The only
  5275. * stable address we can use is aux, which also works with
  5276. * prog clones during blinding.
  5277. */
  5278. u64 addr = (unsigned long)prog->aux;
  5279. struct bpf_insn r4_ld[] = {
  5280. BPF_LD_IMM64(BPF_REG_4, addr),
  5281. *insn,
  5282. };
  5283. cnt = ARRAY_SIZE(r4_ld);
  5284. new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
  5285. if (!new_prog)
  5286. return -ENOMEM;
  5287. delta += cnt - 1;
  5288. env->prog = prog = new_prog;
  5289. insn = new_prog->insnsi + i + delta;
  5290. }
  5291. patch_call_imm:
  5292. fn = env->ops->get_func_proto(insn->imm, env->prog);
  5293. /* all functions that have prototype and verifier allowed
  5294. * programs to call them, must be real in-kernel functions
  5295. */
  5296. if (!fn->func) {
  5297. verbose(env,
  5298. "kernel subsystem misconfigured func %s#%d\n",
  5299. func_id_name(insn->imm), insn->imm);
  5300. return -EFAULT;
  5301. }
  5302. insn->imm = fn->func - __bpf_call_base;
  5303. }
  5304. return 0;
  5305. }
  5306. static void free_states(struct bpf_verifier_env *env)
  5307. {
  5308. struct bpf_verifier_state_list *sl, *sln;
  5309. int i;
  5310. if (!env->explored_states)
  5311. return;
  5312. for (i = 0; i < env->prog->len; i++) {
  5313. sl = env->explored_states[i];
  5314. if (sl)
  5315. while (sl != STATE_LIST_MARK) {
  5316. sln = sl->next;
  5317. free_verifier_state(&sl->state, false);
  5318. kfree(sl);
  5319. sl = sln;
  5320. }
  5321. }
  5322. kfree(env->explored_states);
  5323. }
  5324. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  5325. {
  5326. struct bpf_verifier_env *env;
  5327. struct bpf_verifier_log *log;
  5328. int ret = -EINVAL;
  5329. /* no program is valid */
  5330. if (ARRAY_SIZE(bpf_verifier_ops) == 0)
  5331. return -EINVAL;
  5332. /* 'struct bpf_verifier_env' can be global, but since it's not small,
  5333. * allocate/free it every time bpf_check() is called
  5334. */
  5335. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  5336. if (!env)
  5337. return -ENOMEM;
  5338. log = &env->log;
  5339. env->insn_aux_data =
  5340. vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
  5341. (*prog)->len));
  5342. ret = -ENOMEM;
  5343. if (!env->insn_aux_data)
  5344. goto err_free_env;
  5345. env->prog = *prog;
  5346. env->ops = bpf_verifier_ops[env->prog->type];
  5347. /* grab the mutex to protect few globals used by verifier */
  5348. mutex_lock(&bpf_verifier_lock);
  5349. if (attr->log_level || attr->log_buf || attr->log_size) {
  5350. /* user requested verbose verifier output
  5351. * and supplied buffer to store the verification trace
  5352. */
  5353. log->level = attr->log_level;
  5354. log->ubuf = (char __user *) (unsigned long) attr->log_buf;
  5355. log->len_total = attr->log_size;
  5356. ret = -EINVAL;
  5357. /* log attributes have to be sane */
  5358. if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
  5359. !log->level || !log->ubuf)
  5360. goto err_unlock;
  5361. }
  5362. env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
  5363. if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
  5364. env->strict_alignment = true;
  5365. ret = replace_map_fd_with_map_ptr(env);
  5366. if (ret < 0)
  5367. goto skip_full_check;
  5368. if (bpf_prog_is_dev_bound(env->prog->aux)) {
  5369. ret = bpf_prog_offload_verifier_prep(env);
  5370. if (ret)
  5371. goto skip_full_check;
  5372. }
  5373. env->explored_states = kcalloc(env->prog->len,
  5374. sizeof(struct bpf_verifier_state_list *),
  5375. GFP_USER);
  5376. ret = -ENOMEM;
  5377. if (!env->explored_states)
  5378. goto skip_full_check;
  5379. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  5380. ret = check_cfg(env);
  5381. if (ret < 0)
  5382. goto skip_full_check;
  5383. ret = do_check(env);
  5384. if (env->cur_state) {
  5385. free_verifier_state(env->cur_state, true);
  5386. env->cur_state = NULL;
  5387. }
  5388. skip_full_check:
  5389. while (!pop_stack(env, NULL, NULL));
  5390. free_states(env);
  5391. if (ret == 0)
  5392. sanitize_dead_code(env);
  5393. if (ret == 0)
  5394. ret = check_max_stack_depth(env);
  5395. if (ret == 0)
  5396. /* program is valid, convert *(u32*)(ctx + off) accesses */
  5397. ret = convert_ctx_accesses(env);
  5398. if (ret == 0)
  5399. ret = fixup_bpf_calls(env);
  5400. if (ret == 0)
  5401. ret = fixup_call_args(env);
  5402. if (log->level && bpf_verifier_log_full(log))
  5403. ret = -ENOSPC;
  5404. if (log->level && !log->ubuf) {
  5405. ret = -EFAULT;
  5406. goto err_release_maps;
  5407. }
  5408. if (ret == 0 && env->used_map_cnt) {
  5409. /* if program passed verifier, update used_maps in bpf_prog_info */
  5410. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  5411. sizeof(env->used_maps[0]),
  5412. GFP_KERNEL);
  5413. if (!env->prog->aux->used_maps) {
  5414. ret = -ENOMEM;
  5415. goto err_release_maps;
  5416. }
  5417. memcpy(env->prog->aux->used_maps, env->used_maps,
  5418. sizeof(env->used_maps[0]) * env->used_map_cnt);
  5419. env->prog->aux->used_map_cnt = env->used_map_cnt;
  5420. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  5421. * bpf_ld_imm64 instructions
  5422. */
  5423. convert_pseudo_ld_imm64(env);
  5424. }
  5425. err_release_maps:
  5426. if (!env->prog->aux->used_maps)
  5427. /* if we didn't copy map pointers into bpf_prog_info, release
  5428. * them now. Otherwise free_used_maps() will release them.
  5429. */
  5430. release_maps(env);
  5431. *prog = env->prog;
  5432. err_unlock:
  5433. mutex_unlock(&bpf_verifier_lock);
  5434. vfree(env->insn_aux_data);
  5435. err_free_env:
  5436. kfree(env);
  5437. return ret;
  5438. }