verifier.c 186 KB

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