verifier.c 188 KB

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