verifier.c 187 KB

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