verifier.c 170 KB

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