verifier.c 167 KB

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