verifier.c 359 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  3. * Copyright (c) 2016 Facebook
  4. * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
  5. */
  6. #include <uapi/linux/btf.h>
  7. #include <linux/kernel.h>
  8. #include <linux/types.h>
  9. #include <linux/slab.h>
  10. #include <linux/bpf.h>
  11. #include <linux/btf.h>
  12. #include <linux/bpf_verifier.h>
  13. #include <linux/filter.h>
  14. #include <net/netlink.h>
  15. #include <linux/file.h>
  16. #include <linux/vmalloc.h>
  17. #include <linux/stringify.h>
  18. #include <linux/bsearch.h>
  19. #include <linux/sort.h>
  20. #include <linux/perf_event.h>
  21. #include <linux/ctype.h>
  22. #include <linux/error-injection.h>
  23. #include <linux/bpf_lsm.h>
  24. #include <linux/btf_ids.h>
  25. #include "disasm.h"
  26. static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
  27. #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
  28. [_id] = & _name ## _verifier_ops,
  29. #define BPF_MAP_TYPE(_id, _ops)
  30. #define BPF_LINK_TYPE(_id, _name)
  31. #include <linux/bpf_types.h>
  32. #undef BPF_PROG_TYPE
  33. #undef BPF_MAP_TYPE
  34. #undef BPF_LINK_TYPE
  35. };
  36. /* bpf_check() is a static code analyzer that walks eBPF program
  37. * instruction by instruction and updates register/stack state.
  38. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  39. *
  40. * The first pass is depth-first-search to check that the program is a DAG.
  41. * It rejects the following programs:
  42. * - larger than BPF_MAXINSNS insns
  43. * - if loop is present (detected via back-edge)
  44. * - unreachable insns exist (shouldn't be a forest. program = one function)
  45. * - out of bounds or malformed jumps
  46. * The second pass is all possible path descent from the 1st insn.
  47. * Since it's analyzing all pathes through the program, the length of the
  48. * analysis is limited to 64k insn, which may be hit even if total number of
  49. * insn is less then 4K, but there are too many branches that change stack/regs.
  50. * Number of 'branches to be analyzed' is limited to 1k
  51. *
  52. * On entry to each instruction, each register has a type, and the instruction
  53. * changes the types of the registers depending on instruction semantics.
  54. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  55. * copied to R1.
  56. *
  57. * All registers are 64-bit.
  58. * R0 - return register
  59. * R1-R5 argument passing registers
  60. * R6-R9 callee saved registers
  61. * R10 - frame pointer read-only
  62. *
  63. * At the start of BPF program the register R1 contains a pointer to bpf_context
  64. * and has type PTR_TO_CTX.
  65. *
  66. * Verifier tracks arithmetic operations on pointers in case:
  67. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  68. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  69. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  70. * and 2nd arithmetic instruction is pattern matched to recognize
  71. * that it wants to construct a pointer to some element within stack.
  72. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  73. * (and -20 constant is saved for further stack bounds checking).
  74. * Meaning that this reg is a pointer to stack plus known immediate constant.
  75. *
  76. * Most of the time the registers have SCALAR_VALUE type, which
  77. * means the register has some value, but it's not a valid pointer.
  78. * (like pointer plus pointer becomes SCALAR_VALUE type)
  79. *
  80. * When verifier sees load or store instructions the type of base register
  81. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
  82. * four pointer types recognized by check_mem_access() function.
  83. *
  84. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  85. * and the range of [ptr, ptr + map's value_size) is accessible.
  86. *
  87. * registers used to pass values to function calls are checked against
  88. * function argument constraints.
  89. *
  90. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  91. * It means that the register type passed to this function must be
  92. * PTR_TO_STACK and it will be used inside the function as
  93. * 'pointer to map element key'
  94. *
  95. * For example the argument constraints for bpf_map_lookup_elem():
  96. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  97. * .arg1_type = ARG_CONST_MAP_PTR,
  98. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  99. *
  100. * ret_type says that this function returns 'pointer to map elem value or null'
  101. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  102. * 2nd argument should be a pointer to stack, which will be used inside
  103. * the helper function as a pointer to map element key.
  104. *
  105. * On the kernel side the helper function looks like:
  106. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  107. * {
  108. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  109. * void *key = (void *) (unsigned long) r2;
  110. * void *value;
  111. *
  112. * here kernel can access 'key' and 'map' pointers safely, knowing that
  113. * [key, key + map->key_size) bytes are valid and were initialized on
  114. * the stack of eBPF program.
  115. * }
  116. *
  117. * Corresponding eBPF program may look like:
  118. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  119. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  120. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  121. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  122. * here verifier looks at prototype of map_lookup_elem() and sees:
  123. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  124. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  125. *
  126. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  127. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  128. * and were initialized prior to this call.
  129. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  130. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  131. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  132. * returns ether pointer to map value or NULL.
  133. *
  134. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  135. * insn, the register holding that pointer in the true branch changes state to
  136. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  137. * branch. See check_cond_jmp_op().
  138. *
  139. * After the call R0 is set to return type of the function and registers R1-R5
  140. * are set to NOT_INIT to indicate that they are no longer readable.
  141. *
  142. * The following reference types represent a potential reference to a kernel
  143. * resource which, after first being allocated, must be checked and freed by
  144. * the BPF program:
  145. * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
  146. *
  147. * When the verifier sees a helper call return a reference type, it allocates a
  148. * pointer id for the reference and stores it in the current function state.
  149. * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
  150. * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
  151. * passes through a NULL-check conditional. For the branch wherein the state is
  152. * changed to CONST_IMM, the verifier releases the reference.
  153. *
  154. * For each helper function that allocates a reference, such as
  155. * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
  156. * bpf_sk_release(). When a reference type passes into the release function,
  157. * the verifier also releases the reference. If any unchecked or unreleased
  158. * reference remains at the end of the program, the verifier rejects it.
  159. */
  160. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  161. struct bpf_verifier_stack_elem {
  162. /* verifer state is 'st'
  163. * before processing instruction 'insn_idx'
  164. * and after processing instruction 'prev_insn_idx'
  165. */
  166. struct bpf_verifier_state st;
  167. int insn_idx;
  168. int prev_insn_idx;
  169. struct bpf_verifier_stack_elem *next;
  170. /* length of verifier log at the time this state was pushed on stack */
  171. u32 log_pos;
  172. };
  173. #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
  174. #define BPF_COMPLEXITY_LIMIT_STATES 64
  175. #define BPF_MAP_KEY_POISON (1ULL << 63)
  176. #define BPF_MAP_KEY_SEEN (1ULL << 62)
  177. #define BPF_MAP_PTR_UNPRIV 1UL
  178. #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
  179. POISON_POINTER_DELTA))
  180. #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
  181. static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
  182. {
  183. return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
  184. }
  185. static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
  186. {
  187. return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
  188. }
  189. static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
  190. const struct bpf_map *map, bool unpriv)
  191. {
  192. BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
  193. unpriv |= bpf_map_ptr_unpriv(aux);
  194. aux->map_ptr_state = (unsigned long)map |
  195. (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
  196. }
  197. static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
  198. {
  199. return aux->map_key_state & BPF_MAP_KEY_POISON;
  200. }
  201. static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
  202. {
  203. return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
  204. }
  205. static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
  206. {
  207. return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
  208. }
  209. static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
  210. {
  211. bool poisoned = bpf_map_key_poisoned(aux);
  212. aux->map_key_state = state | BPF_MAP_KEY_SEEN |
  213. (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
  214. }
  215. struct bpf_call_arg_meta {
  216. struct bpf_map *map_ptr;
  217. bool raw_mode;
  218. bool pkt_access;
  219. int regno;
  220. int access_size;
  221. int mem_size;
  222. u64 msize_max_value;
  223. int ref_obj_id;
  224. int func_id;
  225. u32 btf_id;
  226. u32 ret_btf_id;
  227. };
  228. struct btf *btf_vmlinux;
  229. static DEFINE_MUTEX(bpf_verifier_lock);
  230. static const struct bpf_line_info *
  231. find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
  232. {
  233. const struct bpf_line_info *linfo;
  234. const struct bpf_prog *prog;
  235. u32 i, nr_linfo;
  236. prog = env->prog;
  237. nr_linfo = prog->aux->nr_linfo;
  238. if (!nr_linfo || insn_off >= prog->len)
  239. return NULL;
  240. linfo = prog->aux->linfo;
  241. for (i = 1; i < nr_linfo; i++)
  242. if (insn_off < linfo[i].insn_off)
  243. break;
  244. return &linfo[i - 1];
  245. }
  246. void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
  247. va_list args)
  248. {
  249. unsigned int n;
  250. n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
  251. WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
  252. "verifier log line truncated - local buffer too short\n");
  253. n = min(log->len_total - log->len_used - 1, n);
  254. log->kbuf[n] = '\0';
  255. if (log->level == BPF_LOG_KERNEL) {
  256. pr_err("BPF:%s\n", log->kbuf);
  257. return;
  258. }
  259. if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
  260. log->len_used += n;
  261. else
  262. log->ubuf = NULL;
  263. }
  264. static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
  265. {
  266. char zero = 0;
  267. if (!bpf_verifier_log_needed(log))
  268. return;
  269. log->len_used = new_pos;
  270. if (put_user(zero, log->ubuf + new_pos))
  271. log->ubuf = NULL;
  272. }
  273. /* log_level controls verbosity level of eBPF verifier.
  274. * bpf_verifier_log_write() is used to dump the verification trace to the log,
  275. * so the user can figure out what's wrong with the program
  276. */
  277. __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
  278. const char *fmt, ...)
  279. {
  280. va_list args;
  281. if (!bpf_verifier_log_needed(&env->log))
  282. return;
  283. va_start(args, fmt);
  284. bpf_verifier_vlog(&env->log, fmt, args);
  285. va_end(args);
  286. }
  287. EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
  288. __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
  289. {
  290. struct bpf_verifier_env *env = private_data;
  291. va_list args;
  292. if (!bpf_verifier_log_needed(&env->log))
  293. return;
  294. va_start(args, fmt);
  295. bpf_verifier_vlog(&env->log, fmt, args);
  296. va_end(args);
  297. }
  298. __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
  299. const char *fmt, ...)
  300. {
  301. va_list args;
  302. if (!bpf_verifier_log_needed(log))
  303. return;
  304. va_start(args, fmt);
  305. bpf_verifier_vlog(log, fmt, args);
  306. va_end(args);
  307. }
  308. static const char *ltrim(const char *s)
  309. {
  310. while (isspace(*s))
  311. s++;
  312. return s;
  313. }
  314. __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
  315. u32 insn_off,
  316. const char *prefix_fmt, ...)
  317. {
  318. const struct bpf_line_info *linfo;
  319. if (!bpf_verifier_log_needed(&env->log))
  320. return;
  321. linfo = find_linfo(env, insn_off);
  322. if (!linfo || linfo == env->prev_linfo)
  323. return;
  324. if (prefix_fmt) {
  325. va_list args;
  326. va_start(args, prefix_fmt);
  327. bpf_verifier_vlog(&env->log, prefix_fmt, args);
  328. va_end(args);
  329. }
  330. verbose(env, "%s\n",
  331. ltrim(btf_name_by_offset(env->prog->aux->btf,
  332. linfo->line_off)));
  333. env->prev_linfo = linfo;
  334. }
  335. static bool type_is_pkt_pointer(enum bpf_reg_type type)
  336. {
  337. return type == PTR_TO_PACKET ||
  338. type == PTR_TO_PACKET_META;
  339. }
  340. static bool type_is_sk_pointer(enum bpf_reg_type type)
  341. {
  342. return type == PTR_TO_SOCKET ||
  343. type == PTR_TO_SOCK_COMMON ||
  344. type == PTR_TO_TCP_SOCK ||
  345. type == PTR_TO_XDP_SOCK;
  346. }
  347. static bool reg_type_not_null(enum bpf_reg_type type)
  348. {
  349. return type == PTR_TO_SOCKET ||
  350. type == PTR_TO_TCP_SOCK ||
  351. type == PTR_TO_MAP_VALUE ||
  352. type == PTR_TO_SOCK_COMMON;
  353. }
  354. static bool reg_type_may_be_null(enum bpf_reg_type type)
  355. {
  356. return type == PTR_TO_MAP_VALUE_OR_NULL ||
  357. type == PTR_TO_SOCKET_OR_NULL ||
  358. type == PTR_TO_SOCK_COMMON_OR_NULL ||
  359. type == PTR_TO_TCP_SOCK_OR_NULL ||
  360. type == PTR_TO_BTF_ID_OR_NULL ||
  361. type == PTR_TO_MEM_OR_NULL ||
  362. type == PTR_TO_RDONLY_BUF_OR_NULL ||
  363. type == PTR_TO_RDWR_BUF_OR_NULL;
  364. }
  365. static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
  366. {
  367. return reg->type == PTR_TO_MAP_VALUE &&
  368. map_value_has_spin_lock(reg->map_ptr);
  369. }
  370. static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
  371. {
  372. return type == PTR_TO_SOCKET ||
  373. type == PTR_TO_SOCKET_OR_NULL ||
  374. type == PTR_TO_TCP_SOCK ||
  375. type == PTR_TO_TCP_SOCK_OR_NULL ||
  376. type == PTR_TO_MEM ||
  377. type == PTR_TO_MEM_OR_NULL;
  378. }
  379. static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
  380. {
  381. return type == ARG_PTR_TO_SOCK_COMMON;
  382. }
  383. static bool arg_type_may_be_null(enum bpf_arg_type type)
  384. {
  385. return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
  386. type == ARG_PTR_TO_MEM_OR_NULL ||
  387. type == ARG_PTR_TO_CTX_OR_NULL ||
  388. type == ARG_PTR_TO_SOCKET_OR_NULL ||
  389. type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
  390. }
  391. /* Determine whether the function releases some resources allocated by another
  392. * function call. The first reference type argument will be assumed to be
  393. * released by release_reference().
  394. */
  395. static bool is_release_function(enum bpf_func_id func_id)
  396. {
  397. return func_id == BPF_FUNC_sk_release ||
  398. func_id == BPF_FUNC_ringbuf_submit ||
  399. func_id == BPF_FUNC_ringbuf_discard;
  400. }
  401. static bool may_be_acquire_function(enum bpf_func_id func_id)
  402. {
  403. return func_id == BPF_FUNC_sk_lookup_tcp ||
  404. func_id == BPF_FUNC_sk_lookup_udp ||
  405. func_id == BPF_FUNC_skc_lookup_tcp ||
  406. func_id == BPF_FUNC_map_lookup_elem ||
  407. func_id == BPF_FUNC_ringbuf_reserve;
  408. }
  409. static bool is_acquire_function(enum bpf_func_id func_id,
  410. const struct bpf_map *map)
  411. {
  412. enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
  413. if (func_id == BPF_FUNC_sk_lookup_tcp ||
  414. func_id == BPF_FUNC_sk_lookup_udp ||
  415. func_id == BPF_FUNC_skc_lookup_tcp ||
  416. func_id == BPF_FUNC_ringbuf_reserve)
  417. return true;
  418. if (func_id == BPF_FUNC_map_lookup_elem &&
  419. (map_type == BPF_MAP_TYPE_SOCKMAP ||
  420. map_type == BPF_MAP_TYPE_SOCKHASH))
  421. return true;
  422. return false;
  423. }
  424. static bool is_ptr_cast_function(enum bpf_func_id func_id)
  425. {
  426. return func_id == BPF_FUNC_tcp_sock ||
  427. func_id == BPF_FUNC_sk_fullsock ||
  428. func_id == BPF_FUNC_skc_to_tcp_sock ||
  429. func_id == BPF_FUNC_skc_to_tcp6_sock ||
  430. func_id == BPF_FUNC_skc_to_udp6_sock ||
  431. func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
  432. func_id == BPF_FUNC_skc_to_tcp_request_sock;
  433. }
  434. /* string representation of 'enum bpf_reg_type' */
  435. static const char * const reg_type_str[] = {
  436. [NOT_INIT] = "?",
  437. [SCALAR_VALUE] = "inv",
  438. [PTR_TO_CTX] = "ctx",
  439. [CONST_PTR_TO_MAP] = "map_ptr",
  440. [PTR_TO_MAP_VALUE] = "map_value",
  441. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  442. [PTR_TO_STACK] = "fp",
  443. [PTR_TO_PACKET] = "pkt",
  444. [PTR_TO_PACKET_META] = "pkt_meta",
  445. [PTR_TO_PACKET_END] = "pkt_end",
  446. [PTR_TO_FLOW_KEYS] = "flow_keys",
  447. [PTR_TO_SOCKET] = "sock",
  448. [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
  449. [PTR_TO_SOCK_COMMON] = "sock_common",
  450. [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
  451. [PTR_TO_TCP_SOCK] = "tcp_sock",
  452. [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
  453. [PTR_TO_TP_BUFFER] = "tp_buffer",
  454. [PTR_TO_XDP_SOCK] = "xdp_sock",
  455. [PTR_TO_BTF_ID] = "ptr_",
  456. [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
  457. [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
  458. [PTR_TO_MEM] = "mem",
  459. [PTR_TO_MEM_OR_NULL] = "mem_or_null",
  460. [PTR_TO_RDONLY_BUF] = "rdonly_buf",
  461. [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
  462. [PTR_TO_RDWR_BUF] = "rdwr_buf",
  463. [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
  464. };
  465. static char slot_type_char[] = {
  466. [STACK_INVALID] = '?',
  467. [STACK_SPILL] = 'r',
  468. [STACK_MISC] = 'm',
  469. [STACK_ZERO] = '0',
  470. };
  471. static void print_liveness(struct bpf_verifier_env *env,
  472. enum bpf_reg_liveness live)
  473. {
  474. if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
  475. verbose(env, "_");
  476. if (live & REG_LIVE_READ)
  477. verbose(env, "r");
  478. if (live & REG_LIVE_WRITTEN)
  479. verbose(env, "w");
  480. if (live & REG_LIVE_DONE)
  481. verbose(env, "D");
  482. }
  483. static struct bpf_func_state *func(struct bpf_verifier_env *env,
  484. const struct bpf_reg_state *reg)
  485. {
  486. struct bpf_verifier_state *cur = env->cur_state;
  487. return cur->frame[reg->frameno];
  488. }
  489. const char *kernel_type_name(u32 id)
  490. {
  491. return btf_name_by_offset(btf_vmlinux,
  492. btf_type_by_id(btf_vmlinux, id)->name_off);
  493. }
  494. static void print_verifier_state(struct bpf_verifier_env *env,
  495. const struct bpf_func_state *state)
  496. {
  497. const struct bpf_reg_state *reg;
  498. enum bpf_reg_type t;
  499. int i;
  500. if (state->frameno)
  501. verbose(env, " frame%d:", state->frameno);
  502. for (i = 0; i < MAX_BPF_REG; i++) {
  503. reg = &state->regs[i];
  504. t = reg->type;
  505. if (t == NOT_INIT)
  506. continue;
  507. verbose(env, " R%d", i);
  508. print_liveness(env, reg->live);
  509. verbose(env, "=%s", reg_type_str[t]);
  510. if (t == SCALAR_VALUE && reg->precise)
  511. verbose(env, "P");
  512. if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
  513. tnum_is_const(reg->var_off)) {
  514. /* reg->off should be 0 for SCALAR_VALUE */
  515. verbose(env, "%lld", reg->var_off.value + reg->off);
  516. } else {
  517. if (t == PTR_TO_BTF_ID ||
  518. t == PTR_TO_BTF_ID_OR_NULL ||
  519. t == PTR_TO_PERCPU_BTF_ID)
  520. verbose(env, "%s", kernel_type_name(reg->btf_id));
  521. verbose(env, "(id=%d", reg->id);
  522. if (reg_type_may_be_refcounted_or_null(t))
  523. verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
  524. if (t != SCALAR_VALUE)
  525. verbose(env, ",off=%d", reg->off);
  526. if (type_is_pkt_pointer(t))
  527. verbose(env, ",r=%d", reg->range);
  528. else if (t == CONST_PTR_TO_MAP ||
  529. t == PTR_TO_MAP_VALUE ||
  530. t == PTR_TO_MAP_VALUE_OR_NULL)
  531. verbose(env, ",ks=%d,vs=%d",
  532. reg->map_ptr->key_size,
  533. reg->map_ptr->value_size);
  534. if (tnum_is_const(reg->var_off)) {
  535. /* Typically an immediate SCALAR_VALUE, but
  536. * could be a pointer whose offset is too big
  537. * for reg->off
  538. */
  539. verbose(env, ",imm=%llx", reg->var_off.value);
  540. } else {
  541. if (reg->smin_value != reg->umin_value &&
  542. reg->smin_value != S64_MIN)
  543. verbose(env, ",smin_value=%lld",
  544. (long long)reg->smin_value);
  545. if (reg->smax_value != reg->umax_value &&
  546. reg->smax_value != S64_MAX)
  547. verbose(env, ",smax_value=%lld",
  548. (long long)reg->smax_value);
  549. if (reg->umin_value != 0)
  550. verbose(env, ",umin_value=%llu",
  551. (unsigned long long)reg->umin_value);
  552. if (reg->umax_value != U64_MAX)
  553. verbose(env, ",umax_value=%llu",
  554. (unsigned long long)reg->umax_value);
  555. if (!tnum_is_unknown(reg->var_off)) {
  556. char tn_buf[48];
  557. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  558. verbose(env, ",var_off=%s", tn_buf);
  559. }
  560. if (reg->s32_min_value != reg->smin_value &&
  561. reg->s32_min_value != S32_MIN)
  562. verbose(env, ",s32_min_value=%d",
  563. (int)(reg->s32_min_value));
  564. if (reg->s32_max_value != reg->smax_value &&
  565. reg->s32_max_value != S32_MAX)
  566. verbose(env, ",s32_max_value=%d",
  567. (int)(reg->s32_max_value));
  568. if (reg->u32_min_value != reg->umin_value &&
  569. reg->u32_min_value != U32_MIN)
  570. verbose(env, ",u32_min_value=%d",
  571. (int)(reg->u32_min_value));
  572. if (reg->u32_max_value != reg->umax_value &&
  573. reg->u32_max_value != U32_MAX)
  574. verbose(env, ",u32_max_value=%d",
  575. (int)(reg->u32_max_value));
  576. }
  577. verbose(env, ")");
  578. }
  579. }
  580. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  581. char types_buf[BPF_REG_SIZE + 1];
  582. bool valid = false;
  583. int j;
  584. for (j = 0; j < BPF_REG_SIZE; j++) {
  585. if (state->stack[i].slot_type[j] != STACK_INVALID)
  586. valid = true;
  587. types_buf[j] = slot_type_char[
  588. state->stack[i].slot_type[j]];
  589. }
  590. types_buf[BPF_REG_SIZE] = 0;
  591. if (!valid)
  592. continue;
  593. verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
  594. print_liveness(env, state->stack[i].spilled_ptr.live);
  595. if (state->stack[i].slot_type[0] == STACK_SPILL) {
  596. reg = &state->stack[i].spilled_ptr;
  597. t = reg->type;
  598. verbose(env, "=%s", reg_type_str[t]);
  599. if (t == SCALAR_VALUE && reg->precise)
  600. verbose(env, "P");
  601. if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
  602. verbose(env, "%lld", reg->var_off.value + reg->off);
  603. } else {
  604. verbose(env, "=%s", types_buf);
  605. }
  606. }
  607. if (state->acquired_refs && state->refs[0].id) {
  608. verbose(env, " refs=%d", state->refs[0].id);
  609. for (i = 1; i < state->acquired_refs; i++)
  610. if (state->refs[i].id)
  611. verbose(env, ",%d", state->refs[i].id);
  612. }
  613. verbose(env, "\n");
  614. }
  615. #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
  616. static int copy_##NAME##_state(struct bpf_func_state *dst, \
  617. const struct bpf_func_state *src) \
  618. { \
  619. if (!src->FIELD) \
  620. return 0; \
  621. if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
  622. /* internal bug, make state invalid to reject the program */ \
  623. memset(dst, 0, sizeof(*dst)); \
  624. return -EFAULT; \
  625. } \
  626. memcpy(dst->FIELD, src->FIELD, \
  627. sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
  628. return 0; \
  629. }
  630. /* copy_reference_state() */
  631. COPY_STATE_FN(reference, acquired_refs, refs, 1)
  632. /* copy_stack_state() */
  633. COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
  634. #undef COPY_STATE_FN
  635. #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
  636. static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
  637. bool copy_old) \
  638. { \
  639. u32 old_size = state->COUNT; \
  640. struct bpf_##NAME##_state *new_##FIELD; \
  641. int slot = size / SIZE; \
  642. \
  643. if (size <= old_size || !size) { \
  644. if (copy_old) \
  645. return 0; \
  646. state->COUNT = slot * SIZE; \
  647. if (!size && old_size) { \
  648. kfree(state->FIELD); \
  649. state->FIELD = NULL; \
  650. } \
  651. return 0; \
  652. } \
  653. new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
  654. GFP_KERNEL); \
  655. if (!new_##FIELD) \
  656. return -ENOMEM; \
  657. if (copy_old) { \
  658. if (state->FIELD) \
  659. memcpy(new_##FIELD, state->FIELD, \
  660. sizeof(*new_##FIELD) * (old_size / SIZE)); \
  661. memset(new_##FIELD + old_size / SIZE, 0, \
  662. sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
  663. } \
  664. state->COUNT = slot * SIZE; \
  665. kfree(state->FIELD); \
  666. state->FIELD = new_##FIELD; \
  667. return 0; \
  668. }
  669. /* realloc_reference_state() */
  670. REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
  671. /* realloc_stack_state() */
  672. REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
  673. #undef REALLOC_STATE_FN
  674. /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
  675. * make it consume minimal amount of memory. check_stack_write() access from
  676. * the program calls into realloc_func_state() to grow the stack size.
  677. * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
  678. * which realloc_stack_state() copies over. It points to previous
  679. * bpf_verifier_state which is never reallocated.
  680. */
  681. static int realloc_func_state(struct bpf_func_state *state, int stack_size,
  682. int refs_size, bool copy_old)
  683. {
  684. int err = realloc_reference_state(state, refs_size, copy_old);
  685. if (err)
  686. return err;
  687. return realloc_stack_state(state, stack_size, copy_old);
  688. }
  689. /* Acquire a pointer id from the env and update the state->refs to include
  690. * this new pointer reference.
  691. * On success, returns a valid pointer id to associate with the register
  692. * On failure, returns a negative errno.
  693. */
  694. static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
  695. {
  696. struct bpf_func_state *state = cur_func(env);
  697. int new_ofs = state->acquired_refs;
  698. int id, err;
  699. err = realloc_reference_state(state, state->acquired_refs + 1, true);
  700. if (err)
  701. return err;
  702. id = ++env->id_gen;
  703. state->refs[new_ofs].id = id;
  704. state->refs[new_ofs].insn_idx = insn_idx;
  705. return id;
  706. }
  707. /* release function corresponding to acquire_reference_state(). Idempotent. */
  708. static int release_reference_state(struct bpf_func_state *state, int ptr_id)
  709. {
  710. int i, last_idx;
  711. last_idx = state->acquired_refs - 1;
  712. for (i = 0; i < state->acquired_refs; i++) {
  713. if (state->refs[i].id == ptr_id) {
  714. if (last_idx && i != last_idx)
  715. memcpy(&state->refs[i], &state->refs[last_idx],
  716. sizeof(*state->refs));
  717. memset(&state->refs[last_idx], 0, sizeof(*state->refs));
  718. state->acquired_refs--;
  719. return 0;
  720. }
  721. }
  722. return -EINVAL;
  723. }
  724. static int transfer_reference_state(struct bpf_func_state *dst,
  725. struct bpf_func_state *src)
  726. {
  727. int err = realloc_reference_state(dst, src->acquired_refs, false);
  728. if (err)
  729. return err;
  730. err = copy_reference_state(dst, src);
  731. if (err)
  732. return err;
  733. return 0;
  734. }
  735. static void free_func_state(struct bpf_func_state *state)
  736. {
  737. if (!state)
  738. return;
  739. kfree(state->refs);
  740. kfree(state->stack);
  741. kfree(state);
  742. }
  743. static void clear_jmp_history(struct bpf_verifier_state *state)
  744. {
  745. kfree(state->jmp_history);
  746. state->jmp_history = NULL;
  747. state->jmp_history_cnt = 0;
  748. }
  749. static void free_verifier_state(struct bpf_verifier_state *state,
  750. bool free_self)
  751. {
  752. int i;
  753. for (i = 0; i <= state->curframe; i++) {
  754. free_func_state(state->frame[i]);
  755. state->frame[i] = NULL;
  756. }
  757. clear_jmp_history(state);
  758. if (free_self)
  759. kfree(state);
  760. }
  761. /* copy verifier state from src to dst growing dst stack space
  762. * when necessary to accommodate larger src stack
  763. */
  764. static int copy_func_state(struct bpf_func_state *dst,
  765. const struct bpf_func_state *src)
  766. {
  767. int err;
  768. err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
  769. false);
  770. if (err)
  771. return err;
  772. memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
  773. err = copy_reference_state(dst, src);
  774. if (err)
  775. return err;
  776. return copy_stack_state(dst, src);
  777. }
  778. static int copy_verifier_state(struct bpf_verifier_state *dst_state,
  779. const struct bpf_verifier_state *src)
  780. {
  781. struct bpf_func_state *dst;
  782. u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
  783. int i, err;
  784. if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
  785. kfree(dst_state->jmp_history);
  786. dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
  787. if (!dst_state->jmp_history)
  788. return -ENOMEM;
  789. }
  790. memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
  791. dst_state->jmp_history_cnt = src->jmp_history_cnt;
  792. /* if dst has more stack frames then src frame, free them */
  793. for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
  794. free_func_state(dst_state->frame[i]);
  795. dst_state->frame[i] = NULL;
  796. }
  797. dst_state->speculative = src->speculative;
  798. dst_state->curframe = src->curframe;
  799. dst_state->active_spin_lock = src->active_spin_lock;
  800. dst_state->branches = src->branches;
  801. dst_state->parent = src->parent;
  802. dst_state->first_insn_idx = src->first_insn_idx;
  803. dst_state->last_insn_idx = src->last_insn_idx;
  804. for (i = 0; i <= src->curframe; i++) {
  805. dst = dst_state->frame[i];
  806. if (!dst) {
  807. dst = kzalloc(sizeof(*dst), GFP_KERNEL);
  808. if (!dst)
  809. return -ENOMEM;
  810. dst_state->frame[i] = dst;
  811. }
  812. err = copy_func_state(dst, src->frame[i]);
  813. if (err)
  814. return err;
  815. }
  816. return 0;
  817. }
  818. static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
  819. {
  820. while (st) {
  821. u32 br = --st->branches;
  822. /* WARN_ON(br > 1) technically makes sense here,
  823. * but see comment in push_stack(), hence:
  824. */
  825. WARN_ONCE((int)br < 0,
  826. "BUG update_branch_counts:branches_to_explore=%d\n",
  827. br);
  828. if (br)
  829. break;
  830. st = st->parent;
  831. }
  832. }
  833. static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
  834. int *insn_idx, bool pop_log)
  835. {
  836. struct bpf_verifier_state *cur = env->cur_state;
  837. struct bpf_verifier_stack_elem *elem, *head = env->head;
  838. int err;
  839. if (env->head == NULL)
  840. return -ENOENT;
  841. if (cur) {
  842. err = copy_verifier_state(cur, &head->st);
  843. if (err)
  844. return err;
  845. }
  846. if (pop_log)
  847. bpf_vlog_reset(&env->log, head->log_pos);
  848. if (insn_idx)
  849. *insn_idx = head->insn_idx;
  850. if (prev_insn_idx)
  851. *prev_insn_idx = head->prev_insn_idx;
  852. elem = head->next;
  853. free_verifier_state(&head->st, false);
  854. kfree(head);
  855. env->head = elem;
  856. env->stack_size--;
  857. return 0;
  858. }
  859. static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
  860. int insn_idx, int prev_insn_idx,
  861. bool speculative)
  862. {
  863. struct bpf_verifier_state *cur = env->cur_state;
  864. struct bpf_verifier_stack_elem *elem;
  865. int err;
  866. elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
  867. if (!elem)
  868. goto err;
  869. elem->insn_idx = insn_idx;
  870. elem->prev_insn_idx = prev_insn_idx;
  871. elem->next = env->head;
  872. elem->log_pos = env->log.len_used;
  873. env->head = elem;
  874. env->stack_size++;
  875. err = copy_verifier_state(&elem->st, cur);
  876. if (err)
  877. goto err;
  878. elem->st.speculative |= speculative;
  879. if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
  880. verbose(env, "The sequence of %d jumps is too complex.\n",
  881. env->stack_size);
  882. goto err;
  883. }
  884. if (elem->st.parent) {
  885. ++elem->st.parent->branches;
  886. /* WARN_ON(branches > 2) technically makes sense here,
  887. * but
  888. * 1. speculative states will bump 'branches' for non-branch
  889. * instructions
  890. * 2. is_state_visited() heuristics may decide not to create
  891. * a new state for a sequence of branches and all such current
  892. * and cloned states will be pointing to a single parent state
  893. * which might have large 'branches' count.
  894. */
  895. }
  896. return &elem->st;
  897. err:
  898. free_verifier_state(env->cur_state, true);
  899. env->cur_state = NULL;
  900. /* pop all elements and return */
  901. while (!pop_stack(env, NULL, NULL, false));
  902. return NULL;
  903. }
  904. #define CALLER_SAVED_REGS 6
  905. static const int caller_saved[CALLER_SAVED_REGS] = {
  906. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  907. };
  908. static void __mark_reg_not_init(const struct bpf_verifier_env *env,
  909. struct bpf_reg_state *reg);
  910. /* This helper doesn't clear reg->id */
  911. static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
  912. {
  913. reg->var_off = tnum_const(imm);
  914. reg->smin_value = (s64)imm;
  915. reg->smax_value = (s64)imm;
  916. reg->umin_value = imm;
  917. reg->umax_value = imm;
  918. reg->s32_min_value = (s32)imm;
  919. reg->s32_max_value = (s32)imm;
  920. reg->u32_min_value = (u32)imm;
  921. reg->u32_max_value = (u32)imm;
  922. }
  923. /* Mark the unknown part of a register (variable offset or scalar value) as
  924. * known to have the value @imm.
  925. */
  926. static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
  927. {
  928. /* Clear id, off, and union(map_ptr, range) */
  929. memset(((u8 *)reg) + sizeof(reg->type), 0,
  930. offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
  931. ___mark_reg_known(reg, imm);
  932. }
  933. static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
  934. {
  935. reg->var_off = tnum_const_subreg(reg->var_off, imm);
  936. reg->s32_min_value = (s32)imm;
  937. reg->s32_max_value = (s32)imm;
  938. reg->u32_min_value = (u32)imm;
  939. reg->u32_max_value = (u32)imm;
  940. }
  941. /* Mark the 'variable offset' part of a register as zero. This should be
  942. * used only on registers holding a pointer type.
  943. */
  944. static void __mark_reg_known_zero(struct bpf_reg_state *reg)
  945. {
  946. __mark_reg_known(reg, 0);
  947. }
  948. static void __mark_reg_const_zero(struct bpf_reg_state *reg)
  949. {
  950. __mark_reg_known(reg, 0);
  951. reg->type = SCALAR_VALUE;
  952. }
  953. static void mark_reg_known_zero(struct bpf_verifier_env *env,
  954. struct bpf_reg_state *regs, u32 regno)
  955. {
  956. if (WARN_ON(regno >= MAX_BPF_REG)) {
  957. verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
  958. /* Something bad happened, let's kill all regs */
  959. for (regno = 0; regno < MAX_BPF_REG; regno++)
  960. __mark_reg_not_init(env, regs + regno);
  961. return;
  962. }
  963. __mark_reg_known_zero(regs + regno);
  964. }
  965. static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
  966. {
  967. return type_is_pkt_pointer(reg->type);
  968. }
  969. static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
  970. {
  971. return reg_is_pkt_pointer(reg) ||
  972. reg->type == PTR_TO_PACKET_END;
  973. }
  974. /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
  975. static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
  976. enum bpf_reg_type which)
  977. {
  978. /* The register can already have a range from prior markings.
  979. * This is fine as long as it hasn't been advanced from its
  980. * origin.
  981. */
  982. return reg->type == which &&
  983. reg->id == 0 &&
  984. reg->off == 0 &&
  985. tnum_equals_const(reg->var_off, 0);
  986. }
  987. /* Reset the min/max bounds of a register */
  988. static void __mark_reg_unbounded(struct bpf_reg_state *reg)
  989. {
  990. reg->smin_value = S64_MIN;
  991. reg->smax_value = S64_MAX;
  992. reg->umin_value = 0;
  993. reg->umax_value = U64_MAX;
  994. reg->s32_min_value = S32_MIN;
  995. reg->s32_max_value = S32_MAX;
  996. reg->u32_min_value = 0;
  997. reg->u32_max_value = U32_MAX;
  998. }
  999. static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
  1000. {
  1001. reg->smin_value = S64_MIN;
  1002. reg->smax_value = S64_MAX;
  1003. reg->umin_value = 0;
  1004. reg->umax_value = U64_MAX;
  1005. }
  1006. static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
  1007. {
  1008. reg->s32_min_value = S32_MIN;
  1009. reg->s32_max_value = S32_MAX;
  1010. reg->u32_min_value = 0;
  1011. reg->u32_max_value = U32_MAX;
  1012. }
  1013. static void __update_reg32_bounds(struct bpf_reg_state *reg)
  1014. {
  1015. struct tnum var32_off = tnum_subreg(reg->var_off);
  1016. /* min signed is max(sign bit) | min(other bits) */
  1017. reg->s32_min_value = max_t(s32, reg->s32_min_value,
  1018. var32_off.value | (var32_off.mask & S32_MIN));
  1019. /* max signed is min(sign bit) | max(other bits) */
  1020. reg->s32_max_value = min_t(s32, reg->s32_max_value,
  1021. var32_off.value | (var32_off.mask & S32_MAX));
  1022. reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
  1023. reg->u32_max_value = min(reg->u32_max_value,
  1024. (u32)(var32_off.value | var32_off.mask));
  1025. }
  1026. static void __update_reg64_bounds(struct bpf_reg_state *reg)
  1027. {
  1028. /* min signed is max(sign bit) | min(other bits) */
  1029. reg->smin_value = max_t(s64, reg->smin_value,
  1030. reg->var_off.value | (reg->var_off.mask & S64_MIN));
  1031. /* max signed is min(sign bit) | max(other bits) */
  1032. reg->smax_value = min_t(s64, reg->smax_value,
  1033. reg->var_off.value | (reg->var_off.mask & S64_MAX));
  1034. reg->umin_value = max(reg->umin_value, reg->var_off.value);
  1035. reg->umax_value = min(reg->umax_value,
  1036. reg->var_off.value | reg->var_off.mask);
  1037. }
  1038. static void __update_reg_bounds(struct bpf_reg_state *reg)
  1039. {
  1040. __update_reg32_bounds(reg);
  1041. __update_reg64_bounds(reg);
  1042. }
  1043. /* Uses signed min/max values to inform unsigned, and vice-versa */
  1044. static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
  1045. {
  1046. /* Learn sign from signed bounds.
  1047. * If we cannot cross the sign boundary, then signed and unsigned bounds
  1048. * are the same, so combine. This works even in the negative case, e.g.
  1049. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
  1050. */
  1051. if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
  1052. reg->s32_min_value = reg->u32_min_value =
  1053. max_t(u32, reg->s32_min_value, reg->u32_min_value);
  1054. reg->s32_max_value = reg->u32_max_value =
  1055. min_t(u32, reg->s32_max_value, reg->u32_max_value);
  1056. return;
  1057. }
  1058. /* Learn sign from unsigned bounds. Signed bounds cross the sign
  1059. * boundary, so we must be careful.
  1060. */
  1061. if ((s32)reg->u32_max_value >= 0) {
  1062. /* Positive. We can't learn anything from the smin, but smax
  1063. * is positive, hence safe.
  1064. */
  1065. reg->s32_min_value = reg->u32_min_value;
  1066. reg->s32_max_value = reg->u32_max_value =
  1067. min_t(u32, reg->s32_max_value, reg->u32_max_value);
  1068. } else if ((s32)reg->u32_min_value < 0) {
  1069. /* Negative. We can't learn anything from the smax, but smin
  1070. * is negative, hence safe.
  1071. */
  1072. reg->s32_min_value = reg->u32_min_value =
  1073. max_t(u32, reg->s32_min_value, reg->u32_min_value);
  1074. reg->s32_max_value = reg->u32_max_value;
  1075. }
  1076. }
  1077. static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
  1078. {
  1079. /* Learn sign from signed bounds.
  1080. * If we cannot cross the sign boundary, then signed and unsigned bounds
  1081. * are the same, so combine. This works even in the negative case, e.g.
  1082. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
  1083. */
  1084. if (reg->smin_value >= 0 || reg->smax_value < 0) {
  1085. reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
  1086. reg->umin_value);
  1087. reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
  1088. reg->umax_value);
  1089. return;
  1090. }
  1091. /* Learn sign from unsigned bounds. Signed bounds cross the sign
  1092. * boundary, so we must be careful.
  1093. */
  1094. if ((s64)reg->umax_value >= 0) {
  1095. /* Positive. We can't learn anything from the smin, but smax
  1096. * is positive, hence safe.
  1097. */
  1098. reg->smin_value = reg->umin_value;
  1099. reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
  1100. reg->umax_value);
  1101. } else if ((s64)reg->umin_value < 0) {
  1102. /* Negative. We can't learn anything from the smax, but smin
  1103. * is negative, hence safe.
  1104. */
  1105. reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
  1106. reg->umin_value);
  1107. reg->smax_value = reg->umax_value;
  1108. }
  1109. }
  1110. static void __reg_deduce_bounds(struct bpf_reg_state *reg)
  1111. {
  1112. __reg32_deduce_bounds(reg);
  1113. __reg64_deduce_bounds(reg);
  1114. }
  1115. /* Attempts to improve var_off based on unsigned min/max information */
  1116. static void __reg_bound_offset(struct bpf_reg_state *reg)
  1117. {
  1118. struct tnum var64_off = tnum_intersect(reg->var_off,
  1119. tnum_range(reg->umin_value,
  1120. reg->umax_value));
  1121. struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
  1122. tnum_range(reg->u32_min_value,
  1123. reg->u32_max_value));
  1124. reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
  1125. }
  1126. static bool __reg32_bound_s64(s32 a)
  1127. {
  1128. return a >= 0 && a <= S32_MAX;
  1129. }
  1130. static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
  1131. {
  1132. reg->umin_value = reg->u32_min_value;
  1133. reg->umax_value = reg->u32_max_value;
  1134. /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
  1135. * be positive otherwise set to worse case bounds and refine later
  1136. * from tnum.
  1137. */
  1138. if (__reg32_bound_s64(reg->s32_min_value) &&
  1139. __reg32_bound_s64(reg->s32_max_value)) {
  1140. reg->smin_value = reg->s32_min_value;
  1141. reg->smax_value = reg->s32_max_value;
  1142. } else {
  1143. reg->smin_value = 0;
  1144. reg->smax_value = U32_MAX;
  1145. }
  1146. }
  1147. static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
  1148. {
  1149. /* special case when 64-bit register has upper 32-bit register
  1150. * zeroed. Typically happens after zext or <<32, >>32 sequence
  1151. * allowing us to use 32-bit bounds directly,
  1152. */
  1153. if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
  1154. __reg_assign_32_into_64(reg);
  1155. } else {
  1156. /* Otherwise the best we can do is push lower 32bit known and
  1157. * unknown bits into register (var_off set from jmp logic)
  1158. * then learn as much as possible from the 64-bit tnum
  1159. * known and unknown bits. The previous smin/smax bounds are
  1160. * invalid here because of jmp32 compare so mark them unknown
  1161. * so they do not impact tnum bounds calculation.
  1162. */
  1163. __mark_reg64_unbounded(reg);
  1164. __update_reg_bounds(reg);
  1165. }
  1166. /* Intersecting with the old var_off might have improved our bounds
  1167. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  1168. * then new var_off is (0; 0x7f...fc) which improves our umax.
  1169. */
  1170. __reg_deduce_bounds(reg);
  1171. __reg_bound_offset(reg);
  1172. __update_reg_bounds(reg);
  1173. }
  1174. static bool __reg64_bound_s32(s64 a)
  1175. {
  1176. return a >= S32_MIN && a <= S32_MAX;
  1177. }
  1178. static bool __reg64_bound_u32(u64 a)
  1179. {
  1180. return a >= U32_MIN && a <= U32_MAX;
  1181. }
  1182. static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
  1183. {
  1184. __mark_reg32_unbounded(reg);
  1185. if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
  1186. reg->s32_min_value = (s32)reg->smin_value;
  1187. reg->s32_max_value = (s32)reg->smax_value;
  1188. }
  1189. if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
  1190. reg->u32_min_value = (u32)reg->umin_value;
  1191. reg->u32_max_value = (u32)reg->umax_value;
  1192. }
  1193. /* Intersecting with the old var_off might have improved our bounds
  1194. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  1195. * then new var_off is (0; 0x7f...fc) which improves our umax.
  1196. */
  1197. __reg_deduce_bounds(reg);
  1198. __reg_bound_offset(reg);
  1199. __update_reg_bounds(reg);
  1200. }
  1201. /* Mark a register as having a completely unknown (scalar) value. */
  1202. static void __mark_reg_unknown(const struct bpf_verifier_env *env,
  1203. struct bpf_reg_state *reg)
  1204. {
  1205. /*
  1206. * Clear type, id, off, and union(map_ptr, range) and
  1207. * padding between 'type' and union
  1208. */
  1209. memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
  1210. reg->type = SCALAR_VALUE;
  1211. reg->var_off = tnum_unknown;
  1212. reg->frameno = 0;
  1213. reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
  1214. __mark_reg_unbounded(reg);
  1215. }
  1216. static void mark_reg_unknown(struct bpf_verifier_env *env,
  1217. struct bpf_reg_state *regs, u32 regno)
  1218. {
  1219. if (WARN_ON(regno >= MAX_BPF_REG)) {
  1220. verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
  1221. /* Something bad happened, let's kill all regs except FP */
  1222. for (regno = 0; regno < BPF_REG_FP; regno++)
  1223. __mark_reg_not_init(env, regs + regno);
  1224. return;
  1225. }
  1226. __mark_reg_unknown(env, regs + regno);
  1227. }
  1228. static void __mark_reg_not_init(const struct bpf_verifier_env *env,
  1229. struct bpf_reg_state *reg)
  1230. {
  1231. __mark_reg_unknown(env, reg);
  1232. reg->type = NOT_INIT;
  1233. }
  1234. static void mark_reg_not_init(struct bpf_verifier_env *env,
  1235. struct bpf_reg_state *regs, u32 regno)
  1236. {
  1237. if (WARN_ON(regno >= MAX_BPF_REG)) {
  1238. verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
  1239. /* Something bad happened, let's kill all regs except FP */
  1240. for (regno = 0; regno < BPF_REG_FP; regno++)
  1241. __mark_reg_not_init(env, regs + regno);
  1242. return;
  1243. }
  1244. __mark_reg_not_init(env, regs + regno);
  1245. }
  1246. static void mark_btf_ld_reg(struct bpf_verifier_env *env,
  1247. struct bpf_reg_state *regs, u32 regno,
  1248. enum bpf_reg_type reg_type, u32 btf_id)
  1249. {
  1250. if (reg_type == SCALAR_VALUE) {
  1251. mark_reg_unknown(env, regs, regno);
  1252. return;
  1253. }
  1254. mark_reg_known_zero(env, regs, regno);
  1255. regs[regno].type = PTR_TO_BTF_ID;
  1256. regs[regno].btf_id = btf_id;
  1257. }
  1258. #define DEF_NOT_SUBREG (0)
  1259. static void init_reg_state(struct bpf_verifier_env *env,
  1260. struct bpf_func_state *state)
  1261. {
  1262. struct bpf_reg_state *regs = state->regs;
  1263. int i;
  1264. for (i = 0; i < MAX_BPF_REG; i++) {
  1265. mark_reg_not_init(env, regs, i);
  1266. regs[i].live = REG_LIVE_NONE;
  1267. regs[i].parent = NULL;
  1268. regs[i].subreg_def = DEF_NOT_SUBREG;
  1269. }
  1270. /* frame pointer */
  1271. regs[BPF_REG_FP].type = PTR_TO_STACK;
  1272. mark_reg_known_zero(env, regs, BPF_REG_FP);
  1273. regs[BPF_REG_FP].frameno = state->frameno;
  1274. }
  1275. #define BPF_MAIN_FUNC (-1)
  1276. static void init_func_state(struct bpf_verifier_env *env,
  1277. struct bpf_func_state *state,
  1278. int callsite, int frameno, int subprogno)
  1279. {
  1280. state->callsite = callsite;
  1281. state->frameno = frameno;
  1282. state->subprogno = subprogno;
  1283. init_reg_state(env, state);
  1284. }
  1285. enum reg_arg_type {
  1286. SRC_OP, /* register is used as source operand */
  1287. DST_OP, /* register is used as destination operand */
  1288. DST_OP_NO_MARK /* same as above, check only, don't mark */
  1289. };
  1290. static int cmp_subprogs(const void *a, const void *b)
  1291. {
  1292. return ((struct bpf_subprog_info *)a)->start -
  1293. ((struct bpf_subprog_info *)b)->start;
  1294. }
  1295. static int find_subprog(struct bpf_verifier_env *env, int off)
  1296. {
  1297. struct bpf_subprog_info *p;
  1298. p = bsearch(&off, env->subprog_info, env->subprog_cnt,
  1299. sizeof(env->subprog_info[0]), cmp_subprogs);
  1300. if (!p)
  1301. return -ENOENT;
  1302. return p - env->subprog_info;
  1303. }
  1304. static int add_subprog(struct bpf_verifier_env *env, int off)
  1305. {
  1306. int insn_cnt = env->prog->len;
  1307. int ret;
  1308. if (off >= insn_cnt || off < 0) {
  1309. verbose(env, "call to invalid destination\n");
  1310. return -EINVAL;
  1311. }
  1312. ret = find_subprog(env, off);
  1313. if (ret >= 0)
  1314. return 0;
  1315. if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
  1316. verbose(env, "too many subprograms\n");
  1317. return -E2BIG;
  1318. }
  1319. env->subprog_info[env->subprog_cnt++].start = off;
  1320. sort(env->subprog_info, env->subprog_cnt,
  1321. sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
  1322. return 0;
  1323. }
  1324. static int check_subprogs(struct bpf_verifier_env *env)
  1325. {
  1326. int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
  1327. struct bpf_subprog_info *subprog = env->subprog_info;
  1328. struct bpf_insn *insn = env->prog->insnsi;
  1329. int insn_cnt = env->prog->len;
  1330. /* Add entry function. */
  1331. ret = add_subprog(env, 0);
  1332. if (ret < 0)
  1333. return ret;
  1334. /* determine subprog starts. The end is one before the next starts */
  1335. for (i = 0; i < insn_cnt; i++) {
  1336. if (insn[i].code != (BPF_JMP | BPF_CALL))
  1337. continue;
  1338. if (insn[i].src_reg != BPF_PSEUDO_CALL)
  1339. continue;
  1340. if (!env->bpf_capable) {
  1341. verbose(env,
  1342. "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
  1343. return -EPERM;
  1344. }
  1345. ret = add_subprog(env, i + insn[i].imm + 1);
  1346. if (ret < 0)
  1347. return ret;
  1348. }
  1349. /* Add a fake 'exit' subprog which could simplify subprog iteration
  1350. * logic. 'subprog_cnt' should not be increased.
  1351. */
  1352. subprog[env->subprog_cnt].start = insn_cnt;
  1353. if (env->log.level & BPF_LOG_LEVEL2)
  1354. for (i = 0; i < env->subprog_cnt; i++)
  1355. verbose(env, "func#%d @%d\n", i, subprog[i].start);
  1356. /* now check that all jumps are within the same subprog */
  1357. subprog_start = subprog[cur_subprog].start;
  1358. subprog_end = subprog[cur_subprog + 1].start;
  1359. for (i = 0; i < insn_cnt; i++) {
  1360. u8 code = insn[i].code;
  1361. if (code == (BPF_JMP | BPF_CALL) &&
  1362. insn[i].imm == BPF_FUNC_tail_call &&
  1363. insn[i].src_reg != BPF_PSEUDO_CALL)
  1364. subprog[cur_subprog].has_tail_call = true;
  1365. if (BPF_CLASS(code) == BPF_LD &&
  1366. (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
  1367. subprog[cur_subprog].has_ld_abs = true;
  1368. if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
  1369. goto next;
  1370. if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
  1371. goto next;
  1372. off = i + insn[i].off + 1;
  1373. if (off < subprog_start || off >= subprog_end) {
  1374. verbose(env, "jump out of range from insn %d to %d\n", i, off);
  1375. return -EINVAL;
  1376. }
  1377. next:
  1378. if (i == subprog_end - 1) {
  1379. /* to avoid fall-through from one subprog into another
  1380. * the last insn of the subprog should be either exit
  1381. * or unconditional jump back
  1382. */
  1383. if (code != (BPF_JMP | BPF_EXIT) &&
  1384. code != (BPF_JMP | BPF_JA)) {
  1385. verbose(env, "last insn is not an exit or jmp\n");
  1386. return -EINVAL;
  1387. }
  1388. subprog_start = subprog_end;
  1389. cur_subprog++;
  1390. if (cur_subprog < env->subprog_cnt)
  1391. subprog_end = subprog[cur_subprog + 1].start;
  1392. }
  1393. }
  1394. return 0;
  1395. }
  1396. /* Parentage chain of this register (or stack slot) should take care of all
  1397. * issues like callee-saved registers, stack slot allocation time, etc.
  1398. */
  1399. static int mark_reg_read(struct bpf_verifier_env *env,
  1400. const struct bpf_reg_state *state,
  1401. struct bpf_reg_state *parent, u8 flag)
  1402. {
  1403. bool writes = parent == state->parent; /* Observe write marks */
  1404. int cnt = 0;
  1405. while (parent) {
  1406. /* if read wasn't screened by an earlier write ... */
  1407. if (writes && state->live & REG_LIVE_WRITTEN)
  1408. break;
  1409. if (parent->live & REG_LIVE_DONE) {
  1410. verbose(env, "verifier BUG type %s var_off %lld off %d\n",
  1411. reg_type_str[parent->type],
  1412. parent->var_off.value, parent->off);
  1413. return -EFAULT;
  1414. }
  1415. /* The first condition is more likely to be true than the
  1416. * second, checked it first.
  1417. */
  1418. if ((parent->live & REG_LIVE_READ) == flag ||
  1419. parent->live & REG_LIVE_READ64)
  1420. /* The parentage chain never changes and
  1421. * this parent was already marked as LIVE_READ.
  1422. * There is no need to keep walking the chain again and
  1423. * keep re-marking all parents as LIVE_READ.
  1424. * This case happens when the same register is read
  1425. * multiple times without writes into it in-between.
  1426. * Also, if parent has the stronger REG_LIVE_READ64 set,
  1427. * then no need to set the weak REG_LIVE_READ32.
  1428. */
  1429. break;
  1430. /* ... then we depend on parent's value */
  1431. parent->live |= flag;
  1432. /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
  1433. if (flag == REG_LIVE_READ64)
  1434. parent->live &= ~REG_LIVE_READ32;
  1435. state = parent;
  1436. parent = state->parent;
  1437. writes = true;
  1438. cnt++;
  1439. }
  1440. if (env->longest_mark_read_walk < cnt)
  1441. env->longest_mark_read_walk = cnt;
  1442. return 0;
  1443. }
  1444. /* This function is supposed to be used by the following 32-bit optimization
  1445. * code only. It returns TRUE if the source or destination register operates
  1446. * on 64-bit, otherwise return FALSE.
  1447. */
  1448. static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
  1449. u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
  1450. {
  1451. u8 code, class, op;
  1452. code = insn->code;
  1453. class = BPF_CLASS(code);
  1454. op = BPF_OP(code);
  1455. if (class == BPF_JMP) {
  1456. /* BPF_EXIT for "main" will reach here. Return TRUE
  1457. * conservatively.
  1458. */
  1459. if (op == BPF_EXIT)
  1460. return true;
  1461. if (op == BPF_CALL) {
  1462. /* BPF to BPF call will reach here because of marking
  1463. * caller saved clobber with DST_OP_NO_MARK for which we
  1464. * don't care the register def because they are anyway
  1465. * marked as NOT_INIT already.
  1466. */
  1467. if (insn->src_reg == BPF_PSEUDO_CALL)
  1468. return false;
  1469. /* Helper call will reach here because of arg type
  1470. * check, conservatively return TRUE.
  1471. */
  1472. if (t == SRC_OP)
  1473. return true;
  1474. return false;
  1475. }
  1476. }
  1477. if (class == BPF_ALU64 || class == BPF_JMP ||
  1478. /* BPF_END always use BPF_ALU class. */
  1479. (class == BPF_ALU && op == BPF_END && insn->imm == 64))
  1480. return true;
  1481. if (class == BPF_ALU || class == BPF_JMP32)
  1482. return false;
  1483. if (class == BPF_LDX) {
  1484. if (t != SRC_OP)
  1485. return BPF_SIZE(code) == BPF_DW;
  1486. /* LDX source must be ptr. */
  1487. return true;
  1488. }
  1489. if (class == BPF_STX) {
  1490. if (reg->type != SCALAR_VALUE)
  1491. return true;
  1492. return BPF_SIZE(code) == BPF_DW;
  1493. }
  1494. if (class == BPF_LD) {
  1495. u8 mode = BPF_MODE(code);
  1496. /* LD_IMM64 */
  1497. if (mode == BPF_IMM)
  1498. return true;
  1499. /* Both LD_IND and LD_ABS return 32-bit data. */
  1500. if (t != SRC_OP)
  1501. return false;
  1502. /* Implicit ctx ptr. */
  1503. if (regno == BPF_REG_6)
  1504. return true;
  1505. /* Explicit source could be any width. */
  1506. return true;
  1507. }
  1508. if (class == BPF_ST)
  1509. /* The only source register for BPF_ST is a ptr. */
  1510. return true;
  1511. /* Conservatively return true at default. */
  1512. return true;
  1513. }
  1514. /* Return TRUE if INSN doesn't have explicit value define. */
  1515. static bool insn_no_def(struct bpf_insn *insn)
  1516. {
  1517. u8 class = BPF_CLASS(insn->code);
  1518. return (class == BPF_JMP || class == BPF_JMP32 ||
  1519. class == BPF_STX || class == BPF_ST);
  1520. }
  1521. /* Return TRUE if INSN has defined any 32-bit value explicitly. */
  1522. static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
  1523. {
  1524. if (insn_no_def(insn))
  1525. return false;
  1526. return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
  1527. }
  1528. static void mark_insn_zext(struct bpf_verifier_env *env,
  1529. struct bpf_reg_state *reg)
  1530. {
  1531. s32 def_idx = reg->subreg_def;
  1532. if (def_idx == DEF_NOT_SUBREG)
  1533. return;
  1534. env->insn_aux_data[def_idx - 1].zext_dst = true;
  1535. /* The dst will be zero extended, so won't be sub-register anymore. */
  1536. reg->subreg_def = DEF_NOT_SUBREG;
  1537. }
  1538. static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
  1539. enum reg_arg_type t)
  1540. {
  1541. struct bpf_verifier_state *vstate = env->cur_state;
  1542. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  1543. struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
  1544. struct bpf_reg_state *reg, *regs = state->regs;
  1545. bool rw64;
  1546. if (regno >= MAX_BPF_REG) {
  1547. verbose(env, "R%d is invalid\n", regno);
  1548. return -EINVAL;
  1549. }
  1550. reg = &regs[regno];
  1551. rw64 = is_reg64(env, insn, regno, reg, t);
  1552. if (t == SRC_OP) {
  1553. /* check whether register used as source operand can be read */
  1554. if (reg->type == NOT_INIT) {
  1555. verbose(env, "R%d !read_ok\n", regno);
  1556. return -EACCES;
  1557. }
  1558. /* We don't need to worry about FP liveness because it's read-only */
  1559. if (regno == BPF_REG_FP)
  1560. return 0;
  1561. if (rw64)
  1562. mark_insn_zext(env, reg);
  1563. return mark_reg_read(env, reg, reg->parent,
  1564. rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
  1565. } else {
  1566. /* check whether register used as dest operand can be written to */
  1567. if (regno == BPF_REG_FP) {
  1568. verbose(env, "frame pointer is read only\n");
  1569. return -EACCES;
  1570. }
  1571. reg->live |= REG_LIVE_WRITTEN;
  1572. reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
  1573. if (t == DST_OP)
  1574. mark_reg_unknown(env, regs, regno);
  1575. }
  1576. return 0;
  1577. }
  1578. /* for any branch, call, exit record the history of jmps in the given state */
  1579. static int push_jmp_history(struct bpf_verifier_env *env,
  1580. struct bpf_verifier_state *cur)
  1581. {
  1582. u32 cnt = cur->jmp_history_cnt;
  1583. struct bpf_idx_pair *p;
  1584. cnt++;
  1585. p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
  1586. if (!p)
  1587. return -ENOMEM;
  1588. p[cnt - 1].idx = env->insn_idx;
  1589. p[cnt - 1].prev_idx = env->prev_insn_idx;
  1590. cur->jmp_history = p;
  1591. cur->jmp_history_cnt = cnt;
  1592. return 0;
  1593. }
  1594. /* Backtrack one insn at a time. If idx is not at the top of recorded
  1595. * history then previous instruction came from straight line execution.
  1596. */
  1597. static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
  1598. u32 *history)
  1599. {
  1600. u32 cnt = *history;
  1601. if (cnt && st->jmp_history[cnt - 1].idx == i) {
  1602. i = st->jmp_history[cnt - 1].prev_idx;
  1603. (*history)--;
  1604. } else {
  1605. i--;
  1606. }
  1607. return i;
  1608. }
  1609. /* For given verifier state backtrack_insn() is called from the last insn to
  1610. * the first insn. Its purpose is to compute a bitmask of registers and
  1611. * stack slots that needs precision in the parent verifier state.
  1612. */
  1613. static int backtrack_insn(struct bpf_verifier_env *env, int idx,
  1614. u32 *reg_mask, u64 *stack_mask)
  1615. {
  1616. const struct bpf_insn_cbs cbs = {
  1617. .cb_print = verbose,
  1618. .private_data = env,
  1619. };
  1620. struct bpf_insn *insn = env->prog->insnsi + idx;
  1621. u8 class = BPF_CLASS(insn->code);
  1622. u8 opcode = BPF_OP(insn->code);
  1623. u8 mode = BPF_MODE(insn->code);
  1624. u32 dreg = 1u << insn->dst_reg;
  1625. u32 sreg = 1u << insn->src_reg;
  1626. u32 spi;
  1627. if (insn->code == 0)
  1628. return 0;
  1629. if (env->log.level & BPF_LOG_LEVEL) {
  1630. verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
  1631. verbose(env, "%d: ", idx);
  1632. print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
  1633. }
  1634. if (class == BPF_ALU || class == BPF_ALU64) {
  1635. if (!(*reg_mask & dreg))
  1636. return 0;
  1637. if (opcode == BPF_MOV) {
  1638. if (BPF_SRC(insn->code) == BPF_X) {
  1639. /* dreg = sreg
  1640. * dreg needs precision after this insn
  1641. * sreg needs precision before this insn
  1642. */
  1643. *reg_mask &= ~dreg;
  1644. *reg_mask |= sreg;
  1645. } else {
  1646. /* dreg = K
  1647. * dreg needs precision after this insn.
  1648. * Corresponding register is already marked
  1649. * as precise=true in this verifier state.
  1650. * No further markings in parent are necessary
  1651. */
  1652. *reg_mask &= ~dreg;
  1653. }
  1654. } else {
  1655. if (BPF_SRC(insn->code) == BPF_X) {
  1656. /* dreg += sreg
  1657. * both dreg and sreg need precision
  1658. * before this insn
  1659. */
  1660. *reg_mask |= sreg;
  1661. } /* else dreg += K
  1662. * dreg still needs precision before this insn
  1663. */
  1664. }
  1665. } else if (class == BPF_LDX) {
  1666. if (!(*reg_mask & dreg))
  1667. return 0;
  1668. *reg_mask &= ~dreg;
  1669. /* scalars can only be spilled into stack w/o losing precision.
  1670. * Load from any other memory can be zero extended.
  1671. * The desire to keep that precision is already indicated
  1672. * by 'precise' mark in corresponding register of this state.
  1673. * No further tracking necessary.
  1674. */
  1675. if (insn->src_reg != BPF_REG_FP)
  1676. return 0;
  1677. if (BPF_SIZE(insn->code) != BPF_DW)
  1678. return 0;
  1679. /* dreg = *(u64 *)[fp - off] was a fill from the stack.
  1680. * that [fp - off] slot contains scalar that needs to be
  1681. * tracked with precision
  1682. */
  1683. spi = (-insn->off - 1) / BPF_REG_SIZE;
  1684. if (spi >= 64) {
  1685. verbose(env, "BUG spi %d\n", spi);
  1686. WARN_ONCE(1, "verifier backtracking bug");
  1687. return -EFAULT;
  1688. }
  1689. *stack_mask |= 1ull << spi;
  1690. } else if (class == BPF_STX || class == BPF_ST) {
  1691. if (*reg_mask & dreg)
  1692. /* stx & st shouldn't be using _scalar_ dst_reg
  1693. * to access memory. It means backtracking
  1694. * encountered a case of pointer subtraction.
  1695. */
  1696. return -ENOTSUPP;
  1697. /* scalars can only be spilled into stack */
  1698. if (insn->dst_reg != BPF_REG_FP)
  1699. return 0;
  1700. if (BPF_SIZE(insn->code) != BPF_DW)
  1701. return 0;
  1702. spi = (-insn->off - 1) / BPF_REG_SIZE;
  1703. if (spi >= 64) {
  1704. verbose(env, "BUG spi %d\n", spi);
  1705. WARN_ONCE(1, "verifier backtracking bug");
  1706. return -EFAULT;
  1707. }
  1708. if (!(*stack_mask & (1ull << spi)))
  1709. return 0;
  1710. *stack_mask &= ~(1ull << spi);
  1711. if (class == BPF_STX)
  1712. *reg_mask |= sreg;
  1713. } else if (class == BPF_JMP || class == BPF_JMP32) {
  1714. if (opcode == BPF_CALL) {
  1715. if (insn->src_reg == BPF_PSEUDO_CALL)
  1716. return -ENOTSUPP;
  1717. /* regular helper call sets R0 */
  1718. *reg_mask &= ~1;
  1719. if (*reg_mask & 0x3f) {
  1720. /* if backtracing was looking for registers R1-R5
  1721. * they should have been found already.
  1722. */
  1723. verbose(env, "BUG regs %x\n", *reg_mask);
  1724. WARN_ONCE(1, "verifier backtracking bug");
  1725. return -EFAULT;
  1726. }
  1727. } else if (opcode == BPF_EXIT) {
  1728. return -ENOTSUPP;
  1729. }
  1730. } else if (class == BPF_LD) {
  1731. if (!(*reg_mask & dreg))
  1732. return 0;
  1733. *reg_mask &= ~dreg;
  1734. /* It's ld_imm64 or ld_abs or ld_ind.
  1735. * For ld_imm64 no further tracking of precision
  1736. * into parent is necessary
  1737. */
  1738. if (mode == BPF_IND || mode == BPF_ABS)
  1739. /* to be analyzed */
  1740. return -ENOTSUPP;
  1741. }
  1742. return 0;
  1743. }
  1744. /* the scalar precision tracking algorithm:
  1745. * . at the start all registers have precise=false.
  1746. * . scalar ranges are tracked as normal through alu and jmp insns.
  1747. * . once precise value of the scalar register is used in:
  1748. * . ptr + scalar alu
  1749. * . if (scalar cond K|scalar)
  1750. * . helper_call(.., scalar, ...) where ARG_CONST is expected
  1751. * backtrack through the verifier states and mark all registers and
  1752. * stack slots with spilled constants that these scalar regisers
  1753. * should be precise.
  1754. * . during state pruning two registers (or spilled stack slots)
  1755. * are equivalent if both are not precise.
  1756. *
  1757. * Note the verifier cannot simply walk register parentage chain,
  1758. * since many different registers and stack slots could have been
  1759. * used to compute single precise scalar.
  1760. *
  1761. * The approach of starting with precise=true for all registers and then
  1762. * backtrack to mark a register as not precise when the verifier detects
  1763. * that program doesn't care about specific value (e.g., when helper
  1764. * takes register as ARG_ANYTHING parameter) is not safe.
  1765. *
  1766. * It's ok to walk single parentage chain of the verifier states.
  1767. * It's possible that this backtracking will go all the way till 1st insn.
  1768. * All other branches will be explored for needing precision later.
  1769. *
  1770. * The backtracking needs to deal with cases like:
  1771. * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
  1772. * r9 -= r8
  1773. * r5 = r9
  1774. * if r5 > 0x79f goto pc+7
  1775. * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
  1776. * r5 += 1
  1777. * ...
  1778. * call bpf_perf_event_output#25
  1779. * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
  1780. *
  1781. * and this case:
  1782. * r6 = 1
  1783. * call foo // uses callee's r6 inside to compute r0
  1784. * r0 += r6
  1785. * if r0 == 0 goto
  1786. *
  1787. * to track above reg_mask/stack_mask needs to be independent for each frame.
  1788. *
  1789. * Also if parent's curframe > frame where backtracking started,
  1790. * the verifier need to mark registers in both frames, otherwise callees
  1791. * may incorrectly prune callers. This is similar to
  1792. * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
  1793. *
  1794. * For now backtracking falls back into conservative marking.
  1795. */
  1796. static void mark_all_scalars_precise(struct bpf_verifier_env *env,
  1797. struct bpf_verifier_state *st)
  1798. {
  1799. struct bpf_func_state *func;
  1800. struct bpf_reg_state *reg;
  1801. int i, j;
  1802. /* big hammer: mark all scalars precise in this path.
  1803. * pop_stack may still get !precise scalars.
  1804. */
  1805. for (; st; st = st->parent)
  1806. for (i = 0; i <= st->curframe; i++) {
  1807. func = st->frame[i];
  1808. for (j = 0; j < BPF_REG_FP; j++) {
  1809. reg = &func->regs[j];
  1810. if (reg->type != SCALAR_VALUE)
  1811. continue;
  1812. reg->precise = true;
  1813. }
  1814. for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
  1815. if (func->stack[j].slot_type[0] != STACK_SPILL)
  1816. continue;
  1817. reg = &func->stack[j].spilled_ptr;
  1818. if (reg->type != SCALAR_VALUE)
  1819. continue;
  1820. reg->precise = true;
  1821. }
  1822. }
  1823. }
  1824. static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
  1825. int spi)
  1826. {
  1827. struct bpf_verifier_state *st = env->cur_state;
  1828. int first_idx = st->first_insn_idx;
  1829. int last_idx = env->insn_idx;
  1830. struct bpf_func_state *func;
  1831. struct bpf_reg_state *reg;
  1832. u32 reg_mask = regno >= 0 ? 1u << regno : 0;
  1833. u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
  1834. bool skip_first = true;
  1835. bool new_marks = false;
  1836. int i, err;
  1837. if (!env->bpf_capable)
  1838. return 0;
  1839. func = st->frame[st->curframe];
  1840. if (regno >= 0) {
  1841. reg = &func->regs[regno];
  1842. if (reg->type != SCALAR_VALUE) {
  1843. WARN_ONCE(1, "backtracing misuse");
  1844. return -EFAULT;
  1845. }
  1846. if (!reg->precise)
  1847. new_marks = true;
  1848. else
  1849. reg_mask = 0;
  1850. reg->precise = true;
  1851. }
  1852. while (spi >= 0) {
  1853. if (func->stack[spi].slot_type[0] != STACK_SPILL) {
  1854. stack_mask = 0;
  1855. break;
  1856. }
  1857. reg = &func->stack[spi].spilled_ptr;
  1858. if (reg->type != SCALAR_VALUE) {
  1859. stack_mask = 0;
  1860. break;
  1861. }
  1862. if (!reg->precise)
  1863. new_marks = true;
  1864. else
  1865. stack_mask = 0;
  1866. reg->precise = true;
  1867. break;
  1868. }
  1869. if (!new_marks)
  1870. return 0;
  1871. if (!reg_mask && !stack_mask)
  1872. return 0;
  1873. for (;;) {
  1874. DECLARE_BITMAP(mask, 64);
  1875. u32 history = st->jmp_history_cnt;
  1876. if (env->log.level & BPF_LOG_LEVEL)
  1877. verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
  1878. for (i = last_idx;;) {
  1879. if (skip_first) {
  1880. err = 0;
  1881. skip_first = false;
  1882. } else {
  1883. err = backtrack_insn(env, i, &reg_mask, &stack_mask);
  1884. }
  1885. if (err == -ENOTSUPP) {
  1886. mark_all_scalars_precise(env, st);
  1887. return 0;
  1888. } else if (err) {
  1889. return err;
  1890. }
  1891. if (!reg_mask && !stack_mask)
  1892. /* Found assignment(s) into tracked register in this state.
  1893. * Since this state is already marked, just return.
  1894. * Nothing to be tracked further in the parent state.
  1895. */
  1896. return 0;
  1897. if (i == first_idx)
  1898. break;
  1899. i = get_prev_insn_idx(st, i, &history);
  1900. if (i >= env->prog->len) {
  1901. /* This can happen if backtracking reached insn 0
  1902. * and there are still reg_mask or stack_mask
  1903. * to backtrack.
  1904. * It means the backtracking missed the spot where
  1905. * particular register was initialized with a constant.
  1906. */
  1907. verbose(env, "BUG backtracking idx %d\n", i);
  1908. WARN_ONCE(1, "verifier backtracking bug");
  1909. return -EFAULT;
  1910. }
  1911. }
  1912. st = st->parent;
  1913. if (!st)
  1914. break;
  1915. new_marks = false;
  1916. func = st->frame[st->curframe];
  1917. bitmap_from_u64(mask, reg_mask);
  1918. for_each_set_bit(i, mask, 32) {
  1919. reg = &func->regs[i];
  1920. if (reg->type != SCALAR_VALUE) {
  1921. reg_mask &= ~(1u << i);
  1922. continue;
  1923. }
  1924. if (!reg->precise)
  1925. new_marks = true;
  1926. reg->precise = true;
  1927. }
  1928. bitmap_from_u64(mask, stack_mask);
  1929. for_each_set_bit(i, mask, 64) {
  1930. if (i >= func->allocated_stack / BPF_REG_SIZE) {
  1931. /* the sequence of instructions:
  1932. * 2: (bf) r3 = r10
  1933. * 3: (7b) *(u64 *)(r3 -8) = r0
  1934. * 4: (79) r4 = *(u64 *)(r10 -8)
  1935. * doesn't contain jmps. It's backtracked
  1936. * as a single block.
  1937. * During backtracking insn 3 is not recognized as
  1938. * stack access, so at the end of backtracking
  1939. * stack slot fp-8 is still marked in stack_mask.
  1940. * However the parent state may not have accessed
  1941. * fp-8 and it's "unallocated" stack space.
  1942. * In such case fallback to conservative.
  1943. */
  1944. mark_all_scalars_precise(env, st);
  1945. return 0;
  1946. }
  1947. if (func->stack[i].slot_type[0] != STACK_SPILL) {
  1948. stack_mask &= ~(1ull << i);
  1949. continue;
  1950. }
  1951. reg = &func->stack[i].spilled_ptr;
  1952. if (reg->type != SCALAR_VALUE) {
  1953. stack_mask &= ~(1ull << i);
  1954. continue;
  1955. }
  1956. if (!reg->precise)
  1957. new_marks = true;
  1958. reg->precise = true;
  1959. }
  1960. if (env->log.level & BPF_LOG_LEVEL) {
  1961. print_verifier_state(env, func);
  1962. verbose(env, "parent %s regs=%x stack=%llx marks\n",
  1963. new_marks ? "didn't have" : "already had",
  1964. reg_mask, stack_mask);
  1965. }
  1966. if (!reg_mask && !stack_mask)
  1967. break;
  1968. if (!new_marks)
  1969. break;
  1970. last_idx = st->last_insn_idx;
  1971. first_idx = st->first_insn_idx;
  1972. }
  1973. return 0;
  1974. }
  1975. static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
  1976. {
  1977. return __mark_chain_precision(env, regno, -1);
  1978. }
  1979. static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
  1980. {
  1981. return __mark_chain_precision(env, -1, spi);
  1982. }
  1983. static bool is_spillable_regtype(enum bpf_reg_type type)
  1984. {
  1985. switch (type) {
  1986. case PTR_TO_MAP_VALUE:
  1987. case PTR_TO_MAP_VALUE_OR_NULL:
  1988. case PTR_TO_STACK:
  1989. case PTR_TO_CTX:
  1990. case PTR_TO_PACKET:
  1991. case PTR_TO_PACKET_META:
  1992. case PTR_TO_PACKET_END:
  1993. case PTR_TO_FLOW_KEYS:
  1994. case CONST_PTR_TO_MAP:
  1995. case PTR_TO_SOCKET:
  1996. case PTR_TO_SOCKET_OR_NULL:
  1997. case PTR_TO_SOCK_COMMON:
  1998. case PTR_TO_SOCK_COMMON_OR_NULL:
  1999. case PTR_TO_TCP_SOCK:
  2000. case PTR_TO_TCP_SOCK_OR_NULL:
  2001. case PTR_TO_XDP_SOCK:
  2002. case PTR_TO_BTF_ID:
  2003. case PTR_TO_BTF_ID_OR_NULL:
  2004. case PTR_TO_RDONLY_BUF:
  2005. case PTR_TO_RDONLY_BUF_OR_NULL:
  2006. case PTR_TO_RDWR_BUF:
  2007. case PTR_TO_RDWR_BUF_OR_NULL:
  2008. case PTR_TO_PERCPU_BTF_ID:
  2009. case PTR_TO_MEM:
  2010. case PTR_TO_MEM_OR_NULL:
  2011. return true;
  2012. default:
  2013. return false;
  2014. }
  2015. }
  2016. /* Does this register contain a constant zero? */
  2017. static bool register_is_null(struct bpf_reg_state *reg)
  2018. {
  2019. return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
  2020. }
  2021. static bool register_is_const(struct bpf_reg_state *reg)
  2022. {
  2023. return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
  2024. }
  2025. static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
  2026. {
  2027. return tnum_is_unknown(reg->var_off) &&
  2028. reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
  2029. reg->umin_value == 0 && reg->umax_value == U64_MAX &&
  2030. reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
  2031. reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
  2032. }
  2033. static bool register_is_bounded(struct bpf_reg_state *reg)
  2034. {
  2035. return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
  2036. }
  2037. static bool __is_pointer_value(bool allow_ptr_leaks,
  2038. const struct bpf_reg_state *reg)
  2039. {
  2040. if (allow_ptr_leaks)
  2041. return false;
  2042. return reg->type != SCALAR_VALUE;
  2043. }
  2044. static void save_register_state(struct bpf_func_state *state,
  2045. int spi, struct bpf_reg_state *reg)
  2046. {
  2047. int i;
  2048. state->stack[spi].spilled_ptr = *reg;
  2049. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  2050. for (i = 0; i < BPF_REG_SIZE; i++)
  2051. state->stack[spi].slot_type[i] = STACK_SPILL;
  2052. }
  2053. /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
  2054. * stack boundary and alignment are checked in check_mem_access()
  2055. */
  2056. static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
  2057. /* stack frame we're writing to */
  2058. struct bpf_func_state *state,
  2059. int off, int size, int value_regno,
  2060. int insn_idx)
  2061. {
  2062. struct bpf_func_state *cur; /* state of the current function */
  2063. int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
  2064. u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
  2065. struct bpf_reg_state *reg = NULL;
  2066. err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
  2067. state->acquired_refs, true);
  2068. if (err)
  2069. return err;
  2070. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  2071. * so it's aligned access and [off, off + size) are within stack limits
  2072. */
  2073. if (!env->allow_ptr_leaks &&
  2074. state->stack[spi].slot_type[0] == STACK_SPILL &&
  2075. size != BPF_REG_SIZE) {
  2076. verbose(env, "attempt to corrupt spilled pointer on stack\n");
  2077. return -EACCES;
  2078. }
  2079. cur = env->cur_state->frame[env->cur_state->curframe];
  2080. if (value_regno >= 0)
  2081. reg = &cur->regs[value_regno];
  2082. if (!env->bypass_spec_v4) {
  2083. bool sanitize = reg && is_spillable_regtype(reg->type);
  2084. for (i = 0; i < size; i++) {
  2085. if (state->stack[spi].slot_type[i] == STACK_INVALID) {
  2086. sanitize = true;
  2087. break;
  2088. }
  2089. }
  2090. if (sanitize)
  2091. env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
  2092. }
  2093. if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
  2094. !register_is_null(reg) && env->bpf_capable) {
  2095. if (dst_reg != BPF_REG_FP) {
  2096. /* The backtracking logic can only recognize explicit
  2097. * stack slot address like [fp - 8]. Other spill of
  2098. * scalar via different register has to be conervative.
  2099. * Backtrack from here and mark all registers as precise
  2100. * that contributed into 'reg' being a constant.
  2101. */
  2102. err = mark_chain_precision(env, value_regno);
  2103. if (err)
  2104. return err;
  2105. }
  2106. save_register_state(state, spi, reg);
  2107. } else if (reg && is_spillable_regtype(reg->type)) {
  2108. /* register containing pointer is being spilled into stack */
  2109. if (size != BPF_REG_SIZE) {
  2110. verbose_linfo(env, insn_idx, "; ");
  2111. verbose(env, "invalid size of register spill\n");
  2112. return -EACCES;
  2113. }
  2114. if (state != cur && reg->type == PTR_TO_STACK) {
  2115. verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
  2116. return -EINVAL;
  2117. }
  2118. save_register_state(state, spi, reg);
  2119. } else {
  2120. u8 type = STACK_MISC;
  2121. /* regular write of data into stack destroys any spilled ptr */
  2122. state->stack[spi].spilled_ptr.type = NOT_INIT;
  2123. /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
  2124. if (state->stack[spi].slot_type[0] == STACK_SPILL)
  2125. for (i = 0; i < BPF_REG_SIZE; i++)
  2126. state->stack[spi].slot_type[i] = STACK_MISC;
  2127. /* only mark the slot as written if all 8 bytes were written
  2128. * otherwise read propagation may incorrectly stop too soon
  2129. * when stack slots are partially written.
  2130. * This heuristic means that read propagation will be
  2131. * conservative, since it will add reg_live_read marks
  2132. * to stack slots all the way to first state when programs
  2133. * writes+reads less than 8 bytes
  2134. */
  2135. if (size == BPF_REG_SIZE)
  2136. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  2137. /* when we zero initialize stack slots mark them as such */
  2138. if (reg && register_is_null(reg)) {
  2139. /* backtracking doesn't work for STACK_ZERO yet. */
  2140. err = mark_chain_precision(env, value_regno);
  2141. if (err)
  2142. return err;
  2143. type = STACK_ZERO;
  2144. }
  2145. /* Mark slots affected by this stack write. */
  2146. for (i = 0; i < size; i++)
  2147. state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
  2148. type;
  2149. }
  2150. return 0;
  2151. }
  2152. /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
  2153. * known to contain a variable offset.
  2154. * This function checks whether the write is permitted and conservatively
  2155. * tracks the effects of the write, considering that each stack slot in the
  2156. * dynamic range is potentially written to.
  2157. *
  2158. * 'off' includes 'regno->off'.
  2159. * 'value_regno' can be -1, meaning that an unknown value is being written to
  2160. * the stack.
  2161. *
  2162. * Spilled pointers in range are not marked as written because we don't know
  2163. * what's going to be actually written. This means that read propagation for
  2164. * future reads cannot be terminated by this write.
  2165. *
  2166. * For privileged programs, uninitialized stack slots are considered
  2167. * initialized by this write (even though we don't know exactly what offsets
  2168. * are going to be written to). The idea is that we don't want the verifier to
  2169. * reject future reads that access slots written to through variable offsets.
  2170. */
  2171. static int check_stack_write_var_off(struct bpf_verifier_env *env,
  2172. /* func where register points to */
  2173. struct bpf_func_state *state,
  2174. int ptr_regno, int off, int size,
  2175. int value_regno, int insn_idx)
  2176. {
  2177. struct bpf_func_state *cur; /* state of the current function */
  2178. int min_off, max_off;
  2179. int i, err;
  2180. struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
  2181. bool writing_zero = false;
  2182. /* set if the fact that we're writing a zero is used to let any
  2183. * stack slots remain STACK_ZERO
  2184. */
  2185. bool zero_used = false;
  2186. cur = env->cur_state->frame[env->cur_state->curframe];
  2187. ptr_reg = &cur->regs[ptr_regno];
  2188. min_off = ptr_reg->smin_value + off;
  2189. max_off = ptr_reg->smax_value + off + size;
  2190. if (value_regno >= 0)
  2191. value_reg = &cur->regs[value_regno];
  2192. if (value_reg && register_is_null(value_reg))
  2193. writing_zero = true;
  2194. err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
  2195. state->acquired_refs, true);
  2196. if (err)
  2197. return err;
  2198. /* Variable offset writes destroy any spilled pointers in range. */
  2199. for (i = min_off; i < max_off; i++) {
  2200. u8 new_type, *stype;
  2201. int slot, spi;
  2202. slot = -i - 1;
  2203. spi = slot / BPF_REG_SIZE;
  2204. stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
  2205. if (!env->allow_ptr_leaks
  2206. && *stype != NOT_INIT
  2207. && *stype != SCALAR_VALUE) {
  2208. /* Reject the write if there's are spilled pointers in
  2209. * range. If we didn't reject here, the ptr status
  2210. * would be erased below (even though not all slots are
  2211. * actually overwritten), possibly opening the door to
  2212. * leaks.
  2213. */
  2214. verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
  2215. insn_idx, i);
  2216. return -EINVAL;
  2217. }
  2218. /* Erase all spilled pointers. */
  2219. state->stack[spi].spilled_ptr.type = NOT_INIT;
  2220. /* Update the slot type. */
  2221. new_type = STACK_MISC;
  2222. if (writing_zero && *stype == STACK_ZERO) {
  2223. new_type = STACK_ZERO;
  2224. zero_used = true;
  2225. }
  2226. /* If the slot is STACK_INVALID, we check whether it's OK to
  2227. * pretend that it will be initialized by this write. The slot
  2228. * might not actually be written to, and so if we mark it as
  2229. * initialized future reads might leak uninitialized memory.
  2230. * For privileged programs, we will accept such reads to slots
  2231. * that may or may not be written because, if we're reject
  2232. * them, the error would be too confusing.
  2233. */
  2234. if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
  2235. verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
  2236. insn_idx, i);
  2237. return -EINVAL;
  2238. }
  2239. *stype = new_type;
  2240. }
  2241. if (zero_used) {
  2242. /* backtracking doesn't work for STACK_ZERO yet. */
  2243. err = mark_chain_precision(env, value_regno);
  2244. if (err)
  2245. return err;
  2246. }
  2247. return 0;
  2248. }
  2249. /* When register 'dst_regno' is assigned some values from stack[min_off,
  2250. * max_off), we set the register's type according to the types of the
  2251. * respective stack slots. If all the stack values are known to be zeros, then
  2252. * so is the destination reg. Otherwise, the register is considered to be
  2253. * SCALAR. This function does not deal with register filling; the caller must
  2254. * ensure that all spilled registers in the stack range have been marked as
  2255. * read.
  2256. */
  2257. static void mark_reg_stack_read(struct bpf_verifier_env *env,
  2258. /* func where src register points to */
  2259. struct bpf_func_state *ptr_state,
  2260. int min_off, int max_off, int dst_regno)
  2261. {
  2262. struct bpf_verifier_state *vstate = env->cur_state;
  2263. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2264. int i, slot, spi;
  2265. u8 *stype;
  2266. int zeros = 0;
  2267. for (i = min_off; i < max_off; i++) {
  2268. slot = -i - 1;
  2269. spi = slot / BPF_REG_SIZE;
  2270. stype = ptr_state->stack[spi].slot_type;
  2271. if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
  2272. break;
  2273. zeros++;
  2274. }
  2275. if (zeros == max_off - min_off) {
  2276. /* any access_size read into register is zero extended,
  2277. * so the whole register == const_zero
  2278. */
  2279. __mark_reg_const_zero(&state->regs[dst_regno]);
  2280. /* backtracking doesn't support STACK_ZERO yet,
  2281. * so mark it precise here, so that later
  2282. * backtracking can stop here.
  2283. * Backtracking may not need this if this register
  2284. * doesn't participate in pointer adjustment.
  2285. * Forward propagation of precise flag is not
  2286. * necessary either. This mark is only to stop
  2287. * backtracking. Any register that contributed
  2288. * to const 0 was marked precise before spill.
  2289. */
  2290. state->regs[dst_regno].precise = true;
  2291. } else {
  2292. /* have read misc data from the stack */
  2293. mark_reg_unknown(env, state->regs, dst_regno);
  2294. }
  2295. state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
  2296. }
  2297. /* Read the stack at 'off' and put the results into the register indicated by
  2298. * 'dst_regno'. It handles reg filling if the addressed stack slot is a
  2299. * spilled reg.
  2300. *
  2301. * 'dst_regno' can be -1, meaning that the read value is not going to a
  2302. * register.
  2303. *
  2304. * The access is assumed to be within the current stack bounds.
  2305. */
  2306. static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
  2307. /* func where src register points to */
  2308. struct bpf_func_state *reg_state,
  2309. int off, int size, int dst_regno)
  2310. {
  2311. struct bpf_verifier_state *vstate = env->cur_state;
  2312. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2313. int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
  2314. struct bpf_reg_state *reg;
  2315. u8 *stype;
  2316. stype = reg_state->stack[spi].slot_type;
  2317. reg = &reg_state->stack[spi].spilled_ptr;
  2318. if (stype[0] == STACK_SPILL) {
  2319. if (size != BPF_REG_SIZE) {
  2320. if (reg->type != SCALAR_VALUE) {
  2321. verbose_linfo(env, env->insn_idx, "; ");
  2322. verbose(env, "invalid size of register fill\n");
  2323. return -EACCES;
  2324. }
  2325. if (dst_regno >= 0) {
  2326. mark_reg_unknown(env, state->regs, dst_regno);
  2327. state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
  2328. }
  2329. mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
  2330. return 0;
  2331. }
  2332. for (i = 1; i < BPF_REG_SIZE; i++) {
  2333. if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
  2334. verbose(env, "corrupted spill memory\n");
  2335. return -EACCES;
  2336. }
  2337. }
  2338. if (dst_regno >= 0) {
  2339. /* restore register state from stack */
  2340. state->regs[dst_regno] = *reg;
  2341. /* mark reg as written since spilled pointer state likely
  2342. * has its liveness marks cleared by is_state_visited()
  2343. * which resets stack/reg liveness for state transitions
  2344. */
  2345. state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
  2346. } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
  2347. /* If dst_regno==-1, the caller is asking us whether
  2348. * it is acceptable to use this value as a SCALAR_VALUE
  2349. * (e.g. for XADD).
  2350. * We must not allow unprivileged callers to do that
  2351. * with spilled pointers.
  2352. */
  2353. verbose(env, "leaking pointer from stack off %d\n",
  2354. off);
  2355. return -EACCES;
  2356. }
  2357. mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
  2358. } else {
  2359. u8 type;
  2360. for (i = 0; i < size; i++) {
  2361. type = stype[(slot - i) % BPF_REG_SIZE];
  2362. if (type == STACK_MISC)
  2363. continue;
  2364. if (type == STACK_ZERO)
  2365. continue;
  2366. verbose(env, "invalid read from stack off %d+%d size %d\n",
  2367. off, i, size);
  2368. return -EACCES;
  2369. }
  2370. mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
  2371. if (dst_regno >= 0)
  2372. mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
  2373. }
  2374. return 0;
  2375. }
  2376. enum stack_access_src {
  2377. ACCESS_DIRECT = 1, /* the access is performed by an instruction */
  2378. ACCESS_HELPER = 2, /* the access is performed by a helper */
  2379. };
  2380. static int check_stack_range_initialized(struct bpf_verifier_env *env,
  2381. int regno, int off, int access_size,
  2382. bool zero_size_allowed,
  2383. enum stack_access_src type,
  2384. struct bpf_call_arg_meta *meta);
  2385. static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
  2386. {
  2387. return cur_regs(env) + regno;
  2388. }
  2389. /* Read the stack at 'ptr_regno + off' and put the result into the register
  2390. * 'dst_regno'.
  2391. * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
  2392. * but not its variable offset.
  2393. * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
  2394. *
  2395. * As opposed to check_stack_read_fixed_off, this function doesn't deal with
  2396. * filling registers (i.e. reads of spilled register cannot be detected when
  2397. * the offset is not fixed). We conservatively mark 'dst_regno' as containing
  2398. * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
  2399. * offset; for a fixed offset check_stack_read_fixed_off should be used
  2400. * instead.
  2401. */
  2402. static int check_stack_read_var_off(struct bpf_verifier_env *env,
  2403. int ptr_regno, int off, int size, int dst_regno)
  2404. {
  2405. /* The state of the source register. */
  2406. struct bpf_reg_state *reg = reg_state(env, ptr_regno);
  2407. struct bpf_func_state *ptr_state = func(env, reg);
  2408. int err;
  2409. int min_off, max_off;
  2410. /* Note that we pass a NULL meta, so raw access will not be permitted.
  2411. */
  2412. err = check_stack_range_initialized(env, ptr_regno, off, size,
  2413. false, ACCESS_DIRECT, NULL);
  2414. if (err)
  2415. return err;
  2416. min_off = reg->smin_value + off;
  2417. max_off = reg->smax_value + off;
  2418. mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
  2419. return 0;
  2420. }
  2421. /* check_stack_read dispatches to check_stack_read_fixed_off or
  2422. * check_stack_read_var_off.
  2423. *
  2424. * The caller must ensure that the offset falls within the allocated stack
  2425. * bounds.
  2426. *
  2427. * 'dst_regno' is a register which will receive the value from the stack. It
  2428. * can be -1, meaning that the read value is not going to a register.
  2429. */
  2430. static int check_stack_read(struct bpf_verifier_env *env,
  2431. int ptr_regno, int off, int size,
  2432. int dst_regno)
  2433. {
  2434. struct bpf_reg_state *reg = reg_state(env, ptr_regno);
  2435. struct bpf_func_state *state = func(env, reg);
  2436. int err;
  2437. /* Some accesses are only permitted with a static offset. */
  2438. bool var_off = !tnum_is_const(reg->var_off);
  2439. /* The offset is required to be static when reads don't go to a
  2440. * register, in order to not leak pointers (see
  2441. * check_stack_read_fixed_off).
  2442. */
  2443. if (dst_regno < 0 && var_off) {
  2444. char tn_buf[48];
  2445. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  2446. verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
  2447. tn_buf, off, size);
  2448. return -EACCES;
  2449. }
  2450. /* Variable offset is prohibited for unprivileged mode for simplicity
  2451. * since it requires corresponding support in Spectre masking for stack
  2452. * ALU. See also retrieve_ptr_limit().
  2453. */
  2454. if (!env->bypass_spec_v1 && var_off) {
  2455. char tn_buf[48];
  2456. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  2457. verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
  2458. ptr_regno, tn_buf);
  2459. return -EACCES;
  2460. }
  2461. if (!var_off) {
  2462. off += reg->var_off.value;
  2463. err = check_stack_read_fixed_off(env, state, off, size,
  2464. dst_regno);
  2465. } else {
  2466. /* Variable offset stack reads need more conservative handling
  2467. * than fixed offset ones. Note that dst_regno >= 0 on this
  2468. * branch.
  2469. */
  2470. err = check_stack_read_var_off(env, ptr_regno, off, size,
  2471. dst_regno);
  2472. }
  2473. return err;
  2474. }
  2475. /* check_stack_write dispatches to check_stack_write_fixed_off or
  2476. * check_stack_write_var_off.
  2477. *
  2478. * 'ptr_regno' is the register used as a pointer into the stack.
  2479. * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
  2480. * 'value_regno' is the register whose value we're writing to the stack. It can
  2481. * be -1, meaning that we're not writing from a register.
  2482. *
  2483. * The caller must ensure that the offset falls within the maximum stack size.
  2484. */
  2485. static int check_stack_write(struct bpf_verifier_env *env,
  2486. int ptr_regno, int off, int size,
  2487. int value_regno, int insn_idx)
  2488. {
  2489. struct bpf_reg_state *reg = reg_state(env, ptr_regno);
  2490. struct bpf_func_state *state = func(env, reg);
  2491. int err;
  2492. if (tnum_is_const(reg->var_off)) {
  2493. off += reg->var_off.value;
  2494. err = check_stack_write_fixed_off(env, state, off, size,
  2495. value_regno, insn_idx);
  2496. } else {
  2497. /* Variable offset stack reads need more conservative handling
  2498. * than fixed offset ones.
  2499. */
  2500. err = check_stack_write_var_off(env, state,
  2501. ptr_regno, off, size,
  2502. value_regno, insn_idx);
  2503. }
  2504. return err;
  2505. }
  2506. static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
  2507. int off, int size, enum bpf_access_type type)
  2508. {
  2509. struct bpf_reg_state *regs = cur_regs(env);
  2510. struct bpf_map *map = regs[regno].map_ptr;
  2511. u32 cap = bpf_map_flags_to_cap(map);
  2512. if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
  2513. verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
  2514. map->value_size, off, size);
  2515. return -EACCES;
  2516. }
  2517. if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
  2518. verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
  2519. map->value_size, off, size);
  2520. return -EACCES;
  2521. }
  2522. return 0;
  2523. }
  2524. /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
  2525. static int __check_mem_access(struct bpf_verifier_env *env, int regno,
  2526. int off, int size, u32 mem_size,
  2527. bool zero_size_allowed)
  2528. {
  2529. bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
  2530. struct bpf_reg_state *reg;
  2531. if (off >= 0 && size_ok && (u64)off + size <= mem_size)
  2532. return 0;
  2533. reg = &cur_regs(env)[regno];
  2534. switch (reg->type) {
  2535. case PTR_TO_MAP_VALUE:
  2536. verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
  2537. mem_size, off, size);
  2538. break;
  2539. case PTR_TO_PACKET:
  2540. case PTR_TO_PACKET_META:
  2541. case PTR_TO_PACKET_END:
  2542. verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
  2543. off, size, regno, reg->id, off, mem_size);
  2544. break;
  2545. case PTR_TO_MEM:
  2546. default:
  2547. verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
  2548. mem_size, off, size);
  2549. }
  2550. return -EACCES;
  2551. }
  2552. /* check read/write into a memory region with possible variable offset */
  2553. static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
  2554. int off, int size, u32 mem_size,
  2555. bool zero_size_allowed)
  2556. {
  2557. struct bpf_verifier_state *vstate = env->cur_state;
  2558. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2559. struct bpf_reg_state *reg = &state->regs[regno];
  2560. int err;
  2561. /* We may have adjusted the register pointing to memory region, so we
  2562. * need to try adding each of min_value and max_value to off
  2563. * to make sure our theoretical access will be safe.
  2564. */
  2565. if (env->log.level & BPF_LOG_LEVEL)
  2566. print_verifier_state(env, state);
  2567. /* The minimum value is only important with signed
  2568. * comparisons where we can't assume the floor of a
  2569. * value is 0. If we are using signed variables for our
  2570. * index'es we need to make sure that whatever we use
  2571. * will have a set floor within our range.
  2572. */
  2573. if (reg->smin_value < 0 &&
  2574. (reg->smin_value == S64_MIN ||
  2575. (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
  2576. reg->smin_value + off < 0)) {
  2577. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  2578. regno);
  2579. return -EACCES;
  2580. }
  2581. err = __check_mem_access(env, regno, reg->smin_value + off, size,
  2582. mem_size, zero_size_allowed);
  2583. if (err) {
  2584. verbose(env, "R%d min value is outside of the allowed memory range\n",
  2585. regno);
  2586. return err;
  2587. }
  2588. /* If we haven't set a max value then we need to bail since we can't be
  2589. * sure we won't do bad things.
  2590. * If reg->umax_value + off could overflow, treat that as unbounded too.
  2591. */
  2592. if (reg->umax_value >= BPF_MAX_VAR_OFF) {
  2593. verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
  2594. regno);
  2595. return -EACCES;
  2596. }
  2597. err = __check_mem_access(env, regno, reg->umax_value + off, size,
  2598. mem_size, zero_size_allowed);
  2599. if (err) {
  2600. verbose(env, "R%d max value is outside of the allowed memory range\n",
  2601. regno);
  2602. return err;
  2603. }
  2604. return 0;
  2605. }
  2606. /* check read/write into a map element with possible variable offset */
  2607. static int check_map_access(struct bpf_verifier_env *env, u32 regno,
  2608. int off, int size, bool zero_size_allowed)
  2609. {
  2610. struct bpf_verifier_state *vstate = env->cur_state;
  2611. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2612. struct bpf_reg_state *reg = &state->regs[regno];
  2613. struct bpf_map *map = reg->map_ptr;
  2614. int err;
  2615. err = check_mem_region_access(env, regno, off, size, map->value_size,
  2616. zero_size_allowed);
  2617. if (err)
  2618. return err;
  2619. if (map_value_has_spin_lock(map)) {
  2620. u32 lock = map->spin_lock_off;
  2621. /* if any part of struct bpf_spin_lock can be touched by
  2622. * load/store reject this program.
  2623. * To check that [x1, x2) overlaps with [y1, y2)
  2624. * it is sufficient to check x1 < y2 && y1 < x2.
  2625. */
  2626. if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
  2627. lock < reg->umax_value + off + size) {
  2628. verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
  2629. return -EACCES;
  2630. }
  2631. }
  2632. return err;
  2633. }
  2634. #define MAX_PACKET_OFF 0xffff
  2635. static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
  2636. {
  2637. return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
  2638. }
  2639. static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
  2640. const struct bpf_call_arg_meta *meta,
  2641. enum bpf_access_type t)
  2642. {
  2643. enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
  2644. switch (prog_type) {
  2645. /* Program types only with direct read access go here! */
  2646. case BPF_PROG_TYPE_LWT_IN:
  2647. case BPF_PROG_TYPE_LWT_OUT:
  2648. case BPF_PROG_TYPE_LWT_SEG6LOCAL:
  2649. case BPF_PROG_TYPE_SK_REUSEPORT:
  2650. case BPF_PROG_TYPE_FLOW_DISSECTOR:
  2651. case BPF_PROG_TYPE_CGROUP_SKB:
  2652. if (t == BPF_WRITE)
  2653. return false;
  2654. fallthrough;
  2655. /* Program types with direct read + write access go here! */
  2656. case BPF_PROG_TYPE_SCHED_CLS:
  2657. case BPF_PROG_TYPE_SCHED_ACT:
  2658. case BPF_PROG_TYPE_XDP:
  2659. case BPF_PROG_TYPE_LWT_XMIT:
  2660. case BPF_PROG_TYPE_SK_SKB:
  2661. case BPF_PROG_TYPE_SK_MSG:
  2662. if (meta)
  2663. return meta->pkt_access;
  2664. env->seen_direct_write = true;
  2665. return true;
  2666. case BPF_PROG_TYPE_CGROUP_SOCKOPT:
  2667. if (t == BPF_WRITE)
  2668. env->seen_direct_write = true;
  2669. return true;
  2670. default:
  2671. return false;
  2672. }
  2673. }
  2674. static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
  2675. int size, bool zero_size_allowed)
  2676. {
  2677. struct bpf_reg_state *regs = cur_regs(env);
  2678. struct bpf_reg_state *reg = &regs[regno];
  2679. int err;
  2680. /* We may have added a variable offset to the packet pointer; but any
  2681. * reg->range we have comes after that. We are only checking the fixed
  2682. * offset.
  2683. */
  2684. /* We don't allow negative numbers, because we aren't tracking enough
  2685. * detail to prove they're safe.
  2686. */
  2687. if (reg->smin_value < 0) {
  2688. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  2689. regno);
  2690. return -EACCES;
  2691. }
  2692. err = __check_mem_access(env, regno, off, size, reg->range,
  2693. zero_size_allowed);
  2694. if (err) {
  2695. verbose(env, "R%d offset is outside of the packet\n", regno);
  2696. return err;
  2697. }
  2698. /* __check_mem_access has made sure "off + size - 1" is within u16.
  2699. * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
  2700. * otherwise find_good_pkt_pointers would have refused to set range info
  2701. * that __check_mem_access would have rejected this pkt access.
  2702. * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
  2703. */
  2704. env->prog->aux->max_pkt_offset =
  2705. max_t(u32, env->prog->aux->max_pkt_offset,
  2706. off + reg->umax_value + size - 1);
  2707. return err;
  2708. }
  2709. /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
  2710. static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
  2711. enum bpf_access_type t, enum bpf_reg_type *reg_type,
  2712. u32 *btf_id)
  2713. {
  2714. struct bpf_insn_access_aux info = {
  2715. .reg_type = *reg_type,
  2716. .log = &env->log,
  2717. };
  2718. if (env->ops->is_valid_access &&
  2719. env->ops->is_valid_access(off, size, t, env->prog, &info)) {
  2720. /* A non zero info.ctx_field_size indicates that this field is a
  2721. * candidate for later verifier transformation to load the whole
  2722. * field and then apply a mask when accessed with a narrower
  2723. * access than actual ctx access size. A zero info.ctx_field_size
  2724. * will only allow for whole field access and rejects any other
  2725. * type of narrower access.
  2726. */
  2727. *reg_type = info.reg_type;
  2728. if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
  2729. *btf_id = info.btf_id;
  2730. else
  2731. env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
  2732. /* remember the offset of last byte accessed in ctx */
  2733. if (env->prog->aux->max_ctx_offset < off + size)
  2734. env->prog->aux->max_ctx_offset = off + size;
  2735. return 0;
  2736. }
  2737. verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
  2738. return -EACCES;
  2739. }
  2740. static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
  2741. int size)
  2742. {
  2743. if (size < 0 || off < 0 ||
  2744. (u64)off + size > sizeof(struct bpf_flow_keys)) {
  2745. verbose(env, "invalid access to flow keys off=%d size=%d\n",
  2746. off, size);
  2747. return -EACCES;
  2748. }
  2749. return 0;
  2750. }
  2751. static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
  2752. u32 regno, int off, int size,
  2753. enum bpf_access_type t)
  2754. {
  2755. struct bpf_reg_state *regs = cur_regs(env);
  2756. struct bpf_reg_state *reg = &regs[regno];
  2757. struct bpf_insn_access_aux info = {};
  2758. bool valid;
  2759. if (reg->smin_value < 0) {
  2760. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  2761. regno);
  2762. return -EACCES;
  2763. }
  2764. switch (reg->type) {
  2765. case PTR_TO_SOCK_COMMON:
  2766. valid = bpf_sock_common_is_valid_access(off, size, t, &info);
  2767. break;
  2768. case PTR_TO_SOCKET:
  2769. valid = bpf_sock_is_valid_access(off, size, t, &info);
  2770. break;
  2771. case PTR_TO_TCP_SOCK:
  2772. valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
  2773. break;
  2774. case PTR_TO_XDP_SOCK:
  2775. valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
  2776. break;
  2777. default:
  2778. valid = false;
  2779. }
  2780. if (valid) {
  2781. env->insn_aux_data[insn_idx].ctx_field_size =
  2782. info.ctx_field_size;
  2783. return 0;
  2784. }
  2785. verbose(env, "R%d invalid %s access off=%d size=%d\n",
  2786. regno, reg_type_str[reg->type], off, size);
  2787. return -EACCES;
  2788. }
  2789. static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
  2790. {
  2791. return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
  2792. }
  2793. static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
  2794. {
  2795. const struct bpf_reg_state *reg = reg_state(env, regno);
  2796. return reg->type == PTR_TO_CTX;
  2797. }
  2798. static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
  2799. {
  2800. const struct bpf_reg_state *reg = reg_state(env, regno);
  2801. return type_is_sk_pointer(reg->type);
  2802. }
  2803. static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
  2804. {
  2805. const struct bpf_reg_state *reg = reg_state(env, regno);
  2806. return type_is_pkt_pointer(reg->type);
  2807. }
  2808. static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
  2809. {
  2810. const struct bpf_reg_state *reg = reg_state(env, regno);
  2811. /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
  2812. return reg->type == PTR_TO_FLOW_KEYS;
  2813. }
  2814. static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
  2815. const struct bpf_reg_state *reg,
  2816. int off, int size, bool strict)
  2817. {
  2818. struct tnum reg_off;
  2819. int ip_align;
  2820. /* Byte size accesses are always allowed. */
  2821. if (!strict || size == 1)
  2822. return 0;
  2823. /* For platforms that do not have a Kconfig enabling
  2824. * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
  2825. * NET_IP_ALIGN is universally set to '2'. And on platforms
  2826. * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
  2827. * to this code only in strict mode where we want to emulate
  2828. * the NET_IP_ALIGN==2 checking. Therefore use an
  2829. * unconditional IP align value of '2'.
  2830. */
  2831. ip_align = 2;
  2832. reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
  2833. if (!tnum_is_aligned(reg_off, size)) {
  2834. char tn_buf[48];
  2835. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  2836. verbose(env,
  2837. "misaligned packet access off %d+%s+%d+%d size %d\n",
  2838. ip_align, tn_buf, reg->off, off, size);
  2839. return -EACCES;
  2840. }
  2841. return 0;
  2842. }
  2843. static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
  2844. const struct bpf_reg_state *reg,
  2845. const char *pointer_desc,
  2846. int off, int size, bool strict)
  2847. {
  2848. struct tnum reg_off;
  2849. /* Byte size accesses are always allowed. */
  2850. if (!strict || size == 1)
  2851. return 0;
  2852. reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
  2853. if (!tnum_is_aligned(reg_off, size)) {
  2854. char tn_buf[48];
  2855. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  2856. verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
  2857. pointer_desc, tn_buf, reg->off, off, size);
  2858. return -EACCES;
  2859. }
  2860. return 0;
  2861. }
  2862. static int check_ptr_alignment(struct bpf_verifier_env *env,
  2863. const struct bpf_reg_state *reg, int off,
  2864. int size, bool strict_alignment_once)
  2865. {
  2866. bool strict = env->strict_alignment || strict_alignment_once;
  2867. const char *pointer_desc = "";
  2868. switch (reg->type) {
  2869. case PTR_TO_PACKET:
  2870. case PTR_TO_PACKET_META:
  2871. /* Special case, because of NET_IP_ALIGN. Given metadata sits
  2872. * right in front, treat it the very same way.
  2873. */
  2874. return check_pkt_ptr_alignment(env, reg, off, size, strict);
  2875. case PTR_TO_FLOW_KEYS:
  2876. pointer_desc = "flow keys ";
  2877. break;
  2878. case PTR_TO_MAP_VALUE:
  2879. pointer_desc = "value ";
  2880. break;
  2881. case PTR_TO_CTX:
  2882. pointer_desc = "context ";
  2883. break;
  2884. case PTR_TO_STACK:
  2885. pointer_desc = "stack ";
  2886. /* The stack spill tracking logic in check_stack_write_fixed_off()
  2887. * and check_stack_read_fixed_off() relies on stack accesses being
  2888. * aligned.
  2889. */
  2890. strict = true;
  2891. break;
  2892. case PTR_TO_SOCKET:
  2893. pointer_desc = "sock ";
  2894. break;
  2895. case PTR_TO_SOCK_COMMON:
  2896. pointer_desc = "sock_common ";
  2897. break;
  2898. case PTR_TO_TCP_SOCK:
  2899. pointer_desc = "tcp_sock ";
  2900. break;
  2901. case PTR_TO_XDP_SOCK:
  2902. pointer_desc = "xdp_sock ";
  2903. break;
  2904. default:
  2905. break;
  2906. }
  2907. return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
  2908. strict);
  2909. }
  2910. static int update_stack_depth(struct bpf_verifier_env *env,
  2911. const struct bpf_func_state *func,
  2912. int off)
  2913. {
  2914. u16 stack = env->subprog_info[func->subprogno].stack_depth;
  2915. if (stack >= -off)
  2916. return 0;
  2917. /* update known max for given subprogram */
  2918. env->subprog_info[func->subprogno].stack_depth = -off;
  2919. return 0;
  2920. }
  2921. /* starting from main bpf function walk all instructions of the function
  2922. * and recursively walk all callees that given function can call.
  2923. * Ignore jump and exit insns.
  2924. * Since recursion is prevented by check_cfg() this algorithm
  2925. * only needs a local stack of MAX_CALL_FRAMES to remember callsites
  2926. */
  2927. static int check_max_stack_depth(struct bpf_verifier_env *env)
  2928. {
  2929. int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
  2930. struct bpf_subprog_info *subprog = env->subprog_info;
  2931. struct bpf_insn *insn = env->prog->insnsi;
  2932. bool tail_call_reachable = false;
  2933. int ret_insn[MAX_CALL_FRAMES];
  2934. int ret_prog[MAX_CALL_FRAMES];
  2935. int j;
  2936. process_func:
  2937. /* protect against potential stack overflow that might happen when
  2938. * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
  2939. * depth for such case down to 256 so that the worst case scenario
  2940. * would result in 8k stack size (32 which is tailcall limit * 256 =
  2941. * 8k).
  2942. *
  2943. * To get the idea what might happen, see an example:
  2944. * func1 -> sub rsp, 128
  2945. * subfunc1 -> sub rsp, 256
  2946. * tailcall1 -> add rsp, 256
  2947. * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
  2948. * subfunc2 -> sub rsp, 64
  2949. * subfunc22 -> sub rsp, 128
  2950. * tailcall2 -> add rsp, 128
  2951. * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
  2952. *
  2953. * tailcall will unwind the current stack frame but it will not get rid
  2954. * of caller's stack as shown on the example above.
  2955. */
  2956. if (idx && subprog[idx].has_tail_call && depth >= 256) {
  2957. verbose(env,
  2958. "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
  2959. depth);
  2960. return -EACCES;
  2961. }
  2962. /* round up to 32-bytes, since this is granularity
  2963. * of interpreter stack size
  2964. */
  2965. depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
  2966. if (depth > MAX_BPF_STACK) {
  2967. verbose(env, "combined stack size of %d calls is %d. Too large\n",
  2968. frame + 1, depth);
  2969. return -EACCES;
  2970. }
  2971. continue_func:
  2972. subprog_end = subprog[idx + 1].start;
  2973. for (; i < subprog_end; i++) {
  2974. if (insn[i].code != (BPF_JMP | BPF_CALL))
  2975. continue;
  2976. if (insn[i].src_reg != BPF_PSEUDO_CALL)
  2977. continue;
  2978. /* remember insn and function to return to */
  2979. ret_insn[frame] = i + 1;
  2980. ret_prog[frame] = idx;
  2981. /* find the callee */
  2982. i = i + insn[i].imm + 1;
  2983. idx = find_subprog(env, i);
  2984. if (idx < 0) {
  2985. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  2986. i);
  2987. return -EFAULT;
  2988. }
  2989. if (subprog[idx].has_tail_call)
  2990. tail_call_reachable = true;
  2991. frame++;
  2992. if (frame >= MAX_CALL_FRAMES) {
  2993. verbose(env, "the call stack of %d frames is too deep !\n",
  2994. frame);
  2995. return -E2BIG;
  2996. }
  2997. goto process_func;
  2998. }
  2999. /* if tail call got detected across bpf2bpf calls then mark each of the
  3000. * currently present subprog frames as tail call reachable subprogs;
  3001. * this info will be utilized by JIT so that we will be preserving the
  3002. * tail call counter throughout bpf2bpf calls combined with tailcalls
  3003. */
  3004. if (tail_call_reachable)
  3005. for (j = 0; j < frame; j++)
  3006. subprog[ret_prog[j]].tail_call_reachable = true;
  3007. if (subprog[0].tail_call_reachable)
  3008. env->prog->aux->tail_call_reachable = true;
  3009. /* end of for() loop means the last insn of the 'subprog'
  3010. * was reached. Doesn't matter whether it was JA or EXIT
  3011. */
  3012. if (frame == 0)
  3013. return 0;
  3014. depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
  3015. frame--;
  3016. i = ret_insn[frame];
  3017. idx = ret_prog[frame];
  3018. goto continue_func;
  3019. }
  3020. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  3021. static int get_callee_stack_depth(struct bpf_verifier_env *env,
  3022. const struct bpf_insn *insn, int idx)
  3023. {
  3024. int start = idx + insn->imm + 1, subprog;
  3025. subprog = find_subprog(env, start);
  3026. if (subprog < 0) {
  3027. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  3028. start);
  3029. return -EFAULT;
  3030. }
  3031. return env->subprog_info[subprog].stack_depth;
  3032. }
  3033. #endif
  3034. int check_ctx_reg(struct bpf_verifier_env *env,
  3035. const struct bpf_reg_state *reg, int regno)
  3036. {
  3037. /* Access to ctx or passing it to a helper is only allowed in
  3038. * its original, unmodified form.
  3039. */
  3040. if (reg->off) {
  3041. verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
  3042. regno, reg->off);
  3043. return -EACCES;
  3044. }
  3045. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  3046. char tn_buf[48];
  3047. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  3048. verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
  3049. return -EACCES;
  3050. }
  3051. return 0;
  3052. }
  3053. static int __check_buffer_access(struct bpf_verifier_env *env,
  3054. const char *buf_info,
  3055. const struct bpf_reg_state *reg,
  3056. int regno, int off, int size)
  3057. {
  3058. if (off < 0) {
  3059. verbose(env,
  3060. "R%d invalid %s buffer access: off=%d, size=%d\n",
  3061. regno, buf_info, off, size);
  3062. return -EACCES;
  3063. }
  3064. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  3065. char tn_buf[48];
  3066. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  3067. verbose(env,
  3068. "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
  3069. regno, off, tn_buf);
  3070. return -EACCES;
  3071. }
  3072. return 0;
  3073. }
  3074. static int check_tp_buffer_access(struct bpf_verifier_env *env,
  3075. const struct bpf_reg_state *reg,
  3076. int regno, int off, int size)
  3077. {
  3078. int err;
  3079. err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
  3080. if (err)
  3081. return err;
  3082. if (off + size > env->prog->aux->max_tp_access)
  3083. env->prog->aux->max_tp_access = off + size;
  3084. return 0;
  3085. }
  3086. static int check_buffer_access(struct bpf_verifier_env *env,
  3087. const struct bpf_reg_state *reg,
  3088. int regno, int off, int size,
  3089. bool zero_size_allowed,
  3090. const char *buf_info,
  3091. u32 *max_access)
  3092. {
  3093. int err;
  3094. err = __check_buffer_access(env, buf_info, reg, regno, off, size);
  3095. if (err)
  3096. return err;
  3097. if (off + size > *max_access)
  3098. *max_access = off + size;
  3099. return 0;
  3100. }
  3101. /* BPF architecture zero extends alu32 ops into 64-bit registesr */
  3102. static void zext_32_to_64(struct bpf_reg_state *reg)
  3103. {
  3104. reg->var_off = tnum_subreg(reg->var_off);
  3105. __reg_assign_32_into_64(reg);
  3106. }
  3107. /* truncate register to smaller size (in bytes)
  3108. * must be called with size < BPF_REG_SIZE
  3109. */
  3110. static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
  3111. {
  3112. u64 mask;
  3113. /* clear high bits in bit representation */
  3114. reg->var_off = tnum_cast(reg->var_off, size);
  3115. /* fix arithmetic bounds */
  3116. mask = ((u64)1 << (size * 8)) - 1;
  3117. if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
  3118. reg->umin_value &= mask;
  3119. reg->umax_value &= mask;
  3120. } else {
  3121. reg->umin_value = 0;
  3122. reg->umax_value = mask;
  3123. }
  3124. reg->smin_value = reg->umin_value;
  3125. reg->smax_value = reg->umax_value;
  3126. /* If size is smaller than 32bit register the 32bit register
  3127. * values are also truncated so we push 64-bit bounds into
  3128. * 32-bit bounds. Above were truncated < 32-bits already.
  3129. */
  3130. if (size >= 4)
  3131. return;
  3132. __reg_combine_64_into_32(reg);
  3133. }
  3134. static bool bpf_map_is_rdonly(const struct bpf_map *map)
  3135. {
  3136. /* A map is considered read-only if the following condition are true:
  3137. *
  3138. * 1) BPF program side cannot change any of the map content. The
  3139. * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
  3140. * and was set at map creation time.
  3141. * 2) The map value(s) have been initialized from user space by a
  3142. * loader and then "frozen", such that no new map update/delete
  3143. * operations from syscall side are possible for the rest of
  3144. * the map's lifetime from that point onwards.
  3145. * 3) Any parallel/pending map update/delete operations from syscall
  3146. * side have been completed. Only after that point, it's safe to
  3147. * assume that map value(s) are immutable.
  3148. */
  3149. return (map->map_flags & BPF_F_RDONLY_PROG) &&
  3150. READ_ONCE(map->frozen) &&
  3151. !bpf_map_write_active(map);
  3152. }
  3153. static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
  3154. {
  3155. void *ptr;
  3156. u64 addr;
  3157. int err;
  3158. err = map->ops->map_direct_value_addr(map, &addr, off);
  3159. if (err)
  3160. return err;
  3161. ptr = (void *)(long)addr + off;
  3162. switch (size) {
  3163. case sizeof(u8):
  3164. *val = (u64)*(u8 *)ptr;
  3165. break;
  3166. case sizeof(u16):
  3167. *val = (u64)*(u16 *)ptr;
  3168. break;
  3169. case sizeof(u32):
  3170. *val = (u64)*(u32 *)ptr;
  3171. break;
  3172. case sizeof(u64):
  3173. *val = *(u64 *)ptr;
  3174. break;
  3175. default:
  3176. return -EINVAL;
  3177. }
  3178. return 0;
  3179. }
  3180. static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
  3181. struct bpf_reg_state *regs,
  3182. int regno, int off, int size,
  3183. enum bpf_access_type atype,
  3184. int value_regno)
  3185. {
  3186. struct bpf_reg_state *reg = regs + regno;
  3187. const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
  3188. const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
  3189. u32 btf_id;
  3190. int ret;
  3191. if (off < 0) {
  3192. verbose(env,
  3193. "R%d is ptr_%s invalid negative access: off=%d\n",
  3194. regno, tname, off);
  3195. return -EACCES;
  3196. }
  3197. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  3198. char tn_buf[48];
  3199. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  3200. verbose(env,
  3201. "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
  3202. regno, tname, off, tn_buf);
  3203. return -EACCES;
  3204. }
  3205. if (env->ops->btf_struct_access) {
  3206. ret = env->ops->btf_struct_access(&env->log, t, off, size,
  3207. atype, &btf_id);
  3208. } else {
  3209. if (atype != BPF_READ) {
  3210. verbose(env, "only read is supported\n");
  3211. return -EACCES;
  3212. }
  3213. ret = btf_struct_access(&env->log, t, off, size, atype,
  3214. &btf_id);
  3215. }
  3216. if (ret < 0)
  3217. return ret;
  3218. if (atype == BPF_READ && value_regno >= 0)
  3219. mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
  3220. return 0;
  3221. }
  3222. static int check_ptr_to_map_access(struct bpf_verifier_env *env,
  3223. struct bpf_reg_state *regs,
  3224. int regno, int off, int size,
  3225. enum bpf_access_type atype,
  3226. int value_regno)
  3227. {
  3228. struct bpf_reg_state *reg = regs + regno;
  3229. struct bpf_map *map = reg->map_ptr;
  3230. const struct btf_type *t;
  3231. const char *tname;
  3232. u32 btf_id;
  3233. int ret;
  3234. if (!btf_vmlinux) {
  3235. verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
  3236. return -ENOTSUPP;
  3237. }
  3238. if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
  3239. verbose(env, "map_ptr access not supported for map type %d\n",
  3240. map->map_type);
  3241. return -ENOTSUPP;
  3242. }
  3243. t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
  3244. tname = btf_name_by_offset(btf_vmlinux, t->name_off);
  3245. if (!env->allow_ptr_to_map_access) {
  3246. verbose(env,
  3247. "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
  3248. tname);
  3249. return -EPERM;
  3250. }
  3251. if (off < 0) {
  3252. verbose(env, "R%d is %s invalid negative access: off=%d\n",
  3253. regno, tname, off);
  3254. return -EACCES;
  3255. }
  3256. if (atype != BPF_READ) {
  3257. verbose(env, "only read from %s is supported\n", tname);
  3258. return -EACCES;
  3259. }
  3260. ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
  3261. if (ret < 0)
  3262. return ret;
  3263. if (value_regno >= 0)
  3264. mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
  3265. return 0;
  3266. }
  3267. /* Check that the stack access at the given offset is within bounds. The
  3268. * maximum valid offset is -1.
  3269. *
  3270. * The minimum valid offset is -MAX_BPF_STACK for writes, and
  3271. * -state->allocated_stack for reads.
  3272. */
  3273. static int check_stack_slot_within_bounds(int off,
  3274. struct bpf_func_state *state,
  3275. enum bpf_access_type t)
  3276. {
  3277. int min_valid_off;
  3278. if (t == BPF_WRITE)
  3279. min_valid_off = -MAX_BPF_STACK;
  3280. else
  3281. min_valid_off = -state->allocated_stack;
  3282. if (off < min_valid_off || off > -1)
  3283. return -EACCES;
  3284. return 0;
  3285. }
  3286. /* Check that the stack access at 'regno + off' falls within the maximum stack
  3287. * bounds.
  3288. *
  3289. * 'off' includes `regno->offset`, but not its dynamic part (if any).
  3290. */
  3291. static int check_stack_access_within_bounds(
  3292. struct bpf_verifier_env *env,
  3293. int regno, int off, int access_size,
  3294. enum stack_access_src src, enum bpf_access_type type)
  3295. {
  3296. struct bpf_reg_state *regs = cur_regs(env);
  3297. struct bpf_reg_state *reg = regs + regno;
  3298. struct bpf_func_state *state = func(env, reg);
  3299. int min_off, max_off;
  3300. int err;
  3301. char *err_extra;
  3302. if (src == ACCESS_HELPER)
  3303. /* We don't know if helpers are reading or writing (or both). */
  3304. err_extra = " indirect access to";
  3305. else if (type == BPF_READ)
  3306. err_extra = " read from";
  3307. else
  3308. err_extra = " write to";
  3309. if (tnum_is_const(reg->var_off)) {
  3310. min_off = reg->var_off.value + off;
  3311. if (access_size > 0)
  3312. max_off = min_off + access_size - 1;
  3313. else
  3314. max_off = min_off;
  3315. } else {
  3316. if (reg->smax_value >= BPF_MAX_VAR_OFF ||
  3317. reg->smin_value <= -BPF_MAX_VAR_OFF) {
  3318. verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
  3319. err_extra, regno);
  3320. return -EACCES;
  3321. }
  3322. min_off = reg->smin_value + off;
  3323. if (access_size > 0)
  3324. max_off = reg->smax_value + off + access_size - 1;
  3325. else
  3326. max_off = min_off;
  3327. }
  3328. err = check_stack_slot_within_bounds(min_off, state, type);
  3329. if (!err)
  3330. err = check_stack_slot_within_bounds(max_off, state, type);
  3331. if (err) {
  3332. if (tnum_is_const(reg->var_off)) {
  3333. verbose(env, "invalid%s stack R%d off=%d size=%d\n",
  3334. err_extra, regno, off, access_size);
  3335. } else {
  3336. char tn_buf[48];
  3337. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  3338. verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
  3339. err_extra, regno, tn_buf, access_size);
  3340. }
  3341. }
  3342. return err;
  3343. }
  3344. /* check whether memory at (regno + off) is accessible for t = (read | write)
  3345. * if t==write, value_regno is a register which value is stored into memory
  3346. * if t==read, value_regno is a register which will receive the value from memory
  3347. * if t==write && value_regno==-1, some unknown value is stored into memory
  3348. * if t==read && value_regno==-1, don't care what we read from memory
  3349. */
  3350. static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
  3351. int off, int bpf_size, enum bpf_access_type t,
  3352. int value_regno, bool strict_alignment_once)
  3353. {
  3354. struct bpf_reg_state *regs = cur_regs(env);
  3355. struct bpf_reg_state *reg = regs + regno;
  3356. struct bpf_func_state *state;
  3357. int size, err = 0;
  3358. size = bpf_size_to_bytes(bpf_size);
  3359. if (size < 0)
  3360. return size;
  3361. /* alignment checks will add in reg->off themselves */
  3362. err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
  3363. if (err)
  3364. return err;
  3365. /* for access checks, reg->off is just part of off */
  3366. off += reg->off;
  3367. if (reg->type == PTR_TO_MAP_VALUE) {
  3368. if (t == BPF_WRITE && value_regno >= 0 &&
  3369. is_pointer_value(env, value_regno)) {
  3370. verbose(env, "R%d leaks addr into map\n", value_regno);
  3371. return -EACCES;
  3372. }
  3373. err = check_map_access_type(env, regno, off, size, t);
  3374. if (err)
  3375. return err;
  3376. err = check_map_access(env, regno, off, size, false);
  3377. if (!err && t == BPF_READ && value_regno >= 0) {
  3378. struct bpf_map *map = reg->map_ptr;
  3379. /* if map is read-only, track its contents as scalars */
  3380. if (tnum_is_const(reg->var_off) &&
  3381. bpf_map_is_rdonly(map) &&
  3382. map->ops->map_direct_value_addr) {
  3383. int map_off = off + reg->var_off.value;
  3384. u64 val = 0;
  3385. err = bpf_map_direct_read(map, map_off, size,
  3386. &val);
  3387. if (err)
  3388. return err;
  3389. regs[value_regno].type = SCALAR_VALUE;
  3390. __mark_reg_known(&regs[value_regno], val);
  3391. } else {
  3392. mark_reg_unknown(env, regs, value_regno);
  3393. }
  3394. }
  3395. } else if (reg->type == PTR_TO_MEM) {
  3396. if (t == BPF_WRITE && value_regno >= 0 &&
  3397. is_pointer_value(env, value_regno)) {
  3398. verbose(env, "R%d leaks addr into mem\n", value_regno);
  3399. return -EACCES;
  3400. }
  3401. err = check_mem_region_access(env, regno, off, size,
  3402. reg->mem_size, false);
  3403. if (!err && t == BPF_READ && value_regno >= 0)
  3404. mark_reg_unknown(env, regs, value_regno);
  3405. } else if (reg->type == PTR_TO_CTX) {
  3406. enum bpf_reg_type reg_type = SCALAR_VALUE;
  3407. u32 btf_id = 0;
  3408. if (t == BPF_WRITE && value_regno >= 0 &&
  3409. is_pointer_value(env, value_regno)) {
  3410. verbose(env, "R%d leaks addr into ctx\n", value_regno);
  3411. return -EACCES;
  3412. }
  3413. err = check_ctx_reg(env, reg, regno);
  3414. if (err < 0)
  3415. return err;
  3416. err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
  3417. if (err)
  3418. verbose_linfo(env, insn_idx, "; ");
  3419. if (!err && t == BPF_READ && value_regno >= 0) {
  3420. /* ctx access returns either a scalar, or a
  3421. * PTR_TO_PACKET[_META,_END]. In the latter
  3422. * case, we know the offset is zero.
  3423. */
  3424. if (reg_type == SCALAR_VALUE) {
  3425. mark_reg_unknown(env, regs, value_regno);
  3426. } else {
  3427. mark_reg_known_zero(env, regs,
  3428. value_regno);
  3429. if (reg_type_may_be_null(reg_type))
  3430. regs[value_regno].id = ++env->id_gen;
  3431. /* A load of ctx field could have different
  3432. * actual load size with the one encoded in the
  3433. * insn. When the dst is PTR, it is for sure not
  3434. * a sub-register.
  3435. */
  3436. regs[value_regno].subreg_def = DEF_NOT_SUBREG;
  3437. if (reg_type == PTR_TO_BTF_ID ||
  3438. reg_type == PTR_TO_BTF_ID_OR_NULL)
  3439. regs[value_regno].btf_id = btf_id;
  3440. }
  3441. regs[value_regno].type = reg_type;
  3442. }
  3443. } else if (reg->type == PTR_TO_STACK) {
  3444. /* Basic bounds checks. */
  3445. err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
  3446. if (err)
  3447. return err;
  3448. state = func(env, reg);
  3449. err = update_stack_depth(env, state, off);
  3450. if (err)
  3451. return err;
  3452. if (t == BPF_READ)
  3453. err = check_stack_read(env, regno, off, size,
  3454. value_regno);
  3455. else
  3456. err = check_stack_write(env, regno, off, size,
  3457. value_regno, insn_idx);
  3458. } else if (reg_is_pkt_pointer(reg)) {
  3459. if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
  3460. verbose(env, "cannot write into packet\n");
  3461. return -EACCES;
  3462. }
  3463. if (t == BPF_WRITE && value_regno >= 0 &&
  3464. is_pointer_value(env, value_regno)) {
  3465. verbose(env, "R%d leaks addr into packet\n",
  3466. value_regno);
  3467. return -EACCES;
  3468. }
  3469. err = check_packet_access(env, regno, off, size, false);
  3470. if (!err && t == BPF_READ && value_regno >= 0)
  3471. mark_reg_unknown(env, regs, value_regno);
  3472. } else if (reg->type == PTR_TO_FLOW_KEYS) {
  3473. if (t == BPF_WRITE && value_regno >= 0 &&
  3474. is_pointer_value(env, value_regno)) {
  3475. verbose(env, "R%d leaks addr into flow keys\n",
  3476. value_regno);
  3477. return -EACCES;
  3478. }
  3479. err = check_flow_keys_access(env, off, size);
  3480. if (!err && t == BPF_READ && value_regno >= 0)
  3481. mark_reg_unknown(env, regs, value_regno);
  3482. } else if (type_is_sk_pointer(reg->type)) {
  3483. if (t == BPF_WRITE) {
  3484. verbose(env, "R%d cannot write into %s\n",
  3485. regno, reg_type_str[reg->type]);
  3486. return -EACCES;
  3487. }
  3488. err = check_sock_access(env, insn_idx, regno, off, size, t);
  3489. if (!err && value_regno >= 0)
  3490. mark_reg_unknown(env, regs, value_regno);
  3491. } else if (reg->type == PTR_TO_TP_BUFFER) {
  3492. err = check_tp_buffer_access(env, reg, regno, off, size);
  3493. if (!err && t == BPF_READ && value_regno >= 0)
  3494. mark_reg_unknown(env, regs, value_regno);
  3495. } else if (reg->type == PTR_TO_BTF_ID) {
  3496. err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
  3497. value_regno);
  3498. } else if (reg->type == CONST_PTR_TO_MAP) {
  3499. err = check_ptr_to_map_access(env, regs, regno, off, size, t,
  3500. value_regno);
  3501. } else if (reg->type == PTR_TO_RDONLY_BUF) {
  3502. if (t == BPF_WRITE) {
  3503. verbose(env, "R%d cannot write into %s\n",
  3504. regno, reg_type_str[reg->type]);
  3505. return -EACCES;
  3506. }
  3507. err = check_buffer_access(env, reg, regno, off, size, false,
  3508. "rdonly",
  3509. &env->prog->aux->max_rdonly_access);
  3510. if (!err && value_regno >= 0)
  3511. mark_reg_unknown(env, regs, value_regno);
  3512. } else if (reg->type == PTR_TO_RDWR_BUF) {
  3513. err = check_buffer_access(env, reg, regno, off, size, false,
  3514. "rdwr",
  3515. &env->prog->aux->max_rdwr_access);
  3516. if (!err && t == BPF_READ && value_regno >= 0)
  3517. mark_reg_unknown(env, regs, value_regno);
  3518. } else {
  3519. verbose(env, "R%d invalid mem access '%s'\n", regno,
  3520. reg_type_str[reg->type]);
  3521. return -EACCES;
  3522. }
  3523. if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
  3524. regs[value_regno].type == SCALAR_VALUE) {
  3525. /* b/h/w load zero-extends, mark upper bits as known 0 */
  3526. coerce_reg_to_size(&regs[value_regno], size);
  3527. }
  3528. return err;
  3529. }
  3530. static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
  3531. {
  3532. int err;
  3533. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  3534. insn->imm != 0) {
  3535. verbose(env, "BPF_XADD uses reserved fields\n");
  3536. return -EINVAL;
  3537. }
  3538. /* check src1 operand */
  3539. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  3540. if (err)
  3541. return err;
  3542. /* check src2 operand */
  3543. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  3544. if (err)
  3545. return err;
  3546. if (is_pointer_value(env, insn->src_reg)) {
  3547. verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
  3548. return -EACCES;
  3549. }
  3550. if (is_ctx_reg(env, insn->dst_reg) ||
  3551. is_pkt_reg(env, insn->dst_reg) ||
  3552. is_flow_key_reg(env, insn->dst_reg) ||
  3553. is_sk_reg(env, insn->dst_reg)) {
  3554. verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
  3555. insn->dst_reg,
  3556. reg_type_str[reg_state(env, insn->dst_reg)->type]);
  3557. return -EACCES;
  3558. }
  3559. /* check whether atomic_add can read the memory */
  3560. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  3561. BPF_SIZE(insn->code), BPF_READ, -1, true);
  3562. if (err)
  3563. return err;
  3564. /* check whether atomic_add can write into the same memory */
  3565. return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  3566. BPF_SIZE(insn->code), BPF_WRITE, -1, true);
  3567. }
  3568. /* When register 'regno' is used to read the stack (either directly or through
  3569. * a helper function) make sure that it's within stack boundary and, depending
  3570. * on the access type, that all elements of the stack are initialized.
  3571. *
  3572. * 'off' includes 'regno->off', but not its dynamic part (if any).
  3573. *
  3574. * All registers that have been spilled on the stack in the slots within the
  3575. * read offsets are marked as read.
  3576. */
  3577. static int check_stack_range_initialized(
  3578. struct bpf_verifier_env *env, int regno, int off,
  3579. int access_size, bool zero_size_allowed,
  3580. enum stack_access_src type, struct bpf_call_arg_meta *meta)
  3581. {
  3582. struct bpf_reg_state *reg = reg_state(env, regno);
  3583. struct bpf_func_state *state = func(env, reg);
  3584. int err, min_off, max_off, i, j, slot, spi;
  3585. char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
  3586. enum bpf_access_type bounds_check_type;
  3587. /* Some accesses can write anything into the stack, others are
  3588. * read-only.
  3589. */
  3590. bool clobber = false;
  3591. if (access_size == 0 && !zero_size_allowed) {
  3592. verbose(env, "invalid zero-sized read\n");
  3593. return -EACCES;
  3594. }
  3595. if (type == ACCESS_HELPER) {
  3596. /* The bounds checks for writes are more permissive than for
  3597. * reads. However, if raw_mode is not set, we'll do extra
  3598. * checks below.
  3599. */
  3600. bounds_check_type = BPF_WRITE;
  3601. clobber = true;
  3602. } else {
  3603. bounds_check_type = BPF_READ;
  3604. }
  3605. err = check_stack_access_within_bounds(env, regno, off, access_size,
  3606. type, bounds_check_type);
  3607. if (err)
  3608. return err;
  3609. if (tnum_is_const(reg->var_off)) {
  3610. min_off = max_off = reg->var_off.value + off;
  3611. } else {
  3612. /* Variable offset is prohibited for unprivileged mode for
  3613. * simplicity since it requires corresponding support in
  3614. * Spectre masking for stack ALU.
  3615. * See also retrieve_ptr_limit().
  3616. */
  3617. if (!env->bypass_spec_v1) {
  3618. char tn_buf[48];
  3619. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  3620. verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
  3621. regno, err_extra, tn_buf);
  3622. return -EACCES;
  3623. }
  3624. /* Only initialized buffer on stack is allowed to be accessed
  3625. * with variable offset. With uninitialized buffer it's hard to
  3626. * guarantee that whole memory is marked as initialized on
  3627. * helper return since specific bounds are unknown what may
  3628. * cause uninitialized stack leaking.
  3629. */
  3630. if (meta && meta->raw_mode)
  3631. meta = NULL;
  3632. min_off = reg->smin_value + off;
  3633. max_off = reg->smax_value + off;
  3634. }
  3635. if (meta && meta->raw_mode) {
  3636. meta->access_size = access_size;
  3637. meta->regno = regno;
  3638. return 0;
  3639. }
  3640. for (i = min_off; i < max_off + access_size; i++) {
  3641. u8 *stype;
  3642. slot = -i - 1;
  3643. spi = slot / BPF_REG_SIZE;
  3644. if (state->allocated_stack <= slot)
  3645. goto err;
  3646. stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
  3647. if (*stype == STACK_MISC)
  3648. goto mark;
  3649. if (*stype == STACK_ZERO) {
  3650. if (clobber) {
  3651. /* helper can write anything into the stack */
  3652. *stype = STACK_MISC;
  3653. }
  3654. goto mark;
  3655. }
  3656. if (state->stack[spi].slot_type[0] == STACK_SPILL &&
  3657. state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
  3658. goto mark;
  3659. if (state->stack[spi].slot_type[0] == STACK_SPILL &&
  3660. (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
  3661. env->allow_ptr_leaks)) {
  3662. if (clobber) {
  3663. __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
  3664. for (j = 0; j < BPF_REG_SIZE; j++)
  3665. state->stack[spi].slot_type[j] = STACK_MISC;
  3666. }
  3667. goto mark;
  3668. }
  3669. err:
  3670. if (tnum_is_const(reg->var_off)) {
  3671. verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
  3672. err_extra, regno, min_off, i - min_off, access_size);
  3673. } else {
  3674. char tn_buf[48];
  3675. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  3676. verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
  3677. err_extra, regno, tn_buf, i - min_off, access_size);
  3678. }
  3679. return -EACCES;
  3680. mark:
  3681. /* reading any byte out of 8-byte 'spill_slot' will cause
  3682. * the whole slot to be marked as 'read'
  3683. */
  3684. mark_reg_read(env, &state->stack[spi].spilled_ptr,
  3685. state->stack[spi].spilled_ptr.parent,
  3686. REG_LIVE_READ64);
  3687. }
  3688. return update_stack_depth(env, state, min_off);
  3689. }
  3690. static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
  3691. int access_size, bool zero_size_allowed,
  3692. struct bpf_call_arg_meta *meta)
  3693. {
  3694. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  3695. switch (reg->type) {
  3696. case PTR_TO_PACKET:
  3697. case PTR_TO_PACKET_META:
  3698. return check_packet_access(env, regno, reg->off, access_size,
  3699. zero_size_allowed);
  3700. case PTR_TO_MAP_VALUE:
  3701. if (check_map_access_type(env, regno, reg->off, access_size,
  3702. meta && meta->raw_mode ? BPF_WRITE :
  3703. BPF_READ))
  3704. return -EACCES;
  3705. return check_map_access(env, regno, reg->off, access_size,
  3706. zero_size_allowed);
  3707. case PTR_TO_MEM:
  3708. return check_mem_region_access(env, regno, reg->off,
  3709. access_size, reg->mem_size,
  3710. zero_size_allowed);
  3711. case PTR_TO_RDONLY_BUF:
  3712. if (meta && meta->raw_mode)
  3713. return -EACCES;
  3714. return check_buffer_access(env, reg, regno, reg->off,
  3715. access_size, zero_size_allowed,
  3716. "rdonly",
  3717. &env->prog->aux->max_rdonly_access);
  3718. case PTR_TO_RDWR_BUF:
  3719. return check_buffer_access(env, reg, regno, reg->off,
  3720. access_size, zero_size_allowed,
  3721. "rdwr",
  3722. &env->prog->aux->max_rdwr_access);
  3723. case PTR_TO_STACK:
  3724. return check_stack_range_initialized(
  3725. env,
  3726. regno, reg->off, access_size,
  3727. zero_size_allowed, ACCESS_HELPER, meta);
  3728. default: /* scalar_value or invalid ptr */
  3729. /* Allow zero-byte read from NULL, regardless of pointer type */
  3730. if (zero_size_allowed && access_size == 0 &&
  3731. register_is_null(reg))
  3732. return 0;
  3733. verbose(env, "R%d type=%s expected=%s\n", regno,
  3734. reg_type_str[reg->type],
  3735. reg_type_str[PTR_TO_STACK]);
  3736. return -EACCES;
  3737. }
  3738. }
  3739. /* Implementation details:
  3740. * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
  3741. * Two bpf_map_lookups (even with the same key) will have different reg->id.
  3742. * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
  3743. * value_or_null->value transition, since the verifier only cares about
  3744. * the range of access to valid map value pointer and doesn't care about actual
  3745. * address of the map element.
  3746. * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
  3747. * reg->id > 0 after value_or_null->value transition. By doing so
  3748. * two bpf_map_lookups will be considered two different pointers that
  3749. * point to different bpf_spin_locks.
  3750. * The verifier allows taking only one bpf_spin_lock at a time to avoid
  3751. * dead-locks.
  3752. * Since only one bpf_spin_lock is allowed the checks are simpler than
  3753. * reg_is_refcounted() logic. The verifier needs to remember only
  3754. * one spin_lock instead of array of acquired_refs.
  3755. * cur_state->active_spin_lock remembers which map value element got locked
  3756. * and clears it after bpf_spin_unlock.
  3757. */
  3758. static int process_spin_lock(struct bpf_verifier_env *env, int regno,
  3759. bool is_lock)
  3760. {
  3761. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  3762. struct bpf_verifier_state *cur = env->cur_state;
  3763. bool is_const = tnum_is_const(reg->var_off);
  3764. struct bpf_map *map = reg->map_ptr;
  3765. u64 val = reg->var_off.value;
  3766. if (!is_const) {
  3767. verbose(env,
  3768. "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
  3769. regno);
  3770. return -EINVAL;
  3771. }
  3772. if (!map->btf) {
  3773. verbose(env,
  3774. "map '%s' has to have BTF in order to use bpf_spin_lock\n",
  3775. map->name);
  3776. return -EINVAL;
  3777. }
  3778. if (!map_value_has_spin_lock(map)) {
  3779. if (map->spin_lock_off == -E2BIG)
  3780. verbose(env,
  3781. "map '%s' has more than one 'struct bpf_spin_lock'\n",
  3782. map->name);
  3783. else if (map->spin_lock_off == -ENOENT)
  3784. verbose(env,
  3785. "map '%s' doesn't have 'struct bpf_spin_lock'\n",
  3786. map->name);
  3787. else
  3788. verbose(env,
  3789. "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
  3790. map->name);
  3791. return -EINVAL;
  3792. }
  3793. if (map->spin_lock_off != val + reg->off) {
  3794. verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
  3795. val + reg->off);
  3796. return -EINVAL;
  3797. }
  3798. if (is_lock) {
  3799. if (cur->active_spin_lock) {
  3800. verbose(env,
  3801. "Locking two bpf_spin_locks are not allowed\n");
  3802. return -EINVAL;
  3803. }
  3804. cur->active_spin_lock = reg->id;
  3805. } else {
  3806. if (!cur->active_spin_lock) {
  3807. verbose(env, "bpf_spin_unlock without taking a lock\n");
  3808. return -EINVAL;
  3809. }
  3810. if (cur->active_spin_lock != reg->id) {
  3811. verbose(env, "bpf_spin_unlock of different lock\n");
  3812. return -EINVAL;
  3813. }
  3814. cur->active_spin_lock = 0;
  3815. }
  3816. return 0;
  3817. }
  3818. static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
  3819. {
  3820. return type == ARG_PTR_TO_MEM ||
  3821. type == ARG_PTR_TO_MEM_OR_NULL ||
  3822. type == ARG_PTR_TO_UNINIT_MEM;
  3823. }
  3824. static bool arg_type_is_mem_size(enum bpf_arg_type type)
  3825. {
  3826. return type == ARG_CONST_SIZE ||
  3827. type == ARG_CONST_SIZE_OR_ZERO;
  3828. }
  3829. static bool arg_type_is_alloc_size(enum bpf_arg_type type)
  3830. {
  3831. return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
  3832. }
  3833. static bool arg_type_is_int_ptr(enum bpf_arg_type type)
  3834. {
  3835. return type == ARG_PTR_TO_INT ||
  3836. type == ARG_PTR_TO_LONG;
  3837. }
  3838. static int int_ptr_type_to_size(enum bpf_arg_type type)
  3839. {
  3840. if (type == ARG_PTR_TO_INT)
  3841. return sizeof(u32);
  3842. else if (type == ARG_PTR_TO_LONG)
  3843. return sizeof(u64);
  3844. return -EINVAL;
  3845. }
  3846. static int resolve_map_arg_type(struct bpf_verifier_env *env,
  3847. const struct bpf_call_arg_meta *meta,
  3848. enum bpf_arg_type *arg_type)
  3849. {
  3850. if (!meta->map_ptr) {
  3851. /* kernel subsystem misconfigured verifier */
  3852. verbose(env, "invalid map_ptr to access map->type\n");
  3853. return -EACCES;
  3854. }
  3855. switch (meta->map_ptr->map_type) {
  3856. case BPF_MAP_TYPE_SOCKMAP:
  3857. case BPF_MAP_TYPE_SOCKHASH:
  3858. if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
  3859. *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
  3860. } else {
  3861. verbose(env, "invalid arg_type for sockmap/sockhash\n");
  3862. return -EINVAL;
  3863. }
  3864. break;
  3865. default:
  3866. break;
  3867. }
  3868. return 0;
  3869. }
  3870. struct bpf_reg_types {
  3871. const enum bpf_reg_type types[10];
  3872. u32 *btf_id;
  3873. };
  3874. static const struct bpf_reg_types map_key_value_types = {
  3875. .types = {
  3876. PTR_TO_STACK,
  3877. PTR_TO_PACKET,
  3878. PTR_TO_PACKET_META,
  3879. PTR_TO_MAP_VALUE,
  3880. },
  3881. };
  3882. static const struct bpf_reg_types sock_types = {
  3883. .types = {
  3884. PTR_TO_SOCK_COMMON,
  3885. PTR_TO_SOCKET,
  3886. PTR_TO_TCP_SOCK,
  3887. PTR_TO_XDP_SOCK,
  3888. },
  3889. };
  3890. #ifdef CONFIG_NET
  3891. static const struct bpf_reg_types btf_id_sock_common_types = {
  3892. .types = {
  3893. PTR_TO_SOCK_COMMON,
  3894. PTR_TO_SOCKET,
  3895. PTR_TO_TCP_SOCK,
  3896. PTR_TO_XDP_SOCK,
  3897. PTR_TO_BTF_ID,
  3898. },
  3899. .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
  3900. };
  3901. #endif
  3902. static const struct bpf_reg_types mem_types = {
  3903. .types = {
  3904. PTR_TO_STACK,
  3905. PTR_TO_PACKET,
  3906. PTR_TO_PACKET_META,
  3907. PTR_TO_MAP_VALUE,
  3908. PTR_TO_MEM,
  3909. PTR_TO_RDONLY_BUF,
  3910. PTR_TO_RDWR_BUF,
  3911. },
  3912. };
  3913. static const struct bpf_reg_types int_ptr_types = {
  3914. .types = {
  3915. PTR_TO_STACK,
  3916. PTR_TO_PACKET,
  3917. PTR_TO_PACKET_META,
  3918. PTR_TO_MAP_VALUE,
  3919. },
  3920. };
  3921. static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
  3922. static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
  3923. static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
  3924. static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
  3925. static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
  3926. static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
  3927. static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
  3928. static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
  3929. static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
  3930. [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
  3931. [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
  3932. [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
  3933. [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
  3934. [ARG_CONST_SIZE] = &scalar_types,
  3935. [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
  3936. [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
  3937. [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
  3938. [ARG_PTR_TO_CTX] = &context_types,
  3939. [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
  3940. [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
  3941. #ifdef CONFIG_NET
  3942. [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
  3943. #endif
  3944. [ARG_PTR_TO_SOCKET] = &fullsock_types,
  3945. [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
  3946. [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
  3947. [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
  3948. [ARG_PTR_TO_MEM] = &mem_types,
  3949. [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
  3950. [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
  3951. [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
  3952. [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
  3953. [ARG_PTR_TO_INT] = &int_ptr_types,
  3954. [ARG_PTR_TO_LONG] = &int_ptr_types,
  3955. [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
  3956. };
  3957. static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
  3958. enum bpf_arg_type arg_type,
  3959. const u32 *arg_btf_id)
  3960. {
  3961. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  3962. enum bpf_reg_type expected, type = reg->type;
  3963. const struct bpf_reg_types *compatible;
  3964. int i, j;
  3965. compatible = compatible_reg_types[arg_type];
  3966. if (!compatible) {
  3967. verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
  3968. return -EFAULT;
  3969. }
  3970. for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
  3971. expected = compatible->types[i];
  3972. if (expected == NOT_INIT)
  3973. break;
  3974. if (type == expected)
  3975. goto found;
  3976. }
  3977. verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
  3978. for (j = 0; j + 1 < i; j++)
  3979. verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
  3980. verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
  3981. return -EACCES;
  3982. found:
  3983. if (type == PTR_TO_BTF_ID) {
  3984. if (!arg_btf_id) {
  3985. if (!compatible->btf_id) {
  3986. verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
  3987. return -EFAULT;
  3988. }
  3989. arg_btf_id = compatible->btf_id;
  3990. }
  3991. if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
  3992. *arg_btf_id)) {
  3993. verbose(env, "R%d is of type %s but %s is expected\n",
  3994. regno, kernel_type_name(reg->btf_id),
  3995. kernel_type_name(*arg_btf_id));
  3996. return -EACCES;
  3997. }
  3998. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  3999. verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
  4000. regno);
  4001. return -EACCES;
  4002. }
  4003. }
  4004. return 0;
  4005. }
  4006. static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
  4007. struct bpf_call_arg_meta *meta,
  4008. const struct bpf_func_proto *fn)
  4009. {
  4010. u32 regno = BPF_REG_1 + arg;
  4011. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  4012. enum bpf_arg_type arg_type = fn->arg_type[arg];
  4013. enum bpf_reg_type type = reg->type;
  4014. int err = 0;
  4015. if (arg_type == ARG_DONTCARE)
  4016. return 0;
  4017. err = check_reg_arg(env, regno, SRC_OP);
  4018. if (err)
  4019. return err;
  4020. if (arg_type == ARG_ANYTHING) {
  4021. if (is_pointer_value(env, regno)) {
  4022. verbose(env, "R%d leaks addr into helper function\n",
  4023. regno);
  4024. return -EACCES;
  4025. }
  4026. return 0;
  4027. }
  4028. if (type_is_pkt_pointer(type) &&
  4029. !may_access_direct_pkt_data(env, meta, BPF_READ)) {
  4030. verbose(env, "helper access to the packet is not allowed\n");
  4031. return -EACCES;
  4032. }
  4033. if (arg_type == ARG_PTR_TO_MAP_VALUE ||
  4034. arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
  4035. arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
  4036. err = resolve_map_arg_type(env, meta, &arg_type);
  4037. if (err)
  4038. return err;
  4039. }
  4040. if (register_is_null(reg) && arg_type_may_be_null(arg_type))
  4041. /* A NULL register has a SCALAR_VALUE type, so skip
  4042. * type checking.
  4043. */
  4044. goto skip_type_check;
  4045. err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
  4046. if (err)
  4047. return err;
  4048. if (type == PTR_TO_CTX) {
  4049. err = check_ctx_reg(env, reg, regno);
  4050. if (err < 0)
  4051. return err;
  4052. }
  4053. skip_type_check:
  4054. if (reg->ref_obj_id) {
  4055. if (meta->ref_obj_id) {
  4056. verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
  4057. regno, reg->ref_obj_id,
  4058. meta->ref_obj_id);
  4059. return -EFAULT;
  4060. }
  4061. meta->ref_obj_id = reg->ref_obj_id;
  4062. }
  4063. if (arg_type == ARG_CONST_MAP_PTR) {
  4064. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  4065. meta->map_ptr = reg->map_ptr;
  4066. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  4067. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  4068. * check that [key, key + map->key_size) are within
  4069. * stack limits and initialized
  4070. */
  4071. if (!meta->map_ptr) {
  4072. /* in function declaration map_ptr must come before
  4073. * map_key, so that it's verified and known before
  4074. * we have to check map_key here. Otherwise it means
  4075. * that kernel subsystem misconfigured verifier
  4076. */
  4077. verbose(env, "invalid map_ptr to access map->key\n");
  4078. return -EACCES;
  4079. }
  4080. err = check_helper_mem_access(env, regno,
  4081. meta->map_ptr->key_size, false,
  4082. NULL);
  4083. } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
  4084. (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
  4085. !register_is_null(reg)) ||
  4086. arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
  4087. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  4088. * check [value, value + map->value_size) validity
  4089. */
  4090. if (!meta->map_ptr) {
  4091. /* kernel subsystem misconfigured verifier */
  4092. verbose(env, "invalid map_ptr to access map->value\n");
  4093. return -EACCES;
  4094. }
  4095. meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
  4096. err = check_helper_mem_access(env, regno,
  4097. meta->map_ptr->value_size, false,
  4098. meta);
  4099. } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
  4100. if (!reg->btf_id) {
  4101. verbose(env, "Helper has invalid btf_id in R%d\n", regno);
  4102. return -EACCES;
  4103. }
  4104. meta->ret_btf_id = reg->btf_id;
  4105. } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
  4106. if (meta->func_id == BPF_FUNC_spin_lock) {
  4107. if (process_spin_lock(env, regno, true))
  4108. return -EACCES;
  4109. } else if (meta->func_id == BPF_FUNC_spin_unlock) {
  4110. if (process_spin_lock(env, regno, false))
  4111. return -EACCES;
  4112. } else {
  4113. verbose(env, "verifier internal error\n");
  4114. return -EFAULT;
  4115. }
  4116. } else if (arg_type_is_mem_ptr(arg_type)) {
  4117. /* The access to this pointer is only checked when we hit the
  4118. * next is_mem_size argument below.
  4119. */
  4120. meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
  4121. } else if (arg_type_is_mem_size(arg_type)) {
  4122. bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
  4123. /* This is used to refine r0 return value bounds for helpers
  4124. * that enforce this value as an upper bound on return values.
  4125. * See do_refine_retval_range() for helpers that can refine
  4126. * the return value. C type of helper is u32 so we pull register
  4127. * bound from umax_value however, if negative verifier errors
  4128. * out. Only upper bounds can be learned because retval is an
  4129. * int type and negative retvals are allowed.
  4130. */
  4131. meta->msize_max_value = reg->umax_value;
  4132. /* The register is SCALAR_VALUE; the access check
  4133. * happens using its boundaries.
  4134. */
  4135. if (!tnum_is_const(reg->var_off))
  4136. /* For unprivileged variable accesses, disable raw
  4137. * mode so that the program is required to
  4138. * initialize all the memory that the helper could
  4139. * just partially fill up.
  4140. */
  4141. meta = NULL;
  4142. if (reg->smin_value < 0) {
  4143. verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
  4144. regno);
  4145. return -EACCES;
  4146. }
  4147. if (reg->umin_value == 0) {
  4148. err = check_helper_mem_access(env, regno - 1, 0,
  4149. zero_size_allowed,
  4150. meta);
  4151. if (err)
  4152. return err;
  4153. }
  4154. if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
  4155. verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
  4156. regno);
  4157. return -EACCES;
  4158. }
  4159. err = check_helper_mem_access(env, regno - 1,
  4160. reg->umax_value,
  4161. zero_size_allowed, meta);
  4162. if (!err)
  4163. err = mark_chain_precision(env, regno);
  4164. } else if (arg_type_is_alloc_size(arg_type)) {
  4165. if (!tnum_is_const(reg->var_off)) {
  4166. verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
  4167. regno);
  4168. return -EACCES;
  4169. }
  4170. meta->mem_size = reg->var_off.value;
  4171. } else if (arg_type_is_int_ptr(arg_type)) {
  4172. int size = int_ptr_type_to_size(arg_type);
  4173. err = check_helper_mem_access(env, regno, size, false, meta);
  4174. if (err)
  4175. return err;
  4176. err = check_ptr_alignment(env, reg, 0, size, true);
  4177. }
  4178. return err;
  4179. }
  4180. static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
  4181. {
  4182. enum bpf_attach_type eatype = env->prog->expected_attach_type;
  4183. enum bpf_prog_type type = resolve_prog_type(env->prog);
  4184. if (func_id != BPF_FUNC_map_update_elem)
  4185. return false;
  4186. /* It's not possible to get access to a locked struct sock in these
  4187. * contexts, so updating is safe.
  4188. */
  4189. switch (type) {
  4190. case BPF_PROG_TYPE_TRACING:
  4191. if (eatype == BPF_TRACE_ITER)
  4192. return true;
  4193. break;
  4194. case BPF_PROG_TYPE_SOCKET_FILTER:
  4195. case BPF_PROG_TYPE_SCHED_CLS:
  4196. case BPF_PROG_TYPE_SCHED_ACT:
  4197. case BPF_PROG_TYPE_XDP:
  4198. case BPF_PROG_TYPE_SK_REUSEPORT:
  4199. case BPF_PROG_TYPE_FLOW_DISSECTOR:
  4200. case BPF_PROG_TYPE_SK_LOOKUP:
  4201. return true;
  4202. default:
  4203. break;
  4204. }
  4205. verbose(env, "cannot update sockmap in this context\n");
  4206. return false;
  4207. }
  4208. static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
  4209. {
  4210. return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
  4211. }
  4212. static int check_map_func_compatibility(struct bpf_verifier_env *env,
  4213. struct bpf_map *map, int func_id)
  4214. {
  4215. if (!map)
  4216. return 0;
  4217. /* We need a two way check, first is from map perspective ... */
  4218. switch (map->map_type) {
  4219. case BPF_MAP_TYPE_PROG_ARRAY:
  4220. if (func_id != BPF_FUNC_tail_call)
  4221. goto error;
  4222. break;
  4223. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  4224. if (func_id != BPF_FUNC_perf_event_read &&
  4225. func_id != BPF_FUNC_perf_event_output &&
  4226. func_id != BPF_FUNC_skb_output &&
  4227. func_id != BPF_FUNC_perf_event_read_value &&
  4228. func_id != BPF_FUNC_xdp_output)
  4229. goto error;
  4230. break;
  4231. case BPF_MAP_TYPE_RINGBUF:
  4232. if (func_id != BPF_FUNC_ringbuf_output &&
  4233. func_id != BPF_FUNC_ringbuf_reserve &&
  4234. func_id != BPF_FUNC_ringbuf_query)
  4235. goto error;
  4236. break;
  4237. case BPF_MAP_TYPE_STACK_TRACE:
  4238. if (func_id != BPF_FUNC_get_stackid)
  4239. goto error;
  4240. break;
  4241. case BPF_MAP_TYPE_CGROUP_ARRAY:
  4242. if (func_id != BPF_FUNC_skb_under_cgroup &&
  4243. func_id != BPF_FUNC_current_task_under_cgroup)
  4244. goto error;
  4245. break;
  4246. case BPF_MAP_TYPE_CGROUP_STORAGE:
  4247. case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
  4248. if (func_id != BPF_FUNC_get_local_storage)
  4249. goto error;
  4250. break;
  4251. case BPF_MAP_TYPE_DEVMAP:
  4252. case BPF_MAP_TYPE_DEVMAP_HASH:
  4253. if (func_id != BPF_FUNC_redirect_map &&
  4254. func_id != BPF_FUNC_map_lookup_elem)
  4255. goto error;
  4256. break;
  4257. /* Restrict bpf side of cpumap and xskmap, open when use-cases
  4258. * appear.
  4259. */
  4260. case BPF_MAP_TYPE_CPUMAP:
  4261. if (func_id != BPF_FUNC_redirect_map)
  4262. goto error;
  4263. break;
  4264. case BPF_MAP_TYPE_XSKMAP:
  4265. if (func_id != BPF_FUNC_redirect_map &&
  4266. func_id != BPF_FUNC_map_lookup_elem)
  4267. goto error;
  4268. break;
  4269. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  4270. case BPF_MAP_TYPE_HASH_OF_MAPS:
  4271. if (func_id != BPF_FUNC_map_lookup_elem)
  4272. goto error;
  4273. break;
  4274. case BPF_MAP_TYPE_SOCKMAP:
  4275. if (func_id != BPF_FUNC_sk_redirect_map &&
  4276. func_id != BPF_FUNC_sock_map_update &&
  4277. func_id != BPF_FUNC_map_delete_elem &&
  4278. func_id != BPF_FUNC_msg_redirect_map &&
  4279. func_id != BPF_FUNC_sk_select_reuseport &&
  4280. func_id != BPF_FUNC_map_lookup_elem &&
  4281. !may_update_sockmap(env, func_id))
  4282. goto error;
  4283. break;
  4284. case BPF_MAP_TYPE_SOCKHASH:
  4285. if (func_id != BPF_FUNC_sk_redirect_hash &&
  4286. func_id != BPF_FUNC_sock_hash_update &&
  4287. func_id != BPF_FUNC_map_delete_elem &&
  4288. func_id != BPF_FUNC_msg_redirect_hash &&
  4289. func_id != BPF_FUNC_sk_select_reuseport &&
  4290. func_id != BPF_FUNC_map_lookup_elem &&
  4291. !may_update_sockmap(env, func_id))
  4292. goto error;
  4293. break;
  4294. case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
  4295. if (func_id != BPF_FUNC_sk_select_reuseport)
  4296. goto error;
  4297. break;
  4298. case BPF_MAP_TYPE_QUEUE:
  4299. case BPF_MAP_TYPE_STACK:
  4300. if (func_id != BPF_FUNC_map_peek_elem &&
  4301. func_id != BPF_FUNC_map_pop_elem &&
  4302. func_id != BPF_FUNC_map_push_elem)
  4303. goto error;
  4304. break;
  4305. case BPF_MAP_TYPE_SK_STORAGE:
  4306. if (func_id != BPF_FUNC_sk_storage_get &&
  4307. func_id != BPF_FUNC_sk_storage_delete)
  4308. goto error;
  4309. break;
  4310. case BPF_MAP_TYPE_INODE_STORAGE:
  4311. if (func_id != BPF_FUNC_inode_storage_get &&
  4312. func_id != BPF_FUNC_inode_storage_delete)
  4313. goto error;
  4314. break;
  4315. default:
  4316. break;
  4317. }
  4318. /* ... and second from the function itself. */
  4319. switch (func_id) {
  4320. case BPF_FUNC_tail_call:
  4321. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  4322. goto error;
  4323. if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
  4324. verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
  4325. return -EINVAL;
  4326. }
  4327. break;
  4328. case BPF_FUNC_perf_event_read:
  4329. case BPF_FUNC_perf_event_output:
  4330. case BPF_FUNC_perf_event_read_value:
  4331. case BPF_FUNC_skb_output:
  4332. case BPF_FUNC_xdp_output:
  4333. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  4334. goto error;
  4335. break;
  4336. case BPF_FUNC_ringbuf_output:
  4337. case BPF_FUNC_ringbuf_reserve:
  4338. case BPF_FUNC_ringbuf_query:
  4339. if (map->map_type != BPF_MAP_TYPE_RINGBUF)
  4340. goto error;
  4341. break;
  4342. case BPF_FUNC_get_stackid:
  4343. if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
  4344. goto error;
  4345. break;
  4346. case BPF_FUNC_current_task_under_cgroup:
  4347. case BPF_FUNC_skb_under_cgroup:
  4348. if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
  4349. goto error;
  4350. break;
  4351. case BPF_FUNC_redirect_map:
  4352. if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
  4353. map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
  4354. map->map_type != BPF_MAP_TYPE_CPUMAP &&
  4355. map->map_type != BPF_MAP_TYPE_XSKMAP)
  4356. goto error;
  4357. break;
  4358. case BPF_FUNC_sk_redirect_map:
  4359. case BPF_FUNC_msg_redirect_map:
  4360. case BPF_FUNC_sock_map_update:
  4361. if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
  4362. goto error;
  4363. break;
  4364. case BPF_FUNC_sk_redirect_hash:
  4365. case BPF_FUNC_msg_redirect_hash:
  4366. case BPF_FUNC_sock_hash_update:
  4367. if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
  4368. goto error;
  4369. break;
  4370. case BPF_FUNC_get_local_storage:
  4371. if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
  4372. map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
  4373. goto error;
  4374. break;
  4375. case BPF_FUNC_sk_select_reuseport:
  4376. if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
  4377. map->map_type != BPF_MAP_TYPE_SOCKMAP &&
  4378. map->map_type != BPF_MAP_TYPE_SOCKHASH)
  4379. goto error;
  4380. break;
  4381. case BPF_FUNC_map_peek_elem:
  4382. case BPF_FUNC_map_pop_elem:
  4383. case BPF_FUNC_map_push_elem:
  4384. if (map->map_type != BPF_MAP_TYPE_QUEUE &&
  4385. map->map_type != BPF_MAP_TYPE_STACK)
  4386. goto error;
  4387. break;
  4388. case BPF_FUNC_sk_storage_get:
  4389. case BPF_FUNC_sk_storage_delete:
  4390. if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
  4391. goto error;
  4392. break;
  4393. case BPF_FUNC_inode_storage_get:
  4394. case BPF_FUNC_inode_storage_delete:
  4395. if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
  4396. goto error;
  4397. break;
  4398. default:
  4399. break;
  4400. }
  4401. return 0;
  4402. error:
  4403. verbose(env, "cannot pass map_type %d into func %s#%d\n",
  4404. map->map_type, func_id_name(func_id), func_id);
  4405. return -EINVAL;
  4406. }
  4407. static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
  4408. {
  4409. int count = 0;
  4410. if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
  4411. count++;
  4412. if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
  4413. count++;
  4414. if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
  4415. count++;
  4416. if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
  4417. count++;
  4418. if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
  4419. count++;
  4420. /* We only support one arg being in raw mode at the moment,
  4421. * which is sufficient for the helper functions we have
  4422. * right now.
  4423. */
  4424. return count <= 1;
  4425. }
  4426. static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
  4427. enum bpf_arg_type arg_next)
  4428. {
  4429. return (arg_type_is_mem_ptr(arg_curr) &&
  4430. !arg_type_is_mem_size(arg_next)) ||
  4431. (!arg_type_is_mem_ptr(arg_curr) &&
  4432. arg_type_is_mem_size(arg_next));
  4433. }
  4434. static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
  4435. {
  4436. /* bpf_xxx(..., buf, len) call will access 'len'
  4437. * bytes from memory 'buf'. Both arg types need
  4438. * to be paired, so make sure there's no buggy
  4439. * helper function specification.
  4440. */
  4441. if (arg_type_is_mem_size(fn->arg1_type) ||
  4442. arg_type_is_mem_ptr(fn->arg5_type) ||
  4443. check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
  4444. check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
  4445. check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
  4446. check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
  4447. return false;
  4448. return true;
  4449. }
  4450. static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
  4451. {
  4452. int count = 0;
  4453. if (arg_type_may_be_refcounted(fn->arg1_type))
  4454. count++;
  4455. if (arg_type_may_be_refcounted(fn->arg2_type))
  4456. count++;
  4457. if (arg_type_may_be_refcounted(fn->arg3_type))
  4458. count++;
  4459. if (arg_type_may_be_refcounted(fn->arg4_type))
  4460. count++;
  4461. if (arg_type_may_be_refcounted(fn->arg5_type))
  4462. count++;
  4463. /* A reference acquiring function cannot acquire
  4464. * another refcounted ptr.
  4465. */
  4466. if (may_be_acquire_function(func_id) && count)
  4467. return false;
  4468. /* We only support one arg being unreferenced at the moment,
  4469. * which is sufficient for the helper functions we have right now.
  4470. */
  4471. return count <= 1;
  4472. }
  4473. static bool check_btf_id_ok(const struct bpf_func_proto *fn)
  4474. {
  4475. int i;
  4476. for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
  4477. if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
  4478. return false;
  4479. if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
  4480. return false;
  4481. }
  4482. return true;
  4483. }
  4484. static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
  4485. {
  4486. return check_raw_mode_ok(fn) &&
  4487. check_arg_pair_ok(fn) &&
  4488. check_btf_id_ok(fn) &&
  4489. check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
  4490. }
  4491. /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
  4492. * are now invalid, so turn them into unknown SCALAR_VALUE.
  4493. */
  4494. static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
  4495. struct bpf_func_state *state)
  4496. {
  4497. struct bpf_reg_state *regs = state->regs, *reg;
  4498. int i;
  4499. for (i = 0; i < MAX_BPF_REG; i++)
  4500. if (reg_is_pkt_pointer_any(&regs[i]))
  4501. mark_reg_unknown(env, regs, i);
  4502. bpf_for_each_spilled_reg(i, state, reg) {
  4503. if (!reg)
  4504. continue;
  4505. if (reg_is_pkt_pointer_any(reg))
  4506. __mark_reg_unknown(env, reg);
  4507. }
  4508. }
  4509. static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
  4510. {
  4511. struct bpf_verifier_state *vstate = env->cur_state;
  4512. int i;
  4513. for (i = 0; i <= vstate->curframe; i++)
  4514. __clear_all_pkt_pointers(env, vstate->frame[i]);
  4515. }
  4516. static void release_reg_references(struct bpf_verifier_env *env,
  4517. struct bpf_func_state *state,
  4518. int ref_obj_id)
  4519. {
  4520. struct bpf_reg_state *regs = state->regs, *reg;
  4521. int i;
  4522. for (i = 0; i < MAX_BPF_REG; i++)
  4523. if (regs[i].ref_obj_id == ref_obj_id)
  4524. mark_reg_unknown(env, regs, i);
  4525. bpf_for_each_spilled_reg(i, state, reg) {
  4526. if (!reg)
  4527. continue;
  4528. if (reg->ref_obj_id == ref_obj_id)
  4529. __mark_reg_unknown(env, reg);
  4530. }
  4531. }
  4532. /* The pointer with the specified id has released its reference to kernel
  4533. * resources. Identify all copies of the same pointer and clear the reference.
  4534. */
  4535. static int release_reference(struct bpf_verifier_env *env,
  4536. int ref_obj_id)
  4537. {
  4538. struct bpf_verifier_state *vstate = env->cur_state;
  4539. int err;
  4540. int i;
  4541. err = release_reference_state(cur_func(env), ref_obj_id);
  4542. if (err)
  4543. return err;
  4544. for (i = 0; i <= vstate->curframe; i++)
  4545. release_reg_references(env, vstate->frame[i], ref_obj_id);
  4546. return 0;
  4547. }
  4548. static void clear_caller_saved_regs(struct bpf_verifier_env *env,
  4549. struct bpf_reg_state *regs)
  4550. {
  4551. int i;
  4552. /* after the call registers r0 - r5 were scratched */
  4553. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  4554. mark_reg_not_init(env, regs, caller_saved[i]);
  4555. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  4556. }
  4557. }
  4558. static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  4559. int *insn_idx)
  4560. {
  4561. struct bpf_verifier_state *state = env->cur_state;
  4562. struct bpf_func_info_aux *func_info_aux;
  4563. struct bpf_func_state *caller, *callee;
  4564. int i, err, subprog, target_insn;
  4565. bool is_global = false;
  4566. if (state->curframe + 1 >= MAX_CALL_FRAMES) {
  4567. verbose(env, "the call stack of %d frames is too deep\n",
  4568. state->curframe + 2);
  4569. return -E2BIG;
  4570. }
  4571. target_insn = *insn_idx + insn->imm;
  4572. subprog = find_subprog(env, target_insn + 1);
  4573. if (subprog < 0) {
  4574. verbose(env, "verifier bug. No program starts at insn %d\n",
  4575. target_insn + 1);
  4576. return -EFAULT;
  4577. }
  4578. caller = state->frame[state->curframe];
  4579. if (state->frame[state->curframe + 1]) {
  4580. verbose(env, "verifier bug. Frame %d already allocated\n",
  4581. state->curframe + 1);
  4582. return -EFAULT;
  4583. }
  4584. func_info_aux = env->prog->aux->func_info_aux;
  4585. if (func_info_aux)
  4586. is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
  4587. err = btf_check_func_arg_match(env, subprog, caller->regs);
  4588. if (err == -EFAULT)
  4589. return err;
  4590. if (is_global) {
  4591. if (err) {
  4592. verbose(env, "Caller passes invalid args into func#%d\n",
  4593. subprog);
  4594. return err;
  4595. } else {
  4596. if (env->log.level & BPF_LOG_LEVEL)
  4597. verbose(env,
  4598. "Func#%d is global and valid. Skipping.\n",
  4599. subprog);
  4600. clear_caller_saved_regs(env, caller->regs);
  4601. /* All global functions return a 64-bit SCALAR_VALUE */
  4602. mark_reg_unknown(env, caller->regs, BPF_REG_0);
  4603. caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
  4604. /* continue with next insn after call */
  4605. return 0;
  4606. }
  4607. }
  4608. callee = kzalloc(sizeof(*callee), GFP_KERNEL);
  4609. if (!callee)
  4610. return -ENOMEM;
  4611. state->frame[state->curframe + 1] = callee;
  4612. /* callee cannot access r0, r6 - r9 for reading and has to write
  4613. * into its own stack before reading from it.
  4614. * callee can read/write into caller's stack
  4615. */
  4616. init_func_state(env, callee,
  4617. /* remember the callsite, it will be used by bpf_exit */
  4618. *insn_idx /* callsite */,
  4619. state->curframe + 1 /* frameno within this callchain */,
  4620. subprog /* subprog number within this prog */);
  4621. /* Transfer references to the callee */
  4622. err = transfer_reference_state(callee, caller);
  4623. if (err)
  4624. return err;
  4625. /* copy r1 - r5 args that callee can access. The copy includes parent
  4626. * pointers, which connects us up to the liveness chain
  4627. */
  4628. for (i = BPF_REG_1; i <= BPF_REG_5; i++)
  4629. callee->regs[i] = caller->regs[i];
  4630. clear_caller_saved_regs(env, caller->regs);
  4631. /* only increment it after check_reg_arg() finished */
  4632. state->curframe++;
  4633. /* and go analyze first insn of the callee */
  4634. *insn_idx = target_insn;
  4635. if (env->log.level & BPF_LOG_LEVEL) {
  4636. verbose(env, "caller:\n");
  4637. print_verifier_state(env, caller);
  4638. verbose(env, "callee:\n");
  4639. print_verifier_state(env, callee);
  4640. }
  4641. return 0;
  4642. }
  4643. static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
  4644. {
  4645. struct bpf_verifier_state *state = env->cur_state;
  4646. struct bpf_func_state *caller, *callee;
  4647. struct bpf_reg_state *r0;
  4648. int err;
  4649. callee = state->frame[state->curframe];
  4650. r0 = &callee->regs[BPF_REG_0];
  4651. if (r0->type == PTR_TO_STACK) {
  4652. /* technically it's ok to return caller's stack pointer
  4653. * (or caller's caller's pointer) back to the caller,
  4654. * since these pointers are valid. Only current stack
  4655. * pointer will be invalid as soon as function exits,
  4656. * but let's be conservative
  4657. */
  4658. verbose(env, "cannot return stack pointer to the caller\n");
  4659. return -EINVAL;
  4660. }
  4661. state->curframe--;
  4662. caller = state->frame[state->curframe];
  4663. /* return to the caller whatever r0 had in the callee */
  4664. caller->regs[BPF_REG_0] = *r0;
  4665. /* Transfer references to the caller */
  4666. err = transfer_reference_state(caller, callee);
  4667. if (err)
  4668. return err;
  4669. *insn_idx = callee->callsite + 1;
  4670. if (env->log.level & BPF_LOG_LEVEL) {
  4671. verbose(env, "returning from callee:\n");
  4672. print_verifier_state(env, callee);
  4673. verbose(env, "to caller at %d:\n", *insn_idx);
  4674. print_verifier_state(env, caller);
  4675. }
  4676. /* clear everything in the callee */
  4677. free_func_state(callee);
  4678. state->frame[state->curframe + 1] = NULL;
  4679. return 0;
  4680. }
  4681. static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
  4682. int func_id,
  4683. struct bpf_call_arg_meta *meta)
  4684. {
  4685. struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
  4686. if (ret_type != RET_INTEGER ||
  4687. (func_id != BPF_FUNC_get_stack &&
  4688. func_id != BPF_FUNC_probe_read_str &&
  4689. func_id != BPF_FUNC_probe_read_kernel_str &&
  4690. func_id != BPF_FUNC_probe_read_user_str))
  4691. return;
  4692. ret_reg->smax_value = meta->msize_max_value;
  4693. ret_reg->s32_max_value = meta->msize_max_value;
  4694. ret_reg->smin_value = -MAX_ERRNO;
  4695. ret_reg->s32_min_value = -MAX_ERRNO;
  4696. __reg_deduce_bounds(ret_reg);
  4697. __reg_bound_offset(ret_reg);
  4698. __update_reg_bounds(ret_reg);
  4699. }
  4700. static int
  4701. record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
  4702. int func_id, int insn_idx)
  4703. {
  4704. struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
  4705. struct bpf_map *map = meta->map_ptr;
  4706. if (func_id != BPF_FUNC_tail_call &&
  4707. func_id != BPF_FUNC_map_lookup_elem &&
  4708. func_id != BPF_FUNC_map_update_elem &&
  4709. func_id != BPF_FUNC_map_delete_elem &&
  4710. func_id != BPF_FUNC_map_push_elem &&
  4711. func_id != BPF_FUNC_map_pop_elem &&
  4712. func_id != BPF_FUNC_map_peek_elem)
  4713. return 0;
  4714. if (map == NULL) {
  4715. verbose(env, "kernel subsystem misconfigured verifier\n");
  4716. return -EINVAL;
  4717. }
  4718. /* In case of read-only, some additional restrictions
  4719. * need to be applied in order to prevent altering the
  4720. * state of the map from program side.
  4721. */
  4722. if ((map->map_flags & BPF_F_RDONLY_PROG) &&
  4723. (func_id == BPF_FUNC_map_delete_elem ||
  4724. func_id == BPF_FUNC_map_update_elem ||
  4725. func_id == BPF_FUNC_map_push_elem ||
  4726. func_id == BPF_FUNC_map_pop_elem)) {
  4727. verbose(env, "write into map forbidden\n");
  4728. return -EACCES;
  4729. }
  4730. if (!BPF_MAP_PTR(aux->map_ptr_state))
  4731. bpf_map_ptr_store(aux, meta->map_ptr,
  4732. !meta->map_ptr->bypass_spec_v1);
  4733. else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
  4734. bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
  4735. !meta->map_ptr->bypass_spec_v1);
  4736. return 0;
  4737. }
  4738. static int
  4739. record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
  4740. int func_id, int insn_idx)
  4741. {
  4742. struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
  4743. struct bpf_reg_state *regs = cur_regs(env), *reg;
  4744. struct bpf_map *map = meta->map_ptr;
  4745. struct tnum range;
  4746. u64 val;
  4747. int err;
  4748. if (func_id != BPF_FUNC_tail_call)
  4749. return 0;
  4750. if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
  4751. verbose(env, "kernel subsystem misconfigured verifier\n");
  4752. return -EINVAL;
  4753. }
  4754. range = tnum_range(0, map->max_entries - 1);
  4755. reg = &regs[BPF_REG_3];
  4756. if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
  4757. bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
  4758. return 0;
  4759. }
  4760. err = mark_chain_precision(env, BPF_REG_3);
  4761. if (err)
  4762. return err;
  4763. val = reg->var_off.value;
  4764. if (bpf_map_key_unseen(aux))
  4765. bpf_map_key_store(aux, val);
  4766. else if (!bpf_map_key_poisoned(aux) &&
  4767. bpf_map_key_immediate(aux) != val)
  4768. bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
  4769. return 0;
  4770. }
  4771. static int check_reference_leak(struct bpf_verifier_env *env)
  4772. {
  4773. struct bpf_func_state *state = cur_func(env);
  4774. int i;
  4775. for (i = 0; i < state->acquired_refs; i++) {
  4776. verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
  4777. state->refs[i].id, state->refs[i].insn_idx);
  4778. }
  4779. return state->acquired_refs ? -EINVAL : 0;
  4780. }
  4781. static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
  4782. {
  4783. const struct bpf_func_proto *fn = NULL;
  4784. struct bpf_reg_state *regs;
  4785. struct bpf_call_arg_meta meta;
  4786. bool changes_data;
  4787. int i, err;
  4788. /* find function prototype */
  4789. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  4790. verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
  4791. func_id);
  4792. return -EINVAL;
  4793. }
  4794. if (env->ops->get_func_proto)
  4795. fn = env->ops->get_func_proto(func_id, env->prog);
  4796. if (!fn) {
  4797. verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
  4798. func_id);
  4799. return -EINVAL;
  4800. }
  4801. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  4802. if (!env->prog->gpl_compatible && fn->gpl_only) {
  4803. verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
  4804. return -EINVAL;
  4805. }
  4806. if (fn->allowed && !fn->allowed(env->prog)) {
  4807. verbose(env, "helper call is not allowed in probe\n");
  4808. return -EINVAL;
  4809. }
  4810. /* With LD_ABS/IND some JITs save/restore skb from r1. */
  4811. changes_data = bpf_helper_changes_pkt_data(fn->func);
  4812. if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
  4813. verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
  4814. func_id_name(func_id), func_id);
  4815. return -EINVAL;
  4816. }
  4817. memset(&meta, 0, sizeof(meta));
  4818. meta.pkt_access = fn->pkt_access;
  4819. err = check_func_proto(fn, func_id);
  4820. if (err) {
  4821. verbose(env, "kernel subsystem misconfigured func %s#%d\n",
  4822. func_id_name(func_id), func_id);
  4823. return err;
  4824. }
  4825. meta.func_id = func_id;
  4826. /* check args */
  4827. for (i = 0; i < 5; i++) {
  4828. err = check_func_arg(env, i, &meta, fn);
  4829. if (err)
  4830. return err;
  4831. }
  4832. err = record_func_map(env, &meta, func_id, insn_idx);
  4833. if (err)
  4834. return err;
  4835. err = record_func_key(env, &meta, func_id, insn_idx);
  4836. if (err)
  4837. return err;
  4838. /* Mark slots with STACK_MISC in case of raw mode, stack offset
  4839. * is inferred from register state.
  4840. */
  4841. for (i = 0; i < meta.access_size; i++) {
  4842. err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
  4843. BPF_WRITE, -1, false);
  4844. if (err)
  4845. return err;
  4846. }
  4847. if (func_id == BPF_FUNC_tail_call) {
  4848. err = check_reference_leak(env);
  4849. if (err) {
  4850. verbose(env, "tail_call would lead to reference leak\n");
  4851. return err;
  4852. }
  4853. } else if (is_release_function(func_id)) {
  4854. err = release_reference(env, meta.ref_obj_id);
  4855. if (err) {
  4856. verbose(env, "func %s#%d reference has not been acquired before\n",
  4857. func_id_name(func_id), func_id);
  4858. return err;
  4859. }
  4860. }
  4861. regs = cur_regs(env);
  4862. /* check that flags argument in get_local_storage(map, flags) is 0,
  4863. * this is required because get_local_storage() can't return an error.
  4864. */
  4865. if (func_id == BPF_FUNC_get_local_storage &&
  4866. !register_is_null(&regs[BPF_REG_2])) {
  4867. verbose(env, "get_local_storage() doesn't support non-zero flags\n");
  4868. return -EINVAL;
  4869. }
  4870. /* reset caller saved regs */
  4871. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  4872. mark_reg_not_init(env, regs, caller_saved[i]);
  4873. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  4874. }
  4875. /* helper call returns 64-bit value. */
  4876. regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
  4877. /* update return register (already marked as written above) */
  4878. if (fn->ret_type == RET_INTEGER) {
  4879. /* sets type to SCALAR_VALUE */
  4880. mark_reg_unknown(env, regs, BPF_REG_0);
  4881. } else if (fn->ret_type == RET_VOID) {
  4882. regs[BPF_REG_0].type = NOT_INIT;
  4883. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
  4884. fn->ret_type == RET_PTR_TO_MAP_VALUE) {
  4885. /* There is no offset yet applied, variable or fixed */
  4886. mark_reg_known_zero(env, regs, BPF_REG_0);
  4887. /* remember map_ptr, so that check_map_access()
  4888. * can check 'value_size' boundary of memory access
  4889. * to map element returned from bpf_map_lookup_elem()
  4890. */
  4891. if (meta.map_ptr == NULL) {
  4892. verbose(env,
  4893. "kernel subsystem misconfigured verifier\n");
  4894. return -EINVAL;
  4895. }
  4896. regs[BPF_REG_0].map_ptr = meta.map_ptr;
  4897. if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
  4898. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
  4899. if (map_value_has_spin_lock(meta.map_ptr))
  4900. regs[BPF_REG_0].id = ++env->id_gen;
  4901. } else {
  4902. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  4903. }
  4904. } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
  4905. mark_reg_known_zero(env, regs, BPF_REG_0);
  4906. regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
  4907. } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
  4908. mark_reg_known_zero(env, regs, BPF_REG_0);
  4909. regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
  4910. } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
  4911. mark_reg_known_zero(env, regs, BPF_REG_0);
  4912. regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
  4913. } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
  4914. mark_reg_known_zero(env, regs, BPF_REG_0);
  4915. regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
  4916. regs[BPF_REG_0].mem_size = meta.mem_size;
  4917. } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
  4918. fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
  4919. const struct btf_type *t;
  4920. mark_reg_known_zero(env, regs, BPF_REG_0);
  4921. t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
  4922. if (!btf_type_is_struct(t)) {
  4923. u32 tsize;
  4924. const struct btf_type *ret;
  4925. const char *tname;
  4926. /* resolve the type size of ksym. */
  4927. ret = btf_resolve_size(btf_vmlinux, t, &tsize);
  4928. if (IS_ERR(ret)) {
  4929. tname = btf_name_by_offset(btf_vmlinux, t->name_off);
  4930. verbose(env, "unable to resolve the size of type '%s': %ld\n",
  4931. tname, PTR_ERR(ret));
  4932. return -EINVAL;
  4933. }
  4934. regs[BPF_REG_0].type =
  4935. fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
  4936. PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
  4937. regs[BPF_REG_0].mem_size = tsize;
  4938. } else {
  4939. regs[BPF_REG_0].type =
  4940. fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
  4941. PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
  4942. regs[BPF_REG_0].btf_id = meta.ret_btf_id;
  4943. }
  4944. } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
  4945. int ret_btf_id;
  4946. mark_reg_known_zero(env, regs, BPF_REG_0);
  4947. regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
  4948. ret_btf_id = *fn->ret_btf_id;
  4949. if (ret_btf_id == 0) {
  4950. verbose(env, "invalid return type %d of func %s#%d\n",
  4951. fn->ret_type, func_id_name(func_id), func_id);
  4952. return -EINVAL;
  4953. }
  4954. regs[BPF_REG_0].btf_id = ret_btf_id;
  4955. } else {
  4956. verbose(env, "unknown return type %d of func %s#%d\n",
  4957. fn->ret_type, func_id_name(func_id), func_id);
  4958. return -EINVAL;
  4959. }
  4960. if (reg_type_may_be_null(regs[BPF_REG_0].type))
  4961. regs[BPF_REG_0].id = ++env->id_gen;
  4962. if (is_ptr_cast_function(func_id)) {
  4963. /* For release_reference() */
  4964. regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
  4965. } else if (is_acquire_function(func_id, meta.map_ptr)) {
  4966. int id = acquire_reference_state(env, insn_idx);
  4967. if (id < 0)
  4968. return id;
  4969. /* For mark_ptr_or_null_reg() */
  4970. regs[BPF_REG_0].id = id;
  4971. /* For release_reference() */
  4972. regs[BPF_REG_0].ref_obj_id = id;
  4973. }
  4974. do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
  4975. err = check_map_func_compatibility(env, meta.map_ptr, func_id);
  4976. if (err)
  4977. return err;
  4978. if ((func_id == BPF_FUNC_get_stack ||
  4979. func_id == BPF_FUNC_get_task_stack) &&
  4980. !env->prog->has_callchain_buf) {
  4981. const char *err_str;
  4982. #ifdef CONFIG_PERF_EVENTS
  4983. err = get_callchain_buffers(sysctl_perf_event_max_stack);
  4984. err_str = "cannot get callchain buffer for func %s#%d\n";
  4985. #else
  4986. err = -ENOTSUPP;
  4987. err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
  4988. #endif
  4989. if (err) {
  4990. verbose(env, err_str, func_id_name(func_id), func_id);
  4991. return err;
  4992. }
  4993. env->prog->has_callchain_buf = true;
  4994. }
  4995. if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
  4996. env->prog->call_get_stack = true;
  4997. if (changes_data)
  4998. clear_all_pkt_pointers(env);
  4999. return 0;
  5000. }
  5001. static bool signed_add_overflows(s64 a, s64 b)
  5002. {
  5003. /* Do the add in u64, where overflow is well-defined */
  5004. s64 res = (s64)((u64)a + (u64)b);
  5005. if (b < 0)
  5006. return res > a;
  5007. return res < a;
  5008. }
  5009. static bool signed_add32_overflows(s32 a, s32 b)
  5010. {
  5011. /* Do the add in u32, where overflow is well-defined */
  5012. s32 res = (s32)((u32)a + (u32)b);
  5013. if (b < 0)
  5014. return res > a;
  5015. return res < a;
  5016. }
  5017. static bool signed_sub_overflows(s64 a, s64 b)
  5018. {
  5019. /* Do the sub in u64, where overflow is well-defined */
  5020. s64 res = (s64)((u64)a - (u64)b);
  5021. if (b < 0)
  5022. return res < a;
  5023. return res > a;
  5024. }
  5025. static bool signed_sub32_overflows(s32 a, s32 b)
  5026. {
  5027. /* Do the sub in u32, where overflow is well-defined */
  5028. s32 res = (s32)((u32)a - (u32)b);
  5029. if (b < 0)
  5030. return res < a;
  5031. return res > a;
  5032. }
  5033. static bool check_reg_sane_offset(struct bpf_verifier_env *env,
  5034. const struct bpf_reg_state *reg,
  5035. enum bpf_reg_type type)
  5036. {
  5037. bool known = tnum_is_const(reg->var_off);
  5038. s64 val = reg->var_off.value;
  5039. s64 smin = reg->smin_value;
  5040. if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
  5041. verbose(env, "math between %s pointer and %lld is not allowed\n",
  5042. reg_type_str[type], val);
  5043. return false;
  5044. }
  5045. if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
  5046. verbose(env, "%s pointer offset %d is not allowed\n",
  5047. reg_type_str[type], reg->off);
  5048. return false;
  5049. }
  5050. if (smin == S64_MIN) {
  5051. verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
  5052. reg_type_str[type]);
  5053. return false;
  5054. }
  5055. if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
  5056. verbose(env, "value %lld makes %s pointer be out of bounds\n",
  5057. smin, reg_type_str[type]);
  5058. return false;
  5059. }
  5060. return true;
  5061. }
  5062. static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
  5063. {
  5064. return &env->insn_aux_data[env->insn_idx];
  5065. }
  5066. enum {
  5067. REASON_BOUNDS = -1,
  5068. REASON_TYPE = -2,
  5069. REASON_PATHS = -3,
  5070. REASON_LIMIT = -4,
  5071. REASON_STACK = -5,
  5072. };
  5073. static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
  5074. u32 *alu_limit, bool mask_to_left)
  5075. {
  5076. u32 max = 0, ptr_limit = 0;
  5077. switch (ptr_reg->type) {
  5078. case PTR_TO_STACK:
  5079. /* Offset 0 is out-of-bounds, but acceptable start for the
  5080. * left direction, see BPF_REG_FP. Also, unknown scalar
  5081. * offset where we would need to deal with min/max bounds is
  5082. * currently prohibited for unprivileged.
  5083. */
  5084. max = MAX_BPF_STACK + mask_to_left;
  5085. ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
  5086. break;
  5087. case PTR_TO_MAP_VALUE:
  5088. max = ptr_reg->map_ptr->value_size;
  5089. ptr_limit = (mask_to_left ?
  5090. ptr_reg->smin_value :
  5091. ptr_reg->umax_value) + ptr_reg->off;
  5092. break;
  5093. default:
  5094. return REASON_TYPE;
  5095. }
  5096. if (ptr_limit >= max)
  5097. return REASON_LIMIT;
  5098. *alu_limit = ptr_limit;
  5099. return 0;
  5100. }
  5101. static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
  5102. const struct bpf_insn *insn)
  5103. {
  5104. return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
  5105. }
  5106. static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
  5107. u32 alu_state, u32 alu_limit)
  5108. {
  5109. /* If we arrived here from different branches with different
  5110. * state or limits to sanitize, then this won't work.
  5111. */
  5112. if (aux->alu_state &&
  5113. (aux->alu_state != alu_state ||
  5114. aux->alu_limit != alu_limit))
  5115. return REASON_PATHS;
  5116. /* Corresponding fixup done in fixup_bpf_calls(). */
  5117. aux->alu_state = alu_state;
  5118. aux->alu_limit = alu_limit;
  5119. return 0;
  5120. }
  5121. static int sanitize_val_alu(struct bpf_verifier_env *env,
  5122. struct bpf_insn *insn)
  5123. {
  5124. struct bpf_insn_aux_data *aux = cur_aux(env);
  5125. if (can_skip_alu_sanitation(env, insn))
  5126. return 0;
  5127. return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
  5128. }
  5129. static bool sanitize_needed(u8 opcode)
  5130. {
  5131. return opcode == BPF_ADD || opcode == BPF_SUB;
  5132. }
  5133. struct bpf_sanitize_info {
  5134. struct bpf_insn_aux_data aux;
  5135. bool mask_to_left;
  5136. };
  5137. static struct bpf_verifier_state *
  5138. sanitize_speculative_path(struct bpf_verifier_env *env,
  5139. const struct bpf_insn *insn,
  5140. u32 next_idx, u32 curr_idx)
  5141. {
  5142. struct bpf_verifier_state *branch;
  5143. struct bpf_reg_state *regs;
  5144. branch = push_stack(env, next_idx, curr_idx, true);
  5145. if (branch && insn) {
  5146. regs = branch->frame[branch->curframe]->regs;
  5147. if (BPF_SRC(insn->code) == BPF_K) {
  5148. mark_reg_unknown(env, regs, insn->dst_reg);
  5149. } else if (BPF_SRC(insn->code) == BPF_X) {
  5150. mark_reg_unknown(env, regs, insn->dst_reg);
  5151. mark_reg_unknown(env, regs, insn->src_reg);
  5152. }
  5153. }
  5154. return branch;
  5155. }
  5156. static int sanitize_ptr_alu(struct bpf_verifier_env *env,
  5157. struct bpf_insn *insn,
  5158. const struct bpf_reg_state *ptr_reg,
  5159. const struct bpf_reg_state *off_reg,
  5160. struct bpf_reg_state *dst_reg,
  5161. struct bpf_sanitize_info *info,
  5162. const bool commit_window)
  5163. {
  5164. struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
  5165. struct bpf_verifier_state *vstate = env->cur_state;
  5166. bool off_is_imm = tnum_is_const(off_reg->var_off);
  5167. bool off_is_neg = off_reg->smin_value < 0;
  5168. bool ptr_is_dst_reg = ptr_reg == dst_reg;
  5169. u8 opcode = BPF_OP(insn->code);
  5170. u32 alu_state, alu_limit;
  5171. struct bpf_reg_state tmp;
  5172. bool ret;
  5173. int err;
  5174. if (can_skip_alu_sanitation(env, insn))
  5175. return 0;
  5176. /* We already marked aux for masking from non-speculative
  5177. * paths, thus we got here in the first place. We only care
  5178. * to explore bad access from here.
  5179. */
  5180. if (vstate->speculative)
  5181. goto do_sim;
  5182. if (!commit_window) {
  5183. if (!tnum_is_const(off_reg->var_off) &&
  5184. (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
  5185. return REASON_BOUNDS;
  5186. info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
  5187. (opcode == BPF_SUB && !off_is_neg);
  5188. }
  5189. err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
  5190. if (err < 0)
  5191. return err;
  5192. if (commit_window) {
  5193. /* In commit phase we narrow the masking window based on
  5194. * the observed pointer move after the simulated operation.
  5195. */
  5196. alu_state = info->aux.alu_state;
  5197. alu_limit = abs(info->aux.alu_limit - alu_limit);
  5198. } else {
  5199. alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
  5200. alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
  5201. alu_state |= ptr_is_dst_reg ?
  5202. BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
  5203. /* Limit pruning on unknown scalars to enable deep search for
  5204. * potential masking differences from other program paths.
  5205. */
  5206. if (!off_is_imm)
  5207. env->explore_alu_limits = true;
  5208. }
  5209. err = update_alu_sanitation_state(aux, alu_state, alu_limit);
  5210. if (err < 0)
  5211. return err;
  5212. do_sim:
  5213. /* If we're in commit phase, we're done here given we already
  5214. * pushed the truncated dst_reg into the speculative verification
  5215. * stack.
  5216. *
  5217. * Also, when register is a known constant, we rewrite register-based
  5218. * operation to immediate-based, and thus do not need masking (and as
  5219. * a consequence, do not need to simulate the zero-truncation either).
  5220. */
  5221. if (commit_window || off_is_imm)
  5222. return 0;
  5223. /* Simulate and find potential out-of-bounds access under
  5224. * speculative execution from truncation as a result of
  5225. * masking when off was not within expected range. If off
  5226. * sits in dst, then we temporarily need to move ptr there
  5227. * to simulate dst (== 0) +/-= ptr. Needed, for example,
  5228. * for cases where we use K-based arithmetic in one direction
  5229. * and truncated reg-based in the other in order to explore
  5230. * bad access.
  5231. */
  5232. if (!ptr_is_dst_reg) {
  5233. tmp = *dst_reg;
  5234. *dst_reg = *ptr_reg;
  5235. }
  5236. ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
  5237. env->insn_idx);
  5238. if (!ptr_is_dst_reg && ret)
  5239. *dst_reg = tmp;
  5240. return !ret ? REASON_STACK : 0;
  5241. }
  5242. static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
  5243. {
  5244. struct bpf_verifier_state *vstate = env->cur_state;
  5245. /* If we simulate paths under speculation, we don't update the
  5246. * insn as 'seen' such that when we verify unreachable paths in
  5247. * the non-speculative domain, sanitize_dead_code() can still
  5248. * rewrite/sanitize them.
  5249. */
  5250. if (!vstate->speculative)
  5251. env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
  5252. }
  5253. static int sanitize_err(struct bpf_verifier_env *env,
  5254. const struct bpf_insn *insn, int reason,
  5255. const struct bpf_reg_state *off_reg,
  5256. const struct bpf_reg_state *dst_reg)
  5257. {
  5258. static const char *err = "pointer arithmetic with it prohibited for !root";
  5259. const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
  5260. u32 dst = insn->dst_reg, src = insn->src_reg;
  5261. switch (reason) {
  5262. case REASON_BOUNDS:
  5263. verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
  5264. off_reg == dst_reg ? dst : src, err);
  5265. break;
  5266. case REASON_TYPE:
  5267. verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
  5268. off_reg == dst_reg ? src : dst, err);
  5269. break;
  5270. case REASON_PATHS:
  5271. verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
  5272. dst, op, err);
  5273. break;
  5274. case REASON_LIMIT:
  5275. verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
  5276. dst, op, err);
  5277. break;
  5278. case REASON_STACK:
  5279. verbose(env, "R%d could not be pushed for speculative verification, %s\n",
  5280. dst, err);
  5281. break;
  5282. default:
  5283. verbose(env, "verifier internal error: unknown reason (%d)\n",
  5284. reason);
  5285. break;
  5286. }
  5287. return -EACCES;
  5288. }
  5289. /* check that stack access falls within stack limits and that 'reg' doesn't
  5290. * have a variable offset.
  5291. *
  5292. * Variable offset is prohibited for unprivileged mode for simplicity since it
  5293. * requires corresponding support in Spectre masking for stack ALU. See also
  5294. * retrieve_ptr_limit().
  5295. *
  5296. *
  5297. * 'off' includes 'reg->off'.
  5298. */
  5299. static int check_stack_access_for_ptr_arithmetic(
  5300. struct bpf_verifier_env *env,
  5301. int regno,
  5302. const struct bpf_reg_state *reg,
  5303. int off)
  5304. {
  5305. if (!tnum_is_const(reg->var_off)) {
  5306. char tn_buf[48];
  5307. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  5308. verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
  5309. regno, tn_buf, off);
  5310. return -EACCES;
  5311. }
  5312. if (off >= 0 || off < -MAX_BPF_STACK) {
  5313. verbose(env, "R%d stack pointer arithmetic goes out of range, "
  5314. "prohibited for !root; off=%d\n", regno, off);
  5315. return -EACCES;
  5316. }
  5317. return 0;
  5318. }
  5319. static int sanitize_check_bounds(struct bpf_verifier_env *env,
  5320. const struct bpf_insn *insn,
  5321. const struct bpf_reg_state *dst_reg)
  5322. {
  5323. u32 dst = insn->dst_reg;
  5324. /* For unprivileged we require that resulting offset must be in bounds
  5325. * in order to be able to sanitize access later on.
  5326. */
  5327. if (env->bypass_spec_v1)
  5328. return 0;
  5329. switch (dst_reg->type) {
  5330. case PTR_TO_STACK:
  5331. if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
  5332. dst_reg->off + dst_reg->var_off.value))
  5333. return -EACCES;
  5334. break;
  5335. case PTR_TO_MAP_VALUE:
  5336. if (check_map_access(env, dst, dst_reg->off, 1, false)) {
  5337. verbose(env, "R%d pointer arithmetic of map value goes out of range, "
  5338. "prohibited for !root\n", dst);
  5339. return -EACCES;
  5340. }
  5341. break;
  5342. default:
  5343. break;
  5344. }
  5345. return 0;
  5346. }
  5347. /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
  5348. * Caller should also handle BPF_MOV case separately.
  5349. * If we return -EACCES, caller may want to try again treating pointer as a
  5350. * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
  5351. */
  5352. static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
  5353. struct bpf_insn *insn,
  5354. const struct bpf_reg_state *ptr_reg,
  5355. const struct bpf_reg_state *off_reg)
  5356. {
  5357. struct bpf_verifier_state *vstate = env->cur_state;
  5358. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  5359. struct bpf_reg_state *regs = state->regs, *dst_reg;
  5360. bool known = tnum_is_const(off_reg->var_off);
  5361. s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
  5362. smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
  5363. u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
  5364. umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
  5365. struct bpf_sanitize_info info = {};
  5366. u8 opcode = BPF_OP(insn->code);
  5367. u32 dst = insn->dst_reg;
  5368. int ret;
  5369. dst_reg = &regs[dst];
  5370. if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
  5371. smin_val > smax_val || umin_val > umax_val) {
  5372. /* Taint dst register if offset had invalid bounds derived from
  5373. * e.g. dead branches.
  5374. */
  5375. __mark_reg_unknown(env, dst_reg);
  5376. return 0;
  5377. }
  5378. if (BPF_CLASS(insn->code) != BPF_ALU64) {
  5379. /* 32-bit ALU ops on pointers produce (meaningless) scalars */
  5380. if (opcode == BPF_SUB && env->allow_ptr_leaks) {
  5381. __mark_reg_unknown(env, dst_reg);
  5382. return 0;
  5383. }
  5384. verbose(env,
  5385. "R%d 32-bit pointer arithmetic prohibited\n",
  5386. dst);
  5387. return -EACCES;
  5388. }
  5389. switch (ptr_reg->type) {
  5390. case PTR_TO_MAP_VALUE_OR_NULL:
  5391. verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
  5392. dst, reg_type_str[ptr_reg->type]);
  5393. return -EACCES;
  5394. case CONST_PTR_TO_MAP:
  5395. /* smin_val represents the known value */
  5396. if (known && smin_val == 0 && opcode == BPF_ADD)
  5397. break;
  5398. fallthrough;
  5399. case PTR_TO_PACKET_END:
  5400. case PTR_TO_SOCKET:
  5401. case PTR_TO_SOCK_COMMON:
  5402. case PTR_TO_TCP_SOCK:
  5403. case PTR_TO_XDP_SOCK:
  5404. reject:
  5405. verbose(env, "R%d pointer arithmetic on %s prohibited\n",
  5406. dst, reg_type_str[ptr_reg->type]);
  5407. return -EACCES;
  5408. default:
  5409. if (reg_type_may_be_null(ptr_reg->type))
  5410. goto reject;
  5411. break;
  5412. }
  5413. /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
  5414. * The id may be overwritten later if we create a new variable offset.
  5415. */
  5416. dst_reg->type = ptr_reg->type;
  5417. dst_reg->id = ptr_reg->id;
  5418. if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
  5419. !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
  5420. return -EINVAL;
  5421. /* pointer types do not carry 32-bit bounds at the moment. */
  5422. __mark_reg32_unbounded(dst_reg);
  5423. if (sanitize_needed(opcode)) {
  5424. ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
  5425. &info, false);
  5426. if (ret < 0)
  5427. return sanitize_err(env, insn, ret, off_reg, dst_reg);
  5428. }
  5429. switch (opcode) {
  5430. case BPF_ADD:
  5431. /* We can take a fixed offset as long as it doesn't overflow
  5432. * the s32 'off' field
  5433. */
  5434. if (known && (ptr_reg->off + smin_val ==
  5435. (s64)(s32)(ptr_reg->off + smin_val))) {
  5436. /* pointer += K. Accumulate it into fixed offset */
  5437. dst_reg->smin_value = smin_ptr;
  5438. dst_reg->smax_value = smax_ptr;
  5439. dst_reg->umin_value = umin_ptr;
  5440. dst_reg->umax_value = umax_ptr;
  5441. dst_reg->var_off = ptr_reg->var_off;
  5442. dst_reg->off = ptr_reg->off + smin_val;
  5443. dst_reg->raw = ptr_reg->raw;
  5444. break;
  5445. }
  5446. /* A new variable offset is created. Note that off_reg->off
  5447. * == 0, since it's a scalar.
  5448. * dst_reg gets the pointer type and since some positive
  5449. * integer value was added to the pointer, give it a new 'id'
  5450. * if it's a PTR_TO_PACKET.
  5451. * this creates a new 'base' pointer, off_reg (variable) gets
  5452. * added into the variable offset, and we copy the fixed offset
  5453. * from ptr_reg.
  5454. */
  5455. if (signed_add_overflows(smin_ptr, smin_val) ||
  5456. signed_add_overflows(smax_ptr, smax_val)) {
  5457. dst_reg->smin_value = S64_MIN;
  5458. dst_reg->smax_value = S64_MAX;
  5459. } else {
  5460. dst_reg->smin_value = smin_ptr + smin_val;
  5461. dst_reg->smax_value = smax_ptr + smax_val;
  5462. }
  5463. if (umin_ptr + umin_val < umin_ptr ||
  5464. umax_ptr + umax_val < umax_ptr) {
  5465. dst_reg->umin_value = 0;
  5466. dst_reg->umax_value = U64_MAX;
  5467. } else {
  5468. dst_reg->umin_value = umin_ptr + umin_val;
  5469. dst_reg->umax_value = umax_ptr + umax_val;
  5470. }
  5471. dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
  5472. dst_reg->off = ptr_reg->off;
  5473. dst_reg->raw = ptr_reg->raw;
  5474. if (reg_is_pkt_pointer(ptr_reg)) {
  5475. dst_reg->id = ++env->id_gen;
  5476. /* something was added to pkt_ptr, set range to zero */
  5477. dst_reg->raw = 0;
  5478. }
  5479. break;
  5480. case BPF_SUB:
  5481. if (dst_reg == off_reg) {
  5482. /* scalar -= pointer. Creates an unknown scalar */
  5483. verbose(env, "R%d tried to subtract pointer from scalar\n",
  5484. dst);
  5485. return -EACCES;
  5486. }
  5487. /* We don't allow subtraction from FP, because (according to
  5488. * test_verifier.c test "invalid fp arithmetic", JITs might not
  5489. * be able to deal with it.
  5490. */
  5491. if (ptr_reg->type == PTR_TO_STACK) {
  5492. verbose(env, "R%d subtraction from stack pointer prohibited\n",
  5493. dst);
  5494. return -EACCES;
  5495. }
  5496. if (known && (ptr_reg->off - smin_val ==
  5497. (s64)(s32)(ptr_reg->off - smin_val))) {
  5498. /* pointer -= K. Subtract it from fixed offset */
  5499. dst_reg->smin_value = smin_ptr;
  5500. dst_reg->smax_value = smax_ptr;
  5501. dst_reg->umin_value = umin_ptr;
  5502. dst_reg->umax_value = umax_ptr;
  5503. dst_reg->var_off = ptr_reg->var_off;
  5504. dst_reg->id = ptr_reg->id;
  5505. dst_reg->off = ptr_reg->off - smin_val;
  5506. dst_reg->raw = ptr_reg->raw;
  5507. break;
  5508. }
  5509. /* A new variable offset is created. If the subtrahend is known
  5510. * nonnegative, then any reg->range we had before is still good.
  5511. */
  5512. if (signed_sub_overflows(smin_ptr, smax_val) ||
  5513. signed_sub_overflows(smax_ptr, smin_val)) {
  5514. /* Overflow possible, we know nothing */
  5515. dst_reg->smin_value = S64_MIN;
  5516. dst_reg->smax_value = S64_MAX;
  5517. } else {
  5518. dst_reg->smin_value = smin_ptr - smax_val;
  5519. dst_reg->smax_value = smax_ptr - smin_val;
  5520. }
  5521. if (umin_ptr < umax_val) {
  5522. /* Overflow possible, we know nothing */
  5523. dst_reg->umin_value = 0;
  5524. dst_reg->umax_value = U64_MAX;
  5525. } else {
  5526. /* Cannot overflow (as long as bounds are consistent) */
  5527. dst_reg->umin_value = umin_ptr - umax_val;
  5528. dst_reg->umax_value = umax_ptr - umin_val;
  5529. }
  5530. dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
  5531. dst_reg->off = ptr_reg->off;
  5532. dst_reg->raw = ptr_reg->raw;
  5533. if (reg_is_pkt_pointer(ptr_reg)) {
  5534. dst_reg->id = ++env->id_gen;
  5535. /* something was added to pkt_ptr, set range to zero */
  5536. if (smin_val < 0)
  5537. dst_reg->raw = 0;
  5538. }
  5539. break;
  5540. case BPF_AND:
  5541. case BPF_OR:
  5542. case BPF_XOR:
  5543. /* bitwise ops on pointers are troublesome, prohibit. */
  5544. verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
  5545. dst, bpf_alu_string[opcode >> 4]);
  5546. return -EACCES;
  5547. default:
  5548. /* other operators (e.g. MUL,LSH) produce non-pointer results */
  5549. verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
  5550. dst, bpf_alu_string[opcode >> 4]);
  5551. return -EACCES;
  5552. }
  5553. if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
  5554. return -EINVAL;
  5555. __update_reg_bounds(dst_reg);
  5556. __reg_deduce_bounds(dst_reg);
  5557. __reg_bound_offset(dst_reg);
  5558. if (sanitize_check_bounds(env, insn, dst_reg) < 0)
  5559. return -EACCES;
  5560. if (sanitize_needed(opcode)) {
  5561. ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
  5562. &info, true);
  5563. if (ret < 0)
  5564. return sanitize_err(env, insn, ret, off_reg, dst_reg);
  5565. }
  5566. return 0;
  5567. }
  5568. static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
  5569. struct bpf_reg_state *src_reg)
  5570. {
  5571. s32 smin_val = src_reg->s32_min_value;
  5572. s32 smax_val = src_reg->s32_max_value;
  5573. u32 umin_val = src_reg->u32_min_value;
  5574. u32 umax_val = src_reg->u32_max_value;
  5575. if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
  5576. signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
  5577. dst_reg->s32_min_value = S32_MIN;
  5578. dst_reg->s32_max_value = S32_MAX;
  5579. } else {
  5580. dst_reg->s32_min_value += smin_val;
  5581. dst_reg->s32_max_value += smax_val;
  5582. }
  5583. if (dst_reg->u32_min_value + umin_val < umin_val ||
  5584. dst_reg->u32_max_value + umax_val < umax_val) {
  5585. dst_reg->u32_min_value = 0;
  5586. dst_reg->u32_max_value = U32_MAX;
  5587. } else {
  5588. dst_reg->u32_min_value += umin_val;
  5589. dst_reg->u32_max_value += umax_val;
  5590. }
  5591. }
  5592. static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
  5593. struct bpf_reg_state *src_reg)
  5594. {
  5595. s64 smin_val = src_reg->smin_value;
  5596. s64 smax_val = src_reg->smax_value;
  5597. u64 umin_val = src_reg->umin_value;
  5598. u64 umax_val = src_reg->umax_value;
  5599. if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
  5600. signed_add_overflows(dst_reg->smax_value, smax_val)) {
  5601. dst_reg->smin_value = S64_MIN;
  5602. dst_reg->smax_value = S64_MAX;
  5603. } else {
  5604. dst_reg->smin_value += smin_val;
  5605. dst_reg->smax_value += smax_val;
  5606. }
  5607. if (dst_reg->umin_value + umin_val < umin_val ||
  5608. dst_reg->umax_value + umax_val < umax_val) {
  5609. dst_reg->umin_value = 0;
  5610. dst_reg->umax_value = U64_MAX;
  5611. } else {
  5612. dst_reg->umin_value += umin_val;
  5613. dst_reg->umax_value += umax_val;
  5614. }
  5615. }
  5616. static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
  5617. struct bpf_reg_state *src_reg)
  5618. {
  5619. s32 smin_val = src_reg->s32_min_value;
  5620. s32 smax_val = src_reg->s32_max_value;
  5621. u32 umin_val = src_reg->u32_min_value;
  5622. u32 umax_val = src_reg->u32_max_value;
  5623. if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
  5624. signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
  5625. /* Overflow possible, we know nothing */
  5626. dst_reg->s32_min_value = S32_MIN;
  5627. dst_reg->s32_max_value = S32_MAX;
  5628. } else {
  5629. dst_reg->s32_min_value -= smax_val;
  5630. dst_reg->s32_max_value -= smin_val;
  5631. }
  5632. if (dst_reg->u32_min_value < umax_val) {
  5633. /* Overflow possible, we know nothing */
  5634. dst_reg->u32_min_value = 0;
  5635. dst_reg->u32_max_value = U32_MAX;
  5636. } else {
  5637. /* Cannot overflow (as long as bounds are consistent) */
  5638. dst_reg->u32_min_value -= umax_val;
  5639. dst_reg->u32_max_value -= umin_val;
  5640. }
  5641. }
  5642. static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
  5643. struct bpf_reg_state *src_reg)
  5644. {
  5645. s64 smin_val = src_reg->smin_value;
  5646. s64 smax_val = src_reg->smax_value;
  5647. u64 umin_val = src_reg->umin_value;
  5648. u64 umax_val = src_reg->umax_value;
  5649. if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
  5650. signed_sub_overflows(dst_reg->smax_value, smin_val)) {
  5651. /* Overflow possible, we know nothing */
  5652. dst_reg->smin_value = S64_MIN;
  5653. dst_reg->smax_value = S64_MAX;
  5654. } else {
  5655. dst_reg->smin_value -= smax_val;
  5656. dst_reg->smax_value -= smin_val;
  5657. }
  5658. if (dst_reg->umin_value < umax_val) {
  5659. /* Overflow possible, we know nothing */
  5660. dst_reg->umin_value = 0;
  5661. dst_reg->umax_value = U64_MAX;
  5662. } else {
  5663. /* Cannot overflow (as long as bounds are consistent) */
  5664. dst_reg->umin_value -= umax_val;
  5665. dst_reg->umax_value -= umin_val;
  5666. }
  5667. }
  5668. static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
  5669. struct bpf_reg_state *src_reg)
  5670. {
  5671. s32 smin_val = src_reg->s32_min_value;
  5672. u32 umin_val = src_reg->u32_min_value;
  5673. u32 umax_val = src_reg->u32_max_value;
  5674. if (smin_val < 0 || dst_reg->s32_min_value < 0) {
  5675. /* Ain't nobody got time to multiply that sign */
  5676. __mark_reg32_unbounded(dst_reg);
  5677. return;
  5678. }
  5679. /* Both values are positive, so we can work with unsigned and
  5680. * copy the result to signed (unless it exceeds S32_MAX).
  5681. */
  5682. if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
  5683. /* Potential overflow, we know nothing */
  5684. __mark_reg32_unbounded(dst_reg);
  5685. return;
  5686. }
  5687. dst_reg->u32_min_value *= umin_val;
  5688. dst_reg->u32_max_value *= umax_val;
  5689. if (dst_reg->u32_max_value > S32_MAX) {
  5690. /* Overflow possible, we know nothing */
  5691. dst_reg->s32_min_value = S32_MIN;
  5692. dst_reg->s32_max_value = S32_MAX;
  5693. } else {
  5694. dst_reg->s32_min_value = dst_reg->u32_min_value;
  5695. dst_reg->s32_max_value = dst_reg->u32_max_value;
  5696. }
  5697. }
  5698. static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
  5699. struct bpf_reg_state *src_reg)
  5700. {
  5701. s64 smin_val = src_reg->smin_value;
  5702. u64 umin_val = src_reg->umin_value;
  5703. u64 umax_val = src_reg->umax_value;
  5704. if (smin_val < 0 || dst_reg->smin_value < 0) {
  5705. /* Ain't nobody got time to multiply that sign */
  5706. __mark_reg64_unbounded(dst_reg);
  5707. return;
  5708. }
  5709. /* Both values are positive, so we can work with unsigned and
  5710. * copy the result to signed (unless it exceeds S64_MAX).
  5711. */
  5712. if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
  5713. /* Potential overflow, we know nothing */
  5714. __mark_reg64_unbounded(dst_reg);
  5715. return;
  5716. }
  5717. dst_reg->umin_value *= umin_val;
  5718. dst_reg->umax_value *= umax_val;
  5719. if (dst_reg->umax_value > S64_MAX) {
  5720. /* Overflow possible, we know nothing */
  5721. dst_reg->smin_value = S64_MIN;
  5722. dst_reg->smax_value = S64_MAX;
  5723. } else {
  5724. dst_reg->smin_value = dst_reg->umin_value;
  5725. dst_reg->smax_value = dst_reg->umax_value;
  5726. }
  5727. }
  5728. static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
  5729. struct bpf_reg_state *src_reg)
  5730. {
  5731. bool src_known = tnum_subreg_is_const(src_reg->var_off);
  5732. bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
  5733. struct tnum var32_off = tnum_subreg(dst_reg->var_off);
  5734. s32 smin_val = src_reg->s32_min_value;
  5735. u32 umax_val = src_reg->u32_max_value;
  5736. if (src_known && dst_known) {
  5737. __mark_reg32_known(dst_reg, var32_off.value);
  5738. return;
  5739. }
  5740. /* We get our minimum from the var_off, since that's inherently
  5741. * bitwise. Our maximum is the minimum of the operands' maxima.
  5742. */
  5743. dst_reg->u32_min_value = var32_off.value;
  5744. dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
  5745. if (dst_reg->s32_min_value < 0 || smin_val < 0) {
  5746. /* Lose signed bounds when ANDing negative numbers,
  5747. * ain't nobody got time for that.
  5748. */
  5749. dst_reg->s32_min_value = S32_MIN;
  5750. dst_reg->s32_max_value = S32_MAX;
  5751. } else {
  5752. /* ANDing two positives gives a positive, so safe to
  5753. * cast result into s64.
  5754. */
  5755. dst_reg->s32_min_value = dst_reg->u32_min_value;
  5756. dst_reg->s32_max_value = dst_reg->u32_max_value;
  5757. }
  5758. }
  5759. static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
  5760. struct bpf_reg_state *src_reg)
  5761. {
  5762. bool src_known = tnum_is_const(src_reg->var_off);
  5763. bool dst_known = tnum_is_const(dst_reg->var_off);
  5764. s64 smin_val = src_reg->smin_value;
  5765. u64 umax_val = src_reg->umax_value;
  5766. if (src_known && dst_known) {
  5767. __mark_reg_known(dst_reg, dst_reg->var_off.value);
  5768. return;
  5769. }
  5770. /* We get our minimum from the var_off, since that's inherently
  5771. * bitwise. Our maximum is the minimum of the operands' maxima.
  5772. */
  5773. dst_reg->umin_value = dst_reg->var_off.value;
  5774. dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
  5775. if (dst_reg->smin_value < 0 || smin_val < 0) {
  5776. /* Lose signed bounds when ANDing negative numbers,
  5777. * ain't nobody got time for that.
  5778. */
  5779. dst_reg->smin_value = S64_MIN;
  5780. dst_reg->smax_value = S64_MAX;
  5781. } else {
  5782. /* ANDing two positives gives a positive, so safe to
  5783. * cast result into s64.
  5784. */
  5785. dst_reg->smin_value = dst_reg->umin_value;
  5786. dst_reg->smax_value = dst_reg->umax_value;
  5787. }
  5788. /* We may learn something more from the var_off */
  5789. __update_reg_bounds(dst_reg);
  5790. }
  5791. static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
  5792. struct bpf_reg_state *src_reg)
  5793. {
  5794. bool src_known = tnum_subreg_is_const(src_reg->var_off);
  5795. bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
  5796. struct tnum var32_off = tnum_subreg(dst_reg->var_off);
  5797. s32 smin_val = src_reg->s32_min_value;
  5798. u32 umin_val = src_reg->u32_min_value;
  5799. if (src_known && dst_known) {
  5800. __mark_reg32_known(dst_reg, var32_off.value);
  5801. return;
  5802. }
  5803. /* We get our maximum from the var_off, and our minimum is the
  5804. * maximum of the operands' minima
  5805. */
  5806. dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
  5807. dst_reg->u32_max_value = var32_off.value | var32_off.mask;
  5808. if (dst_reg->s32_min_value < 0 || smin_val < 0) {
  5809. /* Lose signed bounds when ORing negative numbers,
  5810. * ain't nobody got time for that.
  5811. */
  5812. dst_reg->s32_min_value = S32_MIN;
  5813. dst_reg->s32_max_value = S32_MAX;
  5814. } else {
  5815. /* ORing two positives gives a positive, so safe to
  5816. * cast result into s64.
  5817. */
  5818. dst_reg->s32_min_value = dst_reg->u32_min_value;
  5819. dst_reg->s32_max_value = dst_reg->u32_max_value;
  5820. }
  5821. }
  5822. static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
  5823. struct bpf_reg_state *src_reg)
  5824. {
  5825. bool src_known = tnum_is_const(src_reg->var_off);
  5826. bool dst_known = tnum_is_const(dst_reg->var_off);
  5827. s64 smin_val = src_reg->smin_value;
  5828. u64 umin_val = src_reg->umin_value;
  5829. if (src_known && dst_known) {
  5830. __mark_reg_known(dst_reg, dst_reg->var_off.value);
  5831. return;
  5832. }
  5833. /* We get our maximum from the var_off, and our minimum is the
  5834. * maximum of the operands' minima
  5835. */
  5836. dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
  5837. dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
  5838. if (dst_reg->smin_value < 0 || smin_val < 0) {
  5839. /* Lose signed bounds when ORing negative numbers,
  5840. * ain't nobody got time for that.
  5841. */
  5842. dst_reg->smin_value = S64_MIN;
  5843. dst_reg->smax_value = S64_MAX;
  5844. } else {
  5845. /* ORing two positives gives a positive, so safe to
  5846. * cast result into s64.
  5847. */
  5848. dst_reg->smin_value = dst_reg->umin_value;
  5849. dst_reg->smax_value = dst_reg->umax_value;
  5850. }
  5851. /* We may learn something more from the var_off */
  5852. __update_reg_bounds(dst_reg);
  5853. }
  5854. static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
  5855. struct bpf_reg_state *src_reg)
  5856. {
  5857. bool src_known = tnum_subreg_is_const(src_reg->var_off);
  5858. bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
  5859. struct tnum var32_off = tnum_subreg(dst_reg->var_off);
  5860. s32 smin_val = src_reg->s32_min_value;
  5861. if (src_known && dst_known) {
  5862. __mark_reg32_known(dst_reg, var32_off.value);
  5863. return;
  5864. }
  5865. /* We get both minimum and maximum from the var32_off. */
  5866. dst_reg->u32_min_value = var32_off.value;
  5867. dst_reg->u32_max_value = var32_off.value | var32_off.mask;
  5868. if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
  5869. /* XORing two positive sign numbers gives a positive,
  5870. * so safe to cast u32 result into s32.
  5871. */
  5872. dst_reg->s32_min_value = dst_reg->u32_min_value;
  5873. dst_reg->s32_max_value = dst_reg->u32_max_value;
  5874. } else {
  5875. dst_reg->s32_min_value = S32_MIN;
  5876. dst_reg->s32_max_value = S32_MAX;
  5877. }
  5878. }
  5879. static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
  5880. struct bpf_reg_state *src_reg)
  5881. {
  5882. bool src_known = tnum_is_const(src_reg->var_off);
  5883. bool dst_known = tnum_is_const(dst_reg->var_off);
  5884. s64 smin_val = src_reg->smin_value;
  5885. if (src_known && dst_known) {
  5886. /* dst_reg->var_off.value has been updated earlier */
  5887. __mark_reg_known(dst_reg, dst_reg->var_off.value);
  5888. return;
  5889. }
  5890. /* We get both minimum and maximum from the var_off. */
  5891. dst_reg->umin_value = dst_reg->var_off.value;
  5892. dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
  5893. if (dst_reg->smin_value >= 0 && smin_val >= 0) {
  5894. /* XORing two positive sign numbers gives a positive,
  5895. * so safe to cast u64 result into s64.
  5896. */
  5897. dst_reg->smin_value = dst_reg->umin_value;
  5898. dst_reg->smax_value = dst_reg->umax_value;
  5899. } else {
  5900. dst_reg->smin_value = S64_MIN;
  5901. dst_reg->smax_value = S64_MAX;
  5902. }
  5903. __update_reg_bounds(dst_reg);
  5904. }
  5905. static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
  5906. u64 umin_val, u64 umax_val)
  5907. {
  5908. /* We lose all sign bit information (except what we can pick
  5909. * up from var_off)
  5910. */
  5911. dst_reg->s32_min_value = S32_MIN;
  5912. dst_reg->s32_max_value = S32_MAX;
  5913. /* If we might shift our top bit out, then we know nothing */
  5914. if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
  5915. dst_reg->u32_min_value = 0;
  5916. dst_reg->u32_max_value = U32_MAX;
  5917. } else {
  5918. dst_reg->u32_min_value <<= umin_val;
  5919. dst_reg->u32_max_value <<= umax_val;
  5920. }
  5921. }
  5922. static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
  5923. struct bpf_reg_state *src_reg)
  5924. {
  5925. u32 umax_val = src_reg->u32_max_value;
  5926. u32 umin_val = src_reg->u32_min_value;
  5927. /* u32 alu operation will zext upper bits */
  5928. struct tnum subreg = tnum_subreg(dst_reg->var_off);
  5929. __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
  5930. dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
  5931. /* Not required but being careful mark reg64 bounds as unknown so
  5932. * that we are forced to pick them up from tnum and zext later and
  5933. * if some path skips this step we are still safe.
  5934. */
  5935. __mark_reg64_unbounded(dst_reg);
  5936. __update_reg32_bounds(dst_reg);
  5937. }
  5938. static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
  5939. u64 umin_val, u64 umax_val)
  5940. {
  5941. /* Special case <<32 because it is a common compiler pattern to sign
  5942. * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
  5943. * positive we know this shift will also be positive so we can track
  5944. * bounds correctly. Otherwise we lose all sign bit information except
  5945. * what we can pick up from var_off. Perhaps we can generalize this
  5946. * later to shifts of any length.
  5947. */
  5948. if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
  5949. dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
  5950. else
  5951. dst_reg->smax_value = S64_MAX;
  5952. if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
  5953. dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
  5954. else
  5955. dst_reg->smin_value = S64_MIN;
  5956. /* If we might shift our top bit out, then we know nothing */
  5957. if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
  5958. dst_reg->umin_value = 0;
  5959. dst_reg->umax_value = U64_MAX;
  5960. } else {
  5961. dst_reg->umin_value <<= umin_val;
  5962. dst_reg->umax_value <<= umax_val;
  5963. }
  5964. }
  5965. static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
  5966. struct bpf_reg_state *src_reg)
  5967. {
  5968. u64 umax_val = src_reg->umax_value;
  5969. u64 umin_val = src_reg->umin_value;
  5970. /* scalar64 calc uses 32bit unshifted bounds so must be called first */
  5971. __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
  5972. __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
  5973. dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
  5974. /* We may learn something more from the var_off */
  5975. __update_reg_bounds(dst_reg);
  5976. }
  5977. static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
  5978. struct bpf_reg_state *src_reg)
  5979. {
  5980. struct tnum subreg = tnum_subreg(dst_reg->var_off);
  5981. u32 umax_val = src_reg->u32_max_value;
  5982. u32 umin_val = src_reg->u32_min_value;
  5983. /* BPF_RSH is an unsigned shift. If the value in dst_reg might
  5984. * be negative, then either:
  5985. * 1) src_reg might be zero, so the sign bit of the result is
  5986. * unknown, so we lose our signed bounds
  5987. * 2) it's known negative, thus the unsigned bounds capture the
  5988. * signed bounds
  5989. * 3) the signed bounds cross zero, so they tell us nothing
  5990. * about the result
  5991. * If the value in dst_reg is known nonnegative, then again the
  5992. * unsigned bounts capture the signed bounds.
  5993. * Thus, in all cases it suffices to blow away our signed bounds
  5994. * and rely on inferring new ones from the unsigned bounds and
  5995. * var_off of the result.
  5996. */
  5997. dst_reg->s32_min_value = S32_MIN;
  5998. dst_reg->s32_max_value = S32_MAX;
  5999. dst_reg->var_off = tnum_rshift(subreg, umin_val);
  6000. dst_reg->u32_min_value >>= umax_val;
  6001. dst_reg->u32_max_value >>= umin_val;
  6002. __mark_reg64_unbounded(dst_reg);
  6003. __update_reg32_bounds(dst_reg);
  6004. }
  6005. static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
  6006. struct bpf_reg_state *src_reg)
  6007. {
  6008. u64 umax_val = src_reg->umax_value;
  6009. u64 umin_val = src_reg->umin_value;
  6010. /* BPF_RSH is an unsigned shift. If the value in dst_reg might
  6011. * be negative, then either:
  6012. * 1) src_reg might be zero, so the sign bit of the result is
  6013. * unknown, so we lose our signed bounds
  6014. * 2) it's known negative, thus the unsigned bounds capture the
  6015. * signed bounds
  6016. * 3) the signed bounds cross zero, so they tell us nothing
  6017. * about the result
  6018. * If the value in dst_reg is known nonnegative, then again the
  6019. * unsigned bounts capture the signed bounds.
  6020. * Thus, in all cases it suffices to blow away our signed bounds
  6021. * and rely on inferring new ones from the unsigned bounds and
  6022. * var_off of the result.
  6023. */
  6024. dst_reg->smin_value = S64_MIN;
  6025. dst_reg->smax_value = S64_MAX;
  6026. dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
  6027. dst_reg->umin_value >>= umax_val;
  6028. dst_reg->umax_value >>= umin_val;
  6029. /* Its not easy to operate on alu32 bounds here because it depends
  6030. * on bits being shifted in. Take easy way out and mark unbounded
  6031. * so we can recalculate later from tnum.
  6032. */
  6033. __mark_reg32_unbounded(dst_reg);
  6034. __update_reg_bounds(dst_reg);
  6035. }
  6036. static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
  6037. struct bpf_reg_state *src_reg)
  6038. {
  6039. u64 umin_val = src_reg->u32_min_value;
  6040. /* Upon reaching here, src_known is true and
  6041. * umax_val is equal to umin_val.
  6042. */
  6043. dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
  6044. dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
  6045. dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
  6046. /* blow away the dst_reg umin_value/umax_value and rely on
  6047. * dst_reg var_off to refine the result.
  6048. */
  6049. dst_reg->u32_min_value = 0;
  6050. dst_reg->u32_max_value = U32_MAX;
  6051. __mark_reg64_unbounded(dst_reg);
  6052. __update_reg32_bounds(dst_reg);
  6053. }
  6054. static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
  6055. struct bpf_reg_state *src_reg)
  6056. {
  6057. u64 umin_val = src_reg->umin_value;
  6058. /* Upon reaching here, src_known is true and umax_val is equal
  6059. * to umin_val.
  6060. */
  6061. dst_reg->smin_value >>= umin_val;
  6062. dst_reg->smax_value >>= umin_val;
  6063. dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
  6064. /* blow away the dst_reg umin_value/umax_value and rely on
  6065. * dst_reg var_off to refine the result.
  6066. */
  6067. dst_reg->umin_value = 0;
  6068. dst_reg->umax_value = U64_MAX;
  6069. /* Its not easy to operate on alu32 bounds here because it depends
  6070. * on bits being shifted in from upper 32-bits. Take easy way out
  6071. * and mark unbounded so we can recalculate later from tnum.
  6072. */
  6073. __mark_reg32_unbounded(dst_reg);
  6074. __update_reg_bounds(dst_reg);
  6075. }
  6076. /* WARNING: This function does calculations on 64-bit values, but the actual
  6077. * execution may occur on 32-bit values. Therefore, things like bitshifts
  6078. * need extra checks in the 32-bit case.
  6079. */
  6080. static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
  6081. struct bpf_insn *insn,
  6082. struct bpf_reg_state *dst_reg,
  6083. struct bpf_reg_state src_reg)
  6084. {
  6085. struct bpf_reg_state *regs = cur_regs(env);
  6086. u8 opcode = BPF_OP(insn->code);
  6087. bool src_known;
  6088. s64 smin_val, smax_val;
  6089. u64 umin_val, umax_val;
  6090. s32 s32_min_val, s32_max_val;
  6091. u32 u32_min_val, u32_max_val;
  6092. u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
  6093. bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
  6094. int ret;
  6095. smin_val = src_reg.smin_value;
  6096. smax_val = src_reg.smax_value;
  6097. umin_val = src_reg.umin_value;
  6098. umax_val = src_reg.umax_value;
  6099. s32_min_val = src_reg.s32_min_value;
  6100. s32_max_val = src_reg.s32_max_value;
  6101. u32_min_val = src_reg.u32_min_value;
  6102. u32_max_val = src_reg.u32_max_value;
  6103. if (alu32) {
  6104. src_known = tnum_subreg_is_const(src_reg.var_off);
  6105. if ((src_known &&
  6106. (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
  6107. s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
  6108. /* Taint dst register if offset had invalid bounds
  6109. * derived from e.g. dead branches.
  6110. */
  6111. __mark_reg_unknown(env, dst_reg);
  6112. return 0;
  6113. }
  6114. } else {
  6115. src_known = tnum_is_const(src_reg.var_off);
  6116. if ((src_known &&
  6117. (smin_val != smax_val || umin_val != umax_val)) ||
  6118. smin_val > smax_val || umin_val > umax_val) {
  6119. /* Taint dst register if offset had invalid bounds
  6120. * derived from e.g. dead branches.
  6121. */
  6122. __mark_reg_unknown(env, dst_reg);
  6123. return 0;
  6124. }
  6125. }
  6126. if (!src_known &&
  6127. opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
  6128. __mark_reg_unknown(env, dst_reg);
  6129. return 0;
  6130. }
  6131. if (sanitize_needed(opcode)) {
  6132. ret = sanitize_val_alu(env, insn);
  6133. if (ret < 0)
  6134. return sanitize_err(env, insn, ret, NULL, NULL);
  6135. }
  6136. /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
  6137. * There are two classes of instructions: The first class we track both
  6138. * alu32 and alu64 sign/unsigned bounds independently this provides the
  6139. * greatest amount of precision when alu operations are mixed with jmp32
  6140. * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
  6141. * and BPF_OR. This is possible because these ops have fairly easy to
  6142. * understand and calculate behavior in both 32-bit and 64-bit alu ops.
  6143. * See alu32 verifier tests for examples. The second class of
  6144. * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
  6145. * with regards to tracking sign/unsigned bounds because the bits may
  6146. * cross subreg boundaries in the alu64 case. When this happens we mark
  6147. * the reg unbounded in the subreg bound space and use the resulting
  6148. * tnum to calculate an approximation of the sign/unsigned bounds.
  6149. */
  6150. switch (opcode) {
  6151. case BPF_ADD:
  6152. scalar32_min_max_add(dst_reg, &src_reg);
  6153. scalar_min_max_add(dst_reg, &src_reg);
  6154. dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
  6155. break;
  6156. case BPF_SUB:
  6157. scalar32_min_max_sub(dst_reg, &src_reg);
  6158. scalar_min_max_sub(dst_reg, &src_reg);
  6159. dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
  6160. break;
  6161. case BPF_MUL:
  6162. dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
  6163. scalar32_min_max_mul(dst_reg, &src_reg);
  6164. scalar_min_max_mul(dst_reg, &src_reg);
  6165. break;
  6166. case BPF_AND:
  6167. dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
  6168. scalar32_min_max_and(dst_reg, &src_reg);
  6169. scalar_min_max_and(dst_reg, &src_reg);
  6170. break;
  6171. case BPF_OR:
  6172. dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
  6173. scalar32_min_max_or(dst_reg, &src_reg);
  6174. scalar_min_max_or(dst_reg, &src_reg);
  6175. break;
  6176. case BPF_XOR:
  6177. dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
  6178. scalar32_min_max_xor(dst_reg, &src_reg);
  6179. scalar_min_max_xor(dst_reg, &src_reg);
  6180. break;
  6181. case BPF_LSH:
  6182. if (umax_val >= insn_bitness) {
  6183. /* Shifts greater than 31 or 63 are undefined.
  6184. * This includes shifts by a negative number.
  6185. */
  6186. mark_reg_unknown(env, regs, insn->dst_reg);
  6187. break;
  6188. }
  6189. if (alu32)
  6190. scalar32_min_max_lsh(dst_reg, &src_reg);
  6191. else
  6192. scalar_min_max_lsh(dst_reg, &src_reg);
  6193. break;
  6194. case BPF_RSH:
  6195. if (umax_val >= insn_bitness) {
  6196. /* Shifts greater than 31 or 63 are undefined.
  6197. * This includes shifts by a negative number.
  6198. */
  6199. mark_reg_unknown(env, regs, insn->dst_reg);
  6200. break;
  6201. }
  6202. if (alu32)
  6203. scalar32_min_max_rsh(dst_reg, &src_reg);
  6204. else
  6205. scalar_min_max_rsh(dst_reg, &src_reg);
  6206. break;
  6207. case BPF_ARSH:
  6208. if (umax_val >= insn_bitness) {
  6209. /* Shifts greater than 31 or 63 are undefined.
  6210. * This includes shifts by a negative number.
  6211. */
  6212. mark_reg_unknown(env, regs, insn->dst_reg);
  6213. break;
  6214. }
  6215. if (alu32)
  6216. scalar32_min_max_arsh(dst_reg, &src_reg);
  6217. else
  6218. scalar_min_max_arsh(dst_reg, &src_reg);
  6219. break;
  6220. default:
  6221. mark_reg_unknown(env, regs, insn->dst_reg);
  6222. break;
  6223. }
  6224. /* ALU32 ops are zero extended into 64bit register */
  6225. if (alu32)
  6226. zext_32_to_64(dst_reg);
  6227. __update_reg_bounds(dst_reg);
  6228. __reg_deduce_bounds(dst_reg);
  6229. __reg_bound_offset(dst_reg);
  6230. return 0;
  6231. }
  6232. /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
  6233. * and var_off.
  6234. */
  6235. static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
  6236. struct bpf_insn *insn)
  6237. {
  6238. struct bpf_verifier_state *vstate = env->cur_state;
  6239. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  6240. struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
  6241. struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
  6242. u8 opcode = BPF_OP(insn->code);
  6243. int err;
  6244. dst_reg = &regs[insn->dst_reg];
  6245. src_reg = NULL;
  6246. if (dst_reg->type != SCALAR_VALUE)
  6247. ptr_reg = dst_reg;
  6248. else
  6249. /* Make sure ID is cleared otherwise dst_reg min/max could be
  6250. * incorrectly propagated into other registers by find_equal_scalars()
  6251. */
  6252. dst_reg->id = 0;
  6253. if (BPF_SRC(insn->code) == BPF_X) {
  6254. src_reg = &regs[insn->src_reg];
  6255. if (src_reg->type != SCALAR_VALUE) {
  6256. if (dst_reg->type != SCALAR_VALUE) {
  6257. /* Combining two pointers by any ALU op yields
  6258. * an arbitrary scalar. Disallow all math except
  6259. * pointer subtraction
  6260. */
  6261. if (opcode == BPF_SUB && env->allow_ptr_leaks) {
  6262. mark_reg_unknown(env, regs, insn->dst_reg);
  6263. return 0;
  6264. }
  6265. verbose(env, "R%d pointer %s pointer prohibited\n",
  6266. insn->dst_reg,
  6267. bpf_alu_string[opcode >> 4]);
  6268. return -EACCES;
  6269. } else {
  6270. /* scalar += pointer
  6271. * This is legal, but we have to reverse our
  6272. * src/dest handling in computing the range
  6273. */
  6274. err = mark_chain_precision(env, insn->dst_reg);
  6275. if (err)
  6276. return err;
  6277. return adjust_ptr_min_max_vals(env, insn,
  6278. src_reg, dst_reg);
  6279. }
  6280. } else if (ptr_reg) {
  6281. /* pointer += scalar */
  6282. err = mark_chain_precision(env, insn->src_reg);
  6283. if (err)
  6284. return err;
  6285. return adjust_ptr_min_max_vals(env, insn,
  6286. dst_reg, src_reg);
  6287. }
  6288. } else {
  6289. /* Pretend the src is a reg with a known value, since we only
  6290. * need to be able to read from this state.
  6291. */
  6292. off_reg.type = SCALAR_VALUE;
  6293. __mark_reg_known(&off_reg, insn->imm);
  6294. src_reg = &off_reg;
  6295. if (ptr_reg) /* pointer += K */
  6296. return adjust_ptr_min_max_vals(env, insn,
  6297. ptr_reg, src_reg);
  6298. }
  6299. /* Got here implies adding two SCALAR_VALUEs */
  6300. if (WARN_ON_ONCE(ptr_reg)) {
  6301. print_verifier_state(env, state);
  6302. verbose(env, "verifier internal error: unexpected ptr_reg\n");
  6303. return -EINVAL;
  6304. }
  6305. if (WARN_ON(!src_reg)) {
  6306. print_verifier_state(env, state);
  6307. verbose(env, "verifier internal error: no src_reg\n");
  6308. return -EINVAL;
  6309. }
  6310. return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
  6311. }
  6312. /* check validity of 32-bit and 64-bit arithmetic operations */
  6313. static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
  6314. {
  6315. struct bpf_reg_state *regs = cur_regs(env);
  6316. u8 opcode = BPF_OP(insn->code);
  6317. int err;
  6318. if (opcode == BPF_END || opcode == BPF_NEG) {
  6319. if (opcode == BPF_NEG) {
  6320. if (BPF_SRC(insn->code) != 0 ||
  6321. insn->src_reg != BPF_REG_0 ||
  6322. insn->off != 0 || insn->imm != 0) {
  6323. verbose(env, "BPF_NEG uses reserved fields\n");
  6324. return -EINVAL;
  6325. }
  6326. } else {
  6327. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  6328. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
  6329. BPF_CLASS(insn->code) == BPF_ALU64) {
  6330. verbose(env, "BPF_END uses reserved fields\n");
  6331. return -EINVAL;
  6332. }
  6333. }
  6334. /* check src operand */
  6335. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  6336. if (err)
  6337. return err;
  6338. if (is_pointer_value(env, insn->dst_reg)) {
  6339. verbose(env, "R%d pointer arithmetic prohibited\n",
  6340. insn->dst_reg);
  6341. return -EACCES;
  6342. }
  6343. /* check dest operand */
  6344. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  6345. if (err)
  6346. return err;
  6347. } else if (opcode == BPF_MOV) {
  6348. if (BPF_SRC(insn->code) == BPF_X) {
  6349. if (insn->imm != 0 || insn->off != 0) {
  6350. verbose(env, "BPF_MOV uses reserved fields\n");
  6351. return -EINVAL;
  6352. }
  6353. /* check src operand */
  6354. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  6355. if (err)
  6356. return err;
  6357. } else {
  6358. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  6359. verbose(env, "BPF_MOV uses reserved fields\n");
  6360. return -EINVAL;
  6361. }
  6362. }
  6363. /* check dest operand, mark as required later */
  6364. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  6365. if (err)
  6366. return err;
  6367. if (BPF_SRC(insn->code) == BPF_X) {
  6368. struct bpf_reg_state *src_reg = regs + insn->src_reg;
  6369. struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
  6370. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  6371. /* case: R1 = R2
  6372. * copy register state to dest reg
  6373. */
  6374. if (src_reg->type == SCALAR_VALUE && !src_reg->id)
  6375. /* Assign src and dst registers the same ID
  6376. * that will be used by find_equal_scalars()
  6377. * to propagate min/max range.
  6378. */
  6379. src_reg->id = ++env->id_gen;
  6380. *dst_reg = *src_reg;
  6381. dst_reg->live |= REG_LIVE_WRITTEN;
  6382. dst_reg->subreg_def = DEF_NOT_SUBREG;
  6383. } else {
  6384. /* R1 = (u32) R2 */
  6385. if (is_pointer_value(env, insn->src_reg)) {
  6386. verbose(env,
  6387. "R%d partial copy of pointer\n",
  6388. insn->src_reg);
  6389. return -EACCES;
  6390. } else if (src_reg->type == SCALAR_VALUE) {
  6391. *dst_reg = *src_reg;
  6392. /* Make sure ID is cleared otherwise
  6393. * dst_reg min/max could be incorrectly
  6394. * propagated into src_reg by find_equal_scalars()
  6395. */
  6396. dst_reg->id = 0;
  6397. dst_reg->live |= REG_LIVE_WRITTEN;
  6398. dst_reg->subreg_def = env->insn_idx + 1;
  6399. } else {
  6400. mark_reg_unknown(env, regs,
  6401. insn->dst_reg);
  6402. }
  6403. zext_32_to_64(dst_reg);
  6404. __update_reg_bounds(dst_reg);
  6405. __reg_deduce_bounds(dst_reg);
  6406. __reg_bound_offset(dst_reg);
  6407. }
  6408. } else {
  6409. /* case: R = imm
  6410. * remember the value we stored into this reg
  6411. */
  6412. /* clear any state __mark_reg_known doesn't set */
  6413. mark_reg_unknown(env, regs, insn->dst_reg);
  6414. regs[insn->dst_reg].type = SCALAR_VALUE;
  6415. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  6416. __mark_reg_known(regs + insn->dst_reg,
  6417. insn->imm);
  6418. } else {
  6419. __mark_reg_known(regs + insn->dst_reg,
  6420. (u32)insn->imm);
  6421. }
  6422. }
  6423. } else if (opcode > BPF_END) {
  6424. verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
  6425. return -EINVAL;
  6426. } else { /* all other ALU ops: and, sub, xor, add, ... */
  6427. if (BPF_SRC(insn->code) == BPF_X) {
  6428. if (insn->imm != 0 || insn->off != 0) {
  6429. verbose(env, "BPF_ALU uses reserved fields\n");
  6430. return -EINVAL;
  6431. }
  6432. /* check src1 operand */
  6433. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  6434. if (err)
  6435. return err;
  6436. } else {
  6437. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  6438. verbose(env, "BPF_ALU uses reserved fields\n");
  6439. return -EINVAL;
  6440. }
  6441. }
  6442. /* check src2 operand */
  6443. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  6444. if (err)
  6445. return err;
  6446. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  6447. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  6448. verbose(env, "div by zero\n");
  6449. return -EINVAL;
  6450. }
  6451. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  6452. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  6453. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  6454. if (insn->imm < 0 || insn->imm >= size) {
  6455. verbose(env, "invalid shift %d\n", insn->imm);
  6456. return -EINVAL;
  6457. }
  6458. }
  6459. /* check dest operand */
  6460. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  6461. if (err)
  6462. return err;
  6463. return adjust_reg_min_max_vals(env, insn);
  6464. }
  6465. return 0;
  6466. }
  6467. static void __find_good_pkt_pointers(struct bpf_func_state *state,
  6468. struct bpf_reg_state *dst_reg,
  6469. enum bpf_reg_type type, u16 new_range)
  6470. {
  6471. struct bpf_reg_state *reg;
  6472. int i;
  6473. for (i = 0; i < MAX_BPF_REG; i++) {
  6474. reg = &state->regs[i];
  6475. if (reg->type == type && reg->id == dst_reg->id)
  6476. /* keep the maximum range already checked */
  6477. reg->range = max(reg->range, new_range);
  6478. }
  6479. bpf_for_each_spilled_reg(i, state, reg) {
  6480. if (!reg)
  6481. continue;
  6482. if (reg->type == type && reg->id == dst_reg->id)
  6483. reg->range = max(reg->range, new_range);
  6484. }
  6485. }
  6486. static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
  6487. struct bpf_reg_state *dst_reg,
  6488. enum bpf_reg_type type,
  6489. bool range_right_open)
  6490. {
  6491. u16 new_range;
  6492. int i;
  6493. if (dst_reg->off < 0 ||
  6494. (dst_reg->off == 0 && range_right_open))
  6495. /* This doesn't give us any range */
  6496. return;
  6497. if (dst_reg->umax_value > MAX_PACKET_OFF ||
  6498. dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
  6499. /* Risk of overflow. For instance, ptr + (1<<63) may be less
  6500. * than pkt_end, but that's because it's also less than pkt.
  6501. */
  6502. return;
  6503. new_range = dst_reg->off;
  6504. if (range_right_open)
  6505. new_range++;
  6506. /* Examples for register markings:
  6507. *
  6508. * pkt_data in dst register:
  6509. *
  6510. * r2 = r3;
  6511. * r2 += 8;
  6512. * if (r2 > pkt_end) goto <handle exception>
  6513. * <access okay>
  6514. *
  6515. * r2 = r3;
  6516. * r2 += 8;
  6517. * if (r2 < pkt_end) goto <access okay>
  6518. * <handle exception>
  6519. *
  6520. * Where:
  6521. * r2 == dst_reg, pkt_end == src_reg
  6522. * r2=pkt(id=n,off=8,r=0)
  6523. * r3=pkt(id=n,off=0,r=0)
  6524. *
  6525. * pkt_data in src register:
  6526. *
  6527. * r2 = r3;
  6528. * r2 += 8;
  6529. * if (pkt_end >= r2) goto <access okay>
  6530. * <handle exception>
  6531. *
  6532. * r2 = r3;
  6533. * r2 += 8;
  6534. * if (pkt_end <= r2) goto <handle exception>
  6535. * <access okay>
  6536. *
  6537. * Where:
  6538. * pkt_end == dst_reg, r2 == src_reg
  6539. * r2=pkt(id=n,off=8,r=0)
  6540. * r3=pkt(id=n,off=0,r=0)
  6541. *
  6542. * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
  6543. * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
  6544. * and [r3, r3 + 8-1) respectively is safe to access depending on
  6545. * the check.
  6546. */
  6547. /* If our ids match, then we must have the same max_value. And we
  6548. * don't care about the other reg's fixed offset, since if it's too big
  6549. * the range won't allow anything.
  6550. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
  6551. */
  6552. for (i = 0; i <= vstate->curframe; i++)
  6553. __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
  6554. new_range);
  6555. }
  6556. static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
  6557. {
  6558. struct tnum subreg = tnum_subreg(reg->var_off);
  6559. s32 sval = (s32)val;
  6560. switch (opcode) {
  6561. case BPF_JEQ:
  6562. if (tnum_is_const(subreg))
  6563. return !!tnum_equals_const(subreg, val);
  6564. break;
  6565. case BPF_JNE:
  6566. if (tnum_is_const(subreg))
  6567. return !tnum_equals_const(subreg, val);
  6568. break;
  6569. case BPF_JSET:
  6570. if ((~subreg.mask & subreg.value) & val)
  6571. return 1;
  6572. if (!((subreg.mask | subreg.value) & val))
  6573. return 0;
  6574. break;
  6575. case BPF_JGT:
  6576. if (reg->u32_min_value > val)
  6577. return 1;
  6578. else if (reg->u32_max_value <= val)
  6579. return 0;
  6580. break;
  6581. case BPF_JSGT:
  6582. if (reg->s32_min_value > sval)
  6583. return 1;
  6584. else if (reg->s32_max_value <= sval)
  6585. return 0;
  6586. break;
  6587. case BPF_JLT:
  6588. if (reg->u32_max_value < val)
  6589. return 1;
  6590. else if (reg->u32_min_value >= val)
  6591. return 0;
  6592. break;
  6593. case BPF_JSLT:
  6594. if (reg->s32_max_value < sval)
  6595. return 1;
  6596. else if (reg->s32_min_value >= sval)
  6597. return 0;
  6598. break;
  6599. case BPF_JGE:
  6600. if (reg->u32_min_value >= val)
  6601. return 1;
  6602. else if (reg->u32_max_value < val)
  6603. return 0;
  6604. break;
  6605. case BPF_JSGE:
  6606. if (reg->s32_min_value >= sval)
  6607. return 1;
  6608. else if (reg->s32_max_value < sval)
  6609. return 0;
  6610. break;
  6611. case BPF_JLE:
  6612. if (reg->u32_max_value <= val)
  6613. return 1;
  6614. else if (reg->u32_min_value > val)
  6615. return 0;
  6616. break;
  6617. case BPF_JSLE:
  6618. if (reg->s32_max_value <= sval)
  6619. return 1;
  6620. else if (reg->s32_min_value > sval)
  6621. return 0;
  6622. break;
  6623. }
  6624. return -1;
  6625. }
  6626. static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
  6627. {
  6628. s64 sval = (s64)val;
  6629. switch (opcode) {
  6630. case BPF_JEQ:
  6631. if (tnum_is_const(reg->var_off))
  6632. return !!tnum_equals_const(reg->var_off, val);
  6633. break;
  6634. case BPF_JNE:
  6635. if (tnum_is_const(reg->var_off))
  6636. return !tnum_equals_const(reg->var_off, val);
  6637. break;
  6638. case BPF_JSET:
  6639. if ((~reg->var_off.mask & reg->var_off.value) & val)
  6640. return 1;
  6641. if (!((reg->var_off.mask | reg->var_off.value) & val))
  6642. return 0;
  6643. break;
  6644. case BPF_JGT:
  6645. if (reg->umin_value > val)
  6646. return 1;
  6647. else if (reg->umax_value <= val)
  6648. return 0;
  6649. break;
  6650. case BPF_JSGT:
  6651. if (reg->smin_value > sval)
  6652. return 1;
  6653. else if (reg->smax_value <= sval)
  6654. return 0;
  6655. break;
  6656. case BPF_JLT:
  6657. if (reg->umax_value < val)
  6658. return 1;
  6659. else if (reg->umin_value >= val)
  6660. return 0;
  6661. break;
  6662. case BPF_JSLT:
  6663. if (reg->smax_value < sval)
  6664. return 1;
  6665. else if (reg->smin_value >= sval)
  6666. return 0;
  6667. break;
  6668. case BPF_JGE:
  6669. if (reg->umin_value >= val)
  6670. return 1;
  6671. else if (reg->umax_value < val)
  6672. return 0;
  6673. break;
  6674. case BPF_JSGE:
  6675. if (reg->smin_value >= sval)
  6676. return 1;
  6677. else if (reg->smax_value < sval)
  6678. return 0;
  6679. break;
  6680. case BPF_JLE:
  6681. if (reg->umax_value <= val)
  6682. return 1;
  6683. else if (reg->umin_value > val)
  6684. return 0;
  6685. break;
  6686. case BPF_JSLE:
  6687. if (reg->smax_value <= sval)
  6688. return 1;
  6689. else if (reg->smin_value > sval)
  6690. return 0;
  6691. break;
  6692. }
  6693. return -1;
  6694. }
  6695. /* compute branch direction of the expression "if (reg opcode val) goto target;"
  6696. * and return:
  6697. * 1 - branch will be taken and "goto target" will be executed
  6698. * 0 - branch will not be taken and fall-through to next insn
  6699. * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
  6700. * range [0,10]
  6701. */
  6702. static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
  6703. bool is_jmp32)
  6704. {
  6705. if (__is_pointer_value(false, reg)) {
  6706. if (!reg_type_not_null(reg->type))
  6707. return -1;
  6708. /* If pointer is valid tests against zero will fail so we can
  6709. * use this to direct branch taken.
  6710. */
  6711. if (val != 0)
  6712. return -1;
  6713. switch (opcode) {
  6714. case BPF_JEQ:
  6715. return 0;
  6716. case BPF_JNE:
  6717. return 1;
  6718. default:
  6719. return -1;
  6720. }
  6721. }
  6722. if (is_jmp32)
  6723. return is_branch32_taken(reg, val, opcode);
  6724. return is_branch64_taken(reg, val, opcode);
  6725. }
  6726. /* Adjusts the register min/max values in the case that the dst_reg is the
  6727. * variable register that we are working on, and src_reg is a constant or we're
  6728. * simply doing a BPF_K check.
  6729. * In JEQ/JNE cases we also adjust the var_off values.
  6730. */
  6731. static void reg_set_min_max(struct bpf_reg_state *true_reg,
  6732. struct bpf_reg_state *false_reg,
  6733. u64 val, u32 val32,
  6734. u8 opcode, bool is_jmp32)
  6735. {
  6736. struct tnum false_32off = tnum_subreg(false_reg->var_off);
  6737. struct tnum false_64off = false_reg->var_off;
  6738. struct tnum true_32off = tnum_subreg(true_reg->var_off);
  6739. struct tnum true_64off = true_reg->var_off;
  6740. s64 sval = (s64)val;
  6741. s32 sval32 = (s32)val32;
  6742. /* If the dst_reg is a pointer, we can't learn anything about its
  6743. * variable offset from the compare (unless src_reg were a pointer into
  6744. * the same object, but we don't bother with that.
  6745. * Since false_reg and true_reg have the same type by construction, we
  6746. * only need to check one of them for pointerness.
  6747. */
  6748. if (__is_pointer_value(false, false_reg))
  6749. return;
  6750. switch (opcode) {
  6751. case BPF_JEQ:
  6752. case BPF_JNE:
  6753. {
  6754. struct bpf_reg_state *reg =
  6755. opcode == BPF_JEQ ? true_reg : false_reg;
  6756. /* JEQ/JNE comparison doesn't change the register equivalence.
  6757. * r1 = r2;
  6758. * if (r1 == 42) goto label;
  6759. * ...
  6760. * label: // here both r1 and r2 are known to be 42.
  6761. *
  6762. * Hence when marking register as known preserve it's ID.
  6763. */
  6764. if (is_jmp32)
  6765. __mark_reg32_known(reg, val32);
  6766. else
  6767. ___mark_reg_known(reg, val);
  6768. break;
  6769. }
  6770. case BPF_JSET:
  6771. if (is_jmp32) {
  6772. false_32off = tnum_and(false_32off, tnum_const(~val32));
  6773. if (is_power_of_2(val32))
  6774. true_32off = tnum_or(true_32off,
  6775. tnum_const(val32));
  6776. } else {
  6777. false_64off = tnum_and(false_64off, tnum_const(~val));
  6778. if (is_power_of_2(val))
  6779. true_64off = tnum_or(true_64off,
  6780. tnum_const(val));
  6781. }
  6782. break;
  6783. case BPF_JGE:
  6784. case BPF_JGT:
  6785. {
  6786. if (is_jmp32) {
  6787. u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
  6788. u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
  6789. false_reg->u32_max_value = min(false_reg->u32_max_value,
  6790. false_umax);
  6791. true_reg->u32_min_value = max(true_reg->u32_min_value,
  6792. true_umin);
  6793. } else {
  6794. u64 false_umax = opcode == BPF_JGT ? val : val - 1;
  6795. u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
  6796. false_reg->umax_value = min(false_reg->umax_value, false_umax);
  6797. true_reg->umin_value = max(true_reg->umin_value, true_umin);
  6798. }
  6799. break;
  6800. }
  6801. case BPF_JSGE:
  6802. case BPF_JSGT:
  6803. {
  6804. if (is_jmp32) {
  6805. s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
  6806. s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
  6807. false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
  6808. true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
  6809. } else {
  6810. s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
  6811. s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
  6812. false_reg->smax_value = min(false_reg->smax_value, false_smax);
  6813. true_reg->smin_value = max(true_reg->smin_value, true_smin);
  6814. }
  6815. break;
  6816. }
  6817. case BPF_JLE:
  6818. case BPF_JLT:
  6819. {
  6820. if (is_jmp32) {
  6821. u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
  6822. u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
  6823. false_reg->u32_min_value = max(false_reg->u32_min_value,
  6824. false_umin);
  6825. true_reg->u32_max_value = min(true_reg->u32_max_value,
  6826. true_umax);
  6827. } else {
  6828. u64 false_umin = opcode == BPF_JLT ? val : val + 1;
  6829. u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
  6830. false_reg->umin_value = max(false_reg->umin_value, false_umin);
  6831. true_reg->umax_value = min(true_reg->umax_value, true_umax);
  6832. }
  6833. break;
  6834. }
  6835. case BPF_JSLE:
  6836. case BPF_JSLT:
  6837. {
  6838. if (is_jmp32) {
  6839. s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
  6840. s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
  6841. false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
  6842. true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
  6843. } else {
  6844. s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
  6845. s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
  6846. false_reg->smin_value = max(false_reg->smin_value, false_smin);
  6847. true_reg->smax_value = min(true_reg->smax_value, true_smax);
  6848. }
  6849. break;
  6850. }
  6851. default:
  6852. return;
  6853. }
  6854. if (is_jmp32) {
  6855. false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
  6856. tnum_subreg(false_32off));
  6857. true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
  6858. tnum_subreg(true_32off));
  6859. __reg_combine_32_into_64(false_reg);
  6860. __reg_combine_32_into_64(true_reg);
  6861. } else {
  6862. false_reg->var_off = false_64off;
  6863. true_reg->var_off = true_64off;
  6864. __reg_combine_64_into_32(false_reg);
  6865. __reg_combine_64_into_32(true_reg);
  6866. }
  6867. }
  6868. /* Same as above, but for the case that dst_reg holds a constant and src_reg is
  6869. * the variable reg.
  6870. */
  6871. static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
  6872. struct bpf_reg_state *false_reg,
  6873. u64 val, u32 val32,
  6874. u8 opcode, bool is_jmp32)
  6875. {
  6876. /* How can we transform "a <op> b" into "b <op> a"? */
  6877. static const u8 opcode_flip[16] = {
  6878. /* these stay the same */
  6879. [BPF_JEQ >> 4] = BPF_JEQ,
  6880. [BPF_JNE >> 4] = BPF_JNE,
  6881. [BPF_JSET >> 4] = BPF_JSET,
  6882. /* these swap "lesser" and "greater" (L and G in the opcodes) */
  6883. [BPF_JGE >> 4] = BPF_JLE,
  6884. [BPF_JGT >> 4] = BPF_JLT,
  6885. [BPF_JLE >> 4] = BPF_JGE,
  6886. [BPF_JLT >> 4] = BPF_JGT,
  6887. [BPF_JSGE >> 4] = BPF_JSLE,
  6888. [BPF_JSGT >> 4] = BPF_JSLT,
  6889. [BPF_JSLE >> 4] = BPF_JSGE,
  6890. [BPF_JSLT >> 4] = BPF_JSGT
  6891. };
  6892. opcode = opcode_flip[opcode >> 4];
  6893. /* This uses zero as "not present in table"; luckily the zero opcode,
  6894. * BPF_JA, can't get here.
  6895. */
  6896. if (opcode)
  6897. reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
  6898. }
  6899. /* Regs are known to be equal, so intersect their min/max/var_off */
  6900. static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
  6901. struct bpf_reg_state *dst_reg)
  6902. {
  6903. src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
  6904. dst_reg->umin_value);
  6905. src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
  6906. dst_reg->umax_value);
  6907. src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
  6908. dst_reg->smin_value);
  6909. src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
  6910. dst_reg->smax_value);
  6911. src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
  6912. dst_reg->var_off);
  6913. /* We might have learned new bounds from the var_off. */
  6914. __update_reg_bounds(src_reg);
  6915. __update_reg_bounds(dst_reg);
  6916. /* We might have learned something about the sign bit. */
  6917. __reg_deduce_bounds(src_reg);
  6918. __reg_deduce_bounds(dst_reg);
  6919. /* We might have learned some bits from the bounds. */
  6920. __reg_bound_offset(src_reg);
  6921. __reg_bound_offset(dst_reg);
  6922. /* Intersecting with the old var_off might have improved our bounds
  6923. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  6924. * then new var_off is (0; 0x7f...fc) which improves our umax.
  6925. */
  6926. __update_reg_bounds(src_reg);
  6927. __update_reg_bounds(dst_reg);
  6928. }
  6929. static void reg_combine_min_max(struct bpf_reg_state *true_src,
  6930. struct bpf_reg_state *true_dst,
  6931. struct bpf_reg_state *false_src,
  6932. struct bpf_reg_state *false_dst,
  6933. u8 opcode)
  6934. {
  6935. switch (opcode) {
  6936. case BPF_JEQ:
  6937. __reg_combine_min_max(true_src, true_dst);
  6938. break;
  6939. case BPF_JNE:
  6940. __reg_combine_min_max(false_src, false_dst);
  6941. break;
  6942. }
  6943. }
  6944. static void mark_ptr_or_null_reg(struct bpf_func_state *state,
  6945. struct bpf_reg_state *reg, u32 id,
  6946. bool is_null)
  6947. {
  6948. if (reg_type_may_be_null(reg->type) && reg->id == id &&
  6949. !WARN_ON_ONCE(!reg->id)) {
  6950. if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
  6951. !tnum_equals_const(reg->var_off, 0) ||
  6952. reg->off)) {
  6953. /* Old offset (both fixed and variable parts) should
  6954. * have been known-zero, because we don't allow pointer
  6955. * arithmetic on pointers that might be NULL. If we
  6956. * see this happening, don't convert the register.
  6957. */
  6958. return;
  6959. }
  6960. if (is_null) {
  6961. reg->type = SCALAR_VALUE;
  6962. } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  6963. const struct bpf_map *map = reg->map_ptr;
  6964. if (map->inner_map_meta) {
  6965. reg->type = CONST_PTR_TO_MAP;
  6966. reg->map_ptr = map->inner_map_meta;
  6967. } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
  6968. reg->type = PTR_TO_XDP_SOCK;
  6969. } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
  6970. map->map_type == BPF_MAP_TYPE_SOCKHASH) {
  6971. reg->type = PTR_TO_SOCKET;
  6972. } else {
  6973. reg->type = PTR_TO_MAP_VALUE;
  6974. }
  6975. } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
  6976. reg->type = PTR_TO_SOCKET;
  6977. } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
  6978. reg->type = PTR_TO_SOCK_COMMON;
  6979. } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
  6980. reg->type = PTR_TO_TCP_SOCK;
  6981. } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
  6982. reg->type = PTR_TO_BTF_ID;
  6983. } else if (reg->type == PTR_TO_MEM_OR_NULL) {
  6984. reg->type = PTR_TO_MEM;
  6985. } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
  6986. reg->type = PTR_TO_RDONLY_BUF;
  6987. } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
  6988. reg->type = PTR_TO_RDWR_BUF;
  6989. }
  6990. if (is_null) {
  6991. /* We don't need id and ref_obj_id from this point
  6992. * onwards anymore, thus we should better reset it,
  6993. * so that state pruning has chances to take effect.
  6994. */
  6995. reg->id = 0;
  6996. reg->ref_obj_id = 0;
  6997. } else if (!reg_may_point_to_spin_lock(reg)) {
  6998. /* For not-NULL ptr, reg->ref_obj_id will be reset
  6999. * in release_reg_references().
  7000. *
  7001. * reg->id is still used by spin_lock ptr. Other
  7002. * than spin_lock ptr type, reg->id can be reset.
  7003. */
  7004. reg->id = 0;
  7005. }
  7006. }
  7007. }
  7008. static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
  7009. bool is_null)
  7010. {
  7011. struct bpf_reg_state *reg;
  7012. int i;
  7013. for (i = 0; i < MAX_BPF_REG; i++)
  7014. mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
  7015. bpf_for_each_spilled_reg(i, state, reg) {
  7016. if (!reg)
  7017. continue;
  7018. mark_ptr_or_null_reg(state, reg, id, is_null);
  7019. }
  7020. }
  7021. /* The logic is similar to find_good_pkt_pointers(), both could eventually
  7022. * be folded together at some point.
  7023. */
  7024. static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
  7025. bool is_null)
  7026. {
  7027. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  7028. struct bpf_reg_state *regs = state->regs;
  7029. u32 ref_obj_id = regs[regno].ref_obj_id;
  7030. u32 id = regs[regno].id;
  7031. int i;
  7032. if (ref_obj_id && ref_obj_id == id && is_null)
  7033. /* regs[regno] is in the " == NULL" branch.
  7034. * No one could have freed the reference state before
  7035. * doing the NULL check.
  7036. */
  7037. WARN_ON_ONCE(release_reference_state(state, id));
  7038. for (i = 0; i <= vstate->curframe; i++)
  7039. __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
  7040. }
  7041. static bool try_match_pkt_pointers(const struct bpf_insn *insn,
  7042. struct bpf_reg_state *dst_reg,
  7043. struct bpf_reg_state *src_reg,
  7044. struct bpf_verifier_state *this_branch,
  7045. struct bpf_verifier_state *other_branch)
  7046. {
  7047. if (BPF_SRC(insn->code) != BPF_X)
  7048. return false;
  7049. /* Pointers are always 64-bit. */
  7050. if (BPF_CLASS(insn->code) == BPF_JMP32)
  7051. return false;
  7052. switch (BPF_OP(insn->code)) {
  7053. case BPF_JGT:
  7054. if ((dst_reg->type == PTR_TO_PACKET &&
  7055. src_reg->type == PTR_TO_PACKET_END) ||
  7056. (dst_reg->type == PTR_TO_PACKET_META &&
  7057. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  7058. /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
  7059. find_good_pkt_pointers(this_branch, dst_reg,
  7060. dst_reg->type, false);
  7061. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  7062. src_reg->type == PTR_TO_PACKET) ||
  7063. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  7064. src_reg->type == PTR_TO_PACKET_META)) {
  7065. /* pkt_end > pkt_data', pkt_data > pkt_meta' */
  7066. find_good_pkt_pointers(other_branch, src_reg,
  7067. src_reg->type, true);
  7068. } else {
  7069. return false;
  7070. }
  7071. break;
  7072. case BPF_JLT:
  7073. if ((dst_reg->type == PTR_TO_PACKET &&
  7074. src_reg->type == PTR_TO_PACKET_END) ||
  7075. (dst_reg->type == PTR_TO_PACKET_META &&
  7076. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  7077. /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
  7078. find_good_pkt_pointers(other_branch, dst_reg,
  7079. dst_reg->type, true);
  7080. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  7081. src_reg->type == PTR_TO_PACKET) ||
  7082. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  7083. src_reg->type == PTR_TO_PACKET_META)) {
  7084. /* pkt_end < pkt_data', pkt_data > pkt_meta' */
  7085. find_good_pkt_pointers(this_branch, src_reg,
  7086. src_reg->type, false);
  7087. } else {
  7088. return false;
  7089. }
  7090. break;
  7091. case BPF_JGE:
  7092. if ((dst_reg->type == PTR_TO_PACKET &&
  7093. src_reg->type == PTR_TO_PACKET_END) ||
  7094. (dst_reg->type == PTR_TO_PACKET_META &&
  7095. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  7096. /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
  7097. find_good_pkt_pointers(this_branch, dst_reg,
  7098. dst_reg->type, true);
  7099. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  7100. src_reg->type == PTR_TO_PACKET) ||
  7101. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  7102. src_reg->type == PTR_TO_PACKET_META)) {
  7103. /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
  7104. find_good_pkt_pointers(other_branch, src_reg,
  7105. src_reg->type, false);
  7106. } else {
  7107. return false;
  7108. }
  7109. break;
  7110. case BPF_JLE:
  7111. if ((dst_reg->type == PTR_TO_PACKET &&
  7112. src_reg->type == PTR_TO_PACKET_END) ||
  7113. (dst_reg->type == PTR_TO_PACKET_META &&
  7114. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  7115. /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
  7116. find_good_pkt_pointers(other_branch, dst_reg,
  7117. dst_reg->type, false);
  7118. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  7119. src_reg->type == PTR_TO_PACKET) ||
  7120. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  7121. src_reg->type == PTR_TO_PACKET_META)) {
  7122. /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
  7123. find_good_pkt_pointers(this_branch, src_reg,
  7124. src_reg->type, true);
  7125. } else {
  7126. return false;
  7127. }
  7128. break;
  7129. default:
  7130. return false;
  7131. }
  7132. return true;
  7133. }
  7134. static void find_equal_scalars(struct bpf_verifier_state *vstate,
  7135. struct bpf_reg_state *known_reg)
  7136. {
  7137. struct bpf_func_state *state;
  7138. struct bpf_reg_state *reg;
  7139. int i, j;
  7140. for (i = 0; i <= vstate->curframe; i++) {
  7141. state = vstate->frame[i];
  7142. for (j = 0; j < MAX_BPF_REG; j++) {
  7143. reg = &state->regs[j];
  7144. if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
  7145. *reg = *known_reg;
  7146. }
  7147. bpf_for_each_spilled_reg(j, state, reg) {
  7148. if (!reg)
  7149. continue;
  7150. if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
  7151. *reg = *known_reg;
  7152. }
  7153. }
  7154. }
  7155. static int check_cond_jmp_op(struct bpf_verifier_env *env,
  7156. struct bpf_insn *insn, int *insn_idx)
  7157. {
  7158. struct bpf_verifier_state *this_branch = env->cur_state;
  7159. struct bpf_verifier_state *other_branch;
  7160. struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
  7161. struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
  7162. u8 opcode = BPF_OP(insn->code);
  7163. bool is_jmp32;
  7164. int pred = -1;
  7165. int err;
  7166. /* Only conditional jumps are expected to reach here. */
  7167. if (opcode == BPF_JA || opcode > BPF_JSLE) {
  7168. verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
  7169. return -EINVAL;
  7170. }
  7171. if (BPF_SRC(insn->code) == BPF_X) {
  7172. if (insn->imm != 0) {
  7173. verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
  7174. return -EINVAL;
  7175. }
  7176. /* check src1 operand */
  7177. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  7178. if (err)
  7179. return err;
  7180. if (is_pointer_value(env, insn->src_reg)) {
  7181. verbose(env, "R%d pointer comparison prohibited\n",
  7182. insn->src_reg);
  7183. return -EACCES;
  7184. }
  7185. src_reg = &regs[insn->src_reg];
  7186. } else {
  7187. if (insn->src_reg != BPF_REG_0) {
  7188. verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
  7189. return -EINVAL;
  7190. }
  7191. }
  7192. /* check src2 operand */
  7193. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  7194. if (err)
  7195. return err;
  7196. dst_reg = &regs[insn->dst_reg];
  7197. is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
  7198. if (BPF_SRC(insn->code) == BPF_K) {
  7199. pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
  7200. } else if (src_reg->type == SCALAR_VALUE &&
  7201. is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
  7202. pred = is_branch_taken(dst_reg,
  7203. tnum_subreg(src_reg->var_off).value,
  7204. opcode,
  7205. is_jmp32);
  7206. } else if (src_reg->type == SCALAR_VALUE &&
  7207. !is_jmp32 && tnum_is_const(src_reg->var_off)) {
  7208. pred = is_branch_taken(dst_reg,
  7209. src_reg->var_off.value,
  7210. opcode,
  7211. is_jmp32);
  7212. }
  7213. if (pred >= 0) {
  7214. /* If we get here with a dst_reg pointer type it is because
  7215. * above is_branch_taken() special cased the 0 comparison.
  7216. */
  7217. if (!__is_pointer_value(false, dst_reg))
  7218. err = mark_chain_precision(env, insn->dst_reg);
  7219. if (BPF_SRC(insn->code) == BPF_X && !err)
  7220. err = mark_chain_precision(env, insn->src_reg);
  7221. if (err)
  7222. return err;
  7223. }
  7224. if (pred == 1) {
  7225. /* Only follow the goto, ignore fall-through. If needed, push
  7226. * the fall-through branch for simulation under speculative
  7227. * execution.
  7228. */
  7229. if (!env->bypass_spec_v1 &&
  7230. !sanitize_speculative_path(env, insn, *insn_idx + 1,
  7231. *insn_idx))
  7232. return -EFAULT;
  7233. *insn_idx += insn->off;
  7234. return 0;
  7235. } else if (pred == 0) {
  7236. /* Only follow the fall-through branch, since that's where the
  7237. * program will go. If needed, push the goto branch for
  7238. * simulation under speculative execution.
  7239. */
  7240. if (!env->bypass_spec_v1 &&
  7241. !sanitize_speculative_path(env, insn,
  7242. *insn_idx + insn->off + 1,
  7243. *insn_idx))
  7244. return -EFAULT;
  7245. return 0;
  7246. }
  7247. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
  7248. false);
  7249. if (!other_branch)
  7250. return -EFAULT;
  7251. other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
  7252. /* detect if we are comparing against a constant value so we can adjust
  7253. * our min/max values for our dst register.
  7254. * this is only legit if both are scalars (or pointers to the same
  7255. * object, I suppose, but we don't support that right now), because
  7256. * otherwise the different base pointers mean the offsets aren't
  7257. * comparable.
  7258. */
  7259. if (BPF_SRC(insn->code) == BPF_X) {
  7260. struct bpf_reg_state *src_reg = &regs[insn->src_reg];
  7261. if (dst_reg->type == SCALAR_VALUE &&
  7262. src_reg->type == SCALAR_VALUE) {
  7263. if (tnum_is_const(src_reg->var_off) ||
  7264. (is_jmp32 &&
  7265. tnum_is_const(tnum_subreg(src_reg->var_off))))
  7266. reg_set_min_max(&other_branch_regs[insn->dst_reg],
  7267. dst_reg,
  7268. src_reg->var_off.value,
  7269. tnum_subreg(src_reg->var_off).value,
  7270. opcode, is_jmp32);
  7271. else if (tnum_is_const(dst_reg->var_off) ||
  7272. (is_jmp32 &&
  7273. tnum_is_const(tnum_subreg(dst_reg->var_off))))
  7274. reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
  7275. src_reg,
  7276. dst_reg->var_off.value,
  7277. tnum_subreg(dst_reg->var_off).value,
  7278. opcode, is_jmp32);
  7279. else if (!is_jmp32 &&
  7280. (opcode == BPF_JEQ || opcode == BPF_JNE))
  7281. /* Comparing for equality, we can combine knowledge */
  7282. reg_combine_min_max(&other_branch_regs[insn->src_reg],
  7283. &other_branch_regs[insn->dst_reg],
  7284. src_reg, dst_reg, opcode);
  7285. if (src_reg->id &&
  7286. !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
  7287. find_equal_scalars(this_branch, src_reg);
  7288. find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
  7289. }
  7290. }
  7291. } else if (dst_reg->type == SCALAR_VALUE) {
  7292. reg_set_min_max(&other_branch_regs[insn->dst_reg],
  7293. dst_reg, insn->imm, (u32)insn->imm,
  7294. opcode, is_jmp32);
  7295. }
  7296. if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
  7297. !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
  7298. find_equal_scalars(this_branch, dst_reg);
  7299. find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
  7300. }
  7301. /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
  7302. * NOTE: these optimizations below are related with pointer comparison
  7303. * which will never be JMP32.
  7304. */
  7305. if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
  7306. insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  7307. reg_type_may_be_null(dst_reg->type)) {
  7308. /* Mark all identical registers in each branch as either
  7309. * safe or unknown depending R == 0 or R != 0 conditional.
  7310. */
  7311. mark_ptr_or_null_regs(this_branch, insn->dst_reg,
  7312. opcode == BPF_JNE);
  7313. mark_ptr_or_null_regs(other_branch, insn->dst_reg,
  7314. opcode == BPF_JEQ);
  7315. } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
  7316. this_branch, other_branch) &&
  7317. is_pointer_value(env, insn->dst_reg)) {
  7318. verbose(env, "R%d pointer comparison prohibited\n",
  7319. insn->dst_reg);
  7320. return -EACCES;
  7321. }
  7322. if (env->log.level & BPF_LOG_LEVEL)
  7323. print_verifier_state(env, this_branch->frame[this_branch->curframe]);
  7324. return 0;
  7325. }
  7326. /* verify BPF_LD_IMM64 instruction */
  7327. static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
  7328. {
  7329. struct bpf_insn_aux_data *aux = cur_aux(env);
  7330. struct bpf_reg_state *regs = cur_regs(env);
  7331. struct bpf_reg_state *dst_reg;
  7332. struct bpf_map *map;
  7333. int err;
  7334. if (BPF_SIZE(insn->code) != BPF_DW) {
  7335. verbose(env, "invalid BPF_LD_IMM insn\n");
  7336. return -EINVAL;
  7337. }
  7338. if (insn->off != 0) {
  7339. verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
  7340. return -EINVAL;
  7341. }
  7342. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  7343. if (err)
  7344. return err;
  7345. dst_reg = &regs[insn->dst_reg];
  7346. if (insn->src_reg == 0) {
  7347. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  7348. dst_reg->type = SCALAR_VALUE;
  7349. __mark_reg_known(&regs[insn->dst_reg], imm);
  7350. return 0;
  7351. }
  7352. if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
  7353. mark_reg_known_zero(env, regs, insn->dst_reg);
  7354. dst_reg->type = aux->btf_var.reg_type;
  7355. switch (dst_reg->type) {
  7356. case PTR_TO_MEM:
  7357. dst_reg->mem_size = aux->btf_var.mem_size;
  7358. break;
  7359. case PTR_TO_BTF_ID:
  7360. case PTR_TO_PERCPU_BTF_ID:
  7361. dst_reg->btf_id = aux->btf_var.btf_id;
  7362. break;
  7363. default:
  7364. verbose(env, "bpf verifier is misconfigured\n");
  7365. return -EFAULT;
  7366. }
  7367. return 0;
  7368. }
  7369. map = env->used_maps[aux->map_index];
  7370. mark_reg_known_zero(env, regs, insn->dst_reg);
  7371. dst_reg->map_ptr = map;
  7372. if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
  7373. dst_reg->type = PTR_TO_MAP_VALUE;
  7374. dst_reg->off = aux->map_off;
  7375. if (map_value_has_spin_lock(map))
  7376. dst_reg->id = ++env->id_gen;
  7377. } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
  7378. dst_reg->type = CONST_PTR_TO_MAP;
  7379. } else {
  7380. verbose(env, "bpf verifier is misconfigured\n");
  7381. return -EINVAL;
  7382. }
  7383. return 0;
  7384. }
  7385. static bool may_access_skb(enum bpf_prog_type type)
  7386. {
  7387. switch (type) {
  7388. case BPF_PROG_TYPE_SOCKET_FILTER:
  7389. case BPF_PROG_TYPE_SCHED_CLS:
  7390. case BPF_PROG_TYPE_SCHED_ACT:
  7391. return true;
  7392. default:
  7393. return false;
  7394. }
  7395. }
  7396. /* verify safety of LD_ABS|LD_IND instructions:
  7397. * - they can only appear in the programs where ctx == skb
  7398. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  7399. * preserve R6-R9, and store return value into R0
  7400. *
  7401. * Implicit input:
  7402. * ctx == skb == R6 == CTX
  7403. *
  7404. * Explicit input:
  7405. * SRC == any register
  7406. * IMM == 32-bit immediate
  7407. *
  7408. * Output:
  7409. * R0 - 8/16/32-bit skb data converted to cpu endianness
  7410. */
  7411. static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
  7412. {
  7413. struct bpf_reg_state *regs = cur_regs(env);
  7414. static const int ctx_reg = BPF_REG_6;
  7415. u8 mode = BPF_MODE(insn->code);
  7416. int i, err;
  7417. if (!may_access_skb(resolve_prog_type(env->prog))) {
  7418. verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
  7419. return -EINVAL;
  7420. }
  7421. if (!env->ops->gen_ld_abs) {
  7422. verbose(env, "bpf verifier is misconfigured\n");
  7423. return -EINVAL;
  7424. }
  7425. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  7426. BPF_SIZE(insn->code) == BPF_DW ||
  7427. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  7428. verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
  7429. return -EINVAL;
  7430. }
  7431. /* check whether implicit source operand (register R6) is readable */
  7432. err = check_reg_arg(env, ctx_reg, SRC_OP);
  7433. if (err)
  7434. return err;
  7435. /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
  7436. * gen_ld_abs() may terminate the program at runtime, leading to
  7437. * reference leak.
  7438. */
  7439. err = check_reference_leak(env);
  7440. if (err) {
  7441. verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
  7442. return err;
  7443. }
  7444. if (env->cur_state->active_spin_lock) {
  7445. verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
  7446. return -EINVAL;
  7447. }
  7448. if (regs[ctx_reg].type != PTR_TO_CTX) {
  7449. verbose(env,
  7450. "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  7451. return -EINVAL;
  7452. }
  7453. if (mode == BPF_IND) {
  7454. /* check explicit source operand */
  7455. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  7456. if (err)
  7457. return err;
  7458. }
  7459. err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
  7460. if (err < 0)
  7461. return err;
  7462. /* reset caller saved regs to unreadable */
  7463. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  7464. mark_reg_not_init(env, regs, caller_saved[i]);
  7465. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  7466. }
  7467. /* mark destination R0 register as readable, since it contains
  7468. * the value fetched from the packet.
  7469. * Already marked as written above.
  7470. */
  7471. mark_reg_unknown(env, regs, BPF_REG_0);
  7472. /* ld_abs load up to 32-bit skb data. */
  7473. regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
  7474. return 0;
  7475. }
  7476. static int check_return_code(struct bpf_verifier_env *env)
  7477. {
  7478. struct tnum enforce_attach_type_range = tnum_unknown;
  7479. const struct bpf_prog *prog = env->prog;
  7480. struct bpf_reg_state *reg;
  7481. struct tnum range = tnum_range(0, 1);
  7482. enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
  7483. int err;
  7484. const bool is_subprog = env->cur_state->frame[0]->subprogno;
  7485. /* LSM and struct_ops func-ptr's return type could be "void" */
  7486. if (!is_subprog &&
  7487. (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
  7488. prog_type == BPF_PROG_TYPE_LSM) &&
  7489. !prog->aux->attach_func_proto->type)
  7490. return 0;
  7491. /* eBPF calling convetion is such that R0 is used
  7492. * to return the value from eBPF program.
  7493. * Make sure that it's readable at this time
  7494. * of bpf_exit, which means that program wrote
  7495. * something into it earlier
  7496. */
  7497. err = check_reg_arg(env, BPF_REG_0, SRC_OP);
  7498. if (err)
  7499. return err;
  7500. if (is_pointer_value(env, BPF_REG_0)) {
  7501. verbose(env, "R0 leaks addr as return value\n");
  7502. return -EACCES;
  7503. }
  7504. reg = cur_regs(env) + BPF_REG_0;
  7505. if (is_subprog) {
  7506. if (reg->type != SCALAR_VALUE) {
  7507. verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
  7508. reg_type_str[reg->type]);
  7509. return -EINVAL;
  7510. }
  7511. return 0;
  7512. }
  7513. switch (prog_type) {
  7514. case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
  7515. if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
  7516. env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
  7517. env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
  7518. env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
  7519. env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
  7520. env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
  7521. range = tnum_range(1, 1);
  7522. break;
  7523. case BPF_PROG_TYPE_CGROUP_SKB:
  7524. if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
  7525. range = tnum_range(0, 3);
  7526. enforce_attach_type_range = tnum_range(2, 3);
  7527. }
  7528. break;
  7529. case BPF_PROG_TYPE_CGROUP_SOCK:
  7530. case BPF_PROG_TYPE_SOCK_OPS:
  7531. case BPF_PROG_TYPE_CGROUP_DEVICE:
  7532. case BPF_PROG_TYPE_CGROUP_SYSCTL:
  7533. case BPF_PROG_TYPE_CGROUP_SOCKOPT:
  7534. break;
  7535. case BPF_PROG_TYPE_RAW_TRACEPOINT:
  7536. if (!env->prog->aux->attach_btf_id)
  7537. return 0;
  7538. range = tnum_const(0);
  7539. break;
  7540. case BPF_PROG_TYPE_TRACING:
  7541. switch (env->prog->expected_attach_type) {
  7542. case BPF_TRACE_FENTRY:
  7543. case BPF_TRACE_FEXIT:
  7544. range = tnum_const(0);
  7545. break;
  7546. case BPF_TRACE_RAW_TP:
  7547. case BPF_MODIFY_RETURN:
  7548. return 0;
  7549. case BPF_TRACE_ITER:
  7550. break;
  7551. default:
  7552. return -ENOTSUPP;
  7553. }
  7554. break;
  7555. case BPF_PROG_TYPE_SK_LOOKUP:
  7556. range = tnum_range(SK_DROP, SK_PASS);
  7557. break;
  7558. case BPF_PROG_TYPE_EXT:
  7559. /* freplace program can return anything as its return value
  7560. * depends on the to-be-replaced kernel func or bpf program.
  7561. */
  7562. default:
  7563. return 0;
  7564. }
  7565. if (reg->type != SCALAR_VALUE) {
  7566. verbose(env, "At program exit the register R0 is not a known value (%s)\n",
  7567. reg_type_str[reg->type]);
  7568. return -EINVAL;
  7569. }
  7570. if (!tnum_in(range, reg->var_off)) {
  7571. char tn_buf[48];
  7572. verbose(env, "At program exit the register R0 ");
  7573. if (!tnum_is_unknown(reg->var_off)) {
  7574. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  7575. verbose(env, "has value %s", tn_buf);
  7576. } else {
  7577. verbose(env, "has unknown scalar value");
  7578. }
  7579. tnum_strn(tn_buf, sizeof(tn_buf), range);
  7580. verbose(env, " should have been in %s\n", tn_buf);
  7581. return -EINVAL;
  7582. }
  7583. if (!tnum_is_unknown(enforce_attach_type_range) &&
  7584. tnum_in(enforce_attach_type_range, reg->var_off))
  7585. env->prog->enforce_expected_attach_type = 1;
  7586. return 0;
  7587. }
  7588. /* non-recursive DFS pseudo code
  7589. * 1 procedure DFS-iterative(G,v):
  7590. * 2 label v as discovered
  7591. * 3 let S be a stack
  7592. * 4 S.push(v)
  7593. * 5 while S is not empty
  7594. * 6 t <- S.pop()
  7595. * 7 if t is what we're looking for:
  7596. * 8 return t
  7597. * 9 for all edges e in G.adjacentEdges(t) do
  7598. * 10 if edge e is already labelled
  7599. * 11 continue with the next edge
  7600. * 12 w <- G.adjacentVertex(t,e)
  7601. * 13 if vertex w is not discovered and not explored
  7602. * 14 label e as tree-edge
  7603. * 15 label w as discovered
  7604. * 16 S.push(w)
  7605. * 17 continue at 5
  7606. * 18 else if vertex w is discovered
  7607. * 19 label e as back-edge
  7608. * 20 else
  7609. * 21 // vertex w is explored
  7610. * 22 label e as forward- or cross-edge
  7611. * 23 label t as explored
  7612. * 24 S.pop()
  7613. *
  7614. * convention:
  7615. * 0x10 - discovered
  7616. * 0x11 - discovered and fall-through edge labelled
  7617. * 0x12 - discovered and fall-through and branch edges labelled
  7618. * 0x20 - explored
  7619. */
  7620. enum {
  7621. DISCOVERED = 0x10,
  7622. EXPLORED = 0x20,
  7623. FALLTHROUGH = 1,
  7624. BRANCH = 2,
  7625. };
  7626. static u32 state_htab_size(struct bpf_verifier_env *env)
  7627. {
  7628. return env->prog->len;
  7629. }
  7630. static struct bpf_verifier_state_list **explored_state(
  7631. struct bpf_verifier_env *env,
  7632. int idx)
  7633. {
  7634. struct bpf_verifier_state *cur = env->cur_state;
  7635. struct bpf_func_state *state = cur->frame[cur->curframe];
  7636. return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
  7637. }
  7638. static void init_explored_state(struct bpf_verifier_env *env, int idx)
  7639. {
  7640. env->insn_aux_data[idx].prune_point = true;
  7641. }
  7642. /* t, w, e - match pseudo-code above:
  7643. * t - index of current instruction
  7644. * w - next instruction
  7645. * e - edge
  7646. */
  7647. static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
  7648. bool loop_ok)
  7649. {
  7650. int *insn_stack = env->cfg.insn_stack;
  7651. int *insn_state = env->cfg.insn_state;
  7652. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  7653. return 0;
  7654. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  7655. return 0;
  7656. if (w < 0 || w >= env->prog->len) {
  7657. verbose_linfo(env, t, "%d: ", t);
  7658. verbose(env, "jump out of range from insn %d to %d\n", t, w);
  7659. return -EINVAL;
  7660. }
  7661. if (e == BRANCH)
  7662. /* mark branch target for state pruning */
  7663. init_explored_state(env, w);
  7664. if (insn_state[w] == 0) {
  7665. /* tree-edge */
  7666. insn_state[t] = DISCOVERED | e;
  7667. insn_state[w] = DISCOVERED;
  7668. if (env->cfg.cur_stack >= env->prog->len)
  7669. return -E2BIG;
  7670. insn_stack[env->cfg.cur_stack++] = w;
  7671. return 1;
  7672. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  7673. if (loop_ok && env->bpf_capable)
  7674. return 0;
  7675. verbose_linfo(env, t, "%d: ", t);
  7676. verbose_linfo(env, w, "%d: ", w);
  7677. verbose(env, "back-edge from insn %d to %d\n", t, w);
  7678. return -EINVAL;
  7679. } else if (insn_state[w] == EXPLORED) {
  7680. /* forward- or cross-edge */
  7681. insn_state[t] = DISCOVERED | e;
  7682. } else {
  7683. verbose(env, "insn state internal bug\n");
  7684. return -EFAULT;
  7685. }
  7686. return 0;
  7687. }
  7688. /* non-recursive depth-first-search to detect loops in BPF program
  7689. * loop == back-edge in directed graph
  7690. */
  7691. static int check_cfg(struct bpf_verifier_env *env)
  7692. {
  7693. struct bpf_insn *insns = env->prog->insnsi;
  7694. int insn_cnt = env->prog->len;
  7695. int *insn_stack, *insn_state;
  7696. int ret = 0;
  7697. int i, t;
  7698. insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  7699. if (!insn_state)
  7700. return -ENOMEM;
  7701. insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  7702. if (!insn_stack) {
  7703. kvfree(insn_state);
  7704. return -ENOMEM;
  7705. }
  7706. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  7707. insn_stack[0] = 0; /* 0 is the first instruction */
  7708. env->cfg.cur_stack = 1;
  7709. peek_stack:
  7710. if (env->cfg.cur_stack == 0)
  7711. goto check_state;
  7712. t = insn_stack[env->cfg.cur_stack - 1];
  7713. if (BPF_CLASS(insns[t].code) == BPF_JMP ||
  7714. BPF_CLASS(insns[t].code) == BPF_JMP32) {
  7715. u8 opcode = BPF_OP(insns[t].code);
  7716. if (opcode == BPF_EXIT) {
  7717. goto mark_explored;
  7718. } else if (opcode == BPF_CALL) {
  7719. ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
  7720. if (ret == 1)
  7721. goto peek_stack;
  7722. else if (ret < 0)
  7723. goto err_free;
  7724. if (t + 1 < insn_cnt)
  7725. init_explored_state(env, t + 1);
  7726. if (insns[t].src_reg == BPF_PSEUDO_CALL) {
  7727. init_explored_state(env, t);
  7728. ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
  7729. env, false);
  7730. if (ret == 1)
  7731. goto peek_stack;
  7732. else if (ret < 0)
  7733. goto err_free;
  7734. }
  7735. } else if (opcode == BPF_JA) {
  7736. if (BPF_SRC(insns[t].code) != BPF_K) {
  7737. ret = -EINVAL;
  7738. goto err_free;
  7739. }
  7740. /* unconditional jump with single edge */
  7741. ret = push_insn(t, t + insns[t].off + 1,
  7742. FALLTHROUGH, env, true);
  7743. if (ret == 1)
  7744. goto peek_stack;
  7745. else if (ret < 0)
  7746. goto err_free;
  7747. /* unconditional jmp is not a good pruning point,
  7748. * but it's marked, since backtracking needs
  7749. * to record jmp history in is_state_visited().
  7750. */
  7751. init_explored_state(env, t + insns[t].off + 1);
  7752. /* tell verifier to check for equivalent states
  7753. * after every call and jump
  7754. */
  7755. if (t + 1 < insn_cnt)
  7756. init_explored_state(env, t + 1);
  7757. } else {
  7758. /* conditional jump with two edges */
  7759. init_explored_state(env, t);
  7760. ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
  7761. if (ret == 1)
  7762. goto peek_stack;
  7763. else if (ret < 0)
  7764. goto err_free;
  7765. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
  7766. if (ret == 1)
  7767. goto peek_stack;
  7768. else if (ret < 0)
  7769. goto err_free;
  7770. }
  7771. } else {
  7772. /* all other non-branch instructions with single
  7773. * fall-through edge
  7774. */
  7775. ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
  7776. if (ret == 1)
  7777. goto peek_stack;
  7778. else if (ret < 0)
  7779. goto err_free;
  7780. }
  7781. mark_explored:
  7782. insn_state[t] = EXPLORED;
  7783. if (env->cfg.cur_stack-- <= 0) {
  7784. verbose(env, "pop stack internal bug\n");
  7785. ret = -EFAULT;
  7786. goto err_free;
  7787. }
  7788. goto peek_stack;
  7789. check_state:
  7790. for (i = 0; i < insn_cnt; i++) {
  7791. if (insn_state[i] != EXPLORED) {
  7792. verbose(env, "unreachable insn %d\n", i);
  7793. ret = -EINVAL;
  7794. goto err_free;
  7795. }
  7796. }
  7797. ret = 0; /* cfg looks good */
  7798. err_free:
  7799. kvfree(insn_state);
  7800. kvfree(insn_stack);
  7801. env->cfg.insn_state = env->cfg.insn_stack = NULL;
  7802. return ret;
  7803. }
  7804. static int check_abnormal_return(struct bpf_verifier_env *env)
  7805. {
  7806. int i;
  7807. for (i = 1; i < env->subprog_cnt; i++) {
  7808. if (env->subprog_info[i].has_ld_abs) {
  7809. verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
  7810. return -EINVAL;
  7811. }
  7812. if (env->subprog_info[i].has_tail_call) {
  7813. verbose(env, "tail_call is not allowed in subprogs without BTF\n");
  7814. return -EINVAL;
  7815. }
  7816. }
  7817. return 0;
  7818. }
  7819. /* The minimum supported BTF func info size */
  7820. #define MIN_BPF_FUNCINFO_SIZE 8
  7821. #define MAX_FUNCINFO_REC_SIZE 252
  7822. static int check_btf_func(struct bpf_verifier_env *env,
  7823. const union bpf_attr *attr,
  7824. union bpf_attr __user *uattr)
  7825. {
  7826. const struct btf_type *type, *func_proto, *ret_type;
  7827. u32 i, nfuncs, urec_size, min_size;
  7828. u32 krec_size = sizeof(struct bpf_func_info);
  7829. struct bpf_func_info *krecord;
  7830. struct bpf_func_info_aux *info_aux = NULL;
  7831. struct bpf_prog *prog;
  7832. const struct btf *btf;
  7833. void __user *urecord;
  7834. u32 prev_offset = 0;
  7835. bool scalar_return;
  7836. int ret = -ENOMEM;
  7837. nfuncs = attr->func_info_cnt;
  7838. if (!nfuncs) {
  7839. if (check_abnormal_return(env))
  7840. return -EINVAL;
  7841. return 0;
  7842. }
  7843. if (nfuncs != env->subprog_cnt) {
  7844. verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
  7845. return -EINVAL;
  7846. }
  7847. urec_size = attr->func_info_rec_size;
  7848. if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
  7849. urec_size > MAX_FUNCINFO_REC_SIZE ||
  7850. urec_size % sizeof(u32)) {
  7851. verbose(env, "invalid func info rec size %u\n", urec_size);
  7852. return -EINVAL;
  7853. }
  7854. prog = env->prog;
  7855. btf = prog->aux->btf;
  7856. urecord = u64_to_user_ptr(attr->func_info);
  7857. min_size = min_t(u32, krec_size, urec_size);
  7858. krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
  7859. if (!krecord)
  7860. return -ENOMEM;
  7861. info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
  7862. if (!info_aux)
  7863. goto err_free;
  7864. for (i = 0; i < nfuncs; i++) {
  7865. ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
  7866. if (ret) {
  7867. if (ret == -E2BIG) {
  7868. verbose(env, "nonzero tailing record in func info");
  7869. /* set the size kernel expects so loader can zero
  7870. * out the rest of the record.
  7871. */
  7872. if (put_user(min_size, &uattr->func_info_rec_size))
  7873. ret = -EFAULT;
  7874. }
  7875. goto err_free;
  7876. }
  7877. if (copy_from_user(&krecord[i], urecord, min_size)) {
  7878. ret = -EFAULT;
  7879. goto err_free;
  7880. }
  7881. /* check insn_off */
  7882. ret = -EINVAL;
  7883. if (i == 0) {
  7884. if (krecord[i].insn_off) {
  7885. verbose(env,
  7886. "nonzero insn_off %u for the first func info record",
  7887. krecord[i].insn_off);
  7888. goto err_free;
  7889. }
  7890. } else if (krecord[i].insn_off <= prev_offset) {
  7891. verbose(env,
  7892. "same or smaller insn offset (%u) than previous func info record (%u)",
  7893. krecord[i].insn_off, prev_offset);
  7894. goto err_free;
  7895. }
  7896. if (env->subprog_info[i].start != krecord[i].insn_off) {
  7897. verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
  7898. goto err_free;
  7899. }
  7900. /* check type_id */
  7901. type = btf_type_by_id(btf, krecord[i].type_id);
  7902. if (!type || !btf_type_is_func(type)) {
  7903. verbose(env, "invalid type id %d in func info",
  7904. krecord[i].type_id);
  7905. goto err_free;
  7906. }
  7907. info_aux[i].linkage = BTF_INFO_VLEN(type->info);
  7908. func_proto = btf_type_by_id(btf, type->type);
  7909. if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
  7910. /* btf_func_check() already verified it during BTF load */
  7911. goto err_free;
  7912. ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
  7913. scalar_return =
  7914. btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
  7915. if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
  7916. verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
  7917. goto err_free;
  7918. }
  7919. if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
  7920. verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
  7921. goto err_free;
  7922. }
  7923. prev_offset = krecord[i].insn_off;
  7924. urecord += urec_size;
  7925. }
  7926. prog->aux->func_info = krecord;
  7927. prog->aux->func_info_cnt = nfuncs;
  7928. prog->aux->func_info_aux = info_aux;
  7929. return 0;
  7930. err_free:
  7931. kvfree(krecord);
  7932. kfree(info_aux);
  7933. return ret;
  7934. }
  7935. static void adjust_btf_func(struct bpf_verifier_env *env)
  7936. {
  7937. struct bpf_prog_aux *aux = env->prog->aux;
  7938. int i;
  7939. if (!aux->func_info)
  7940. return;
  7941. for (i = 0; i < env->subprog_cnt; i++)
  7942. aux->func_info[i].insn_off = env->subprog_info[i].start;
  7943. }
  7944. #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
  7945. sizeof(((struct bpf_line_info *)(0))->line_col))
  7946. #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
  7947. static int check_btf_line(struct bpf_verifier_env *env,
  7948. const union bpf_attr *attr,
  7949. union bpf_attr __user *uattr)
  7950. {
  7951. u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
  7952. struct bpf_subprog_info *sub;
  7953. struct bpf_line_info *linfo;
  7954. struct bpf_prog *prog;
  7955. const struct btf *btf;
  7956. void __user *ulinfo;
  7957. int err;
  7958. nr_linfo = attr->line_info_cnt;
  7959. if (!nr_linfo)
  7960. return 0;
  7961. if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
  7962. return -EINVAL;
  7963. rec_size = attr->line_info_rec_size;
  7964. if (rec_size < MIN_BPF_LINEINFO_SIZE ||
  7965. rec_size > MAX_LINEINFO_REC_SIZE ||
  7966. rec_size & (sizeof(u32) - 1))
  7967. return -EINVAL;
  7968. /* Need to zero it in case the userspace may
  7969. * pass in a smaller bpf_line_info object.
  7970. */
  7971. linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
  7972. GFP_KERNEL | __GFP_NOWARN);
  7973. if (!linfo)
  7974. return -ENOMEM;
  7975. prog = env->prog;
  7976. btf = prog->aux->btf;
  7977. s = 0;
  7978. sub = env->subprog_info;
  7979. ulinfo = u64_to_user_ptr(attr->line_info);
  7980. expected_size = sizeof(struct bpf_line_info);
  7981. ncopy = min_t(u32, expected_size, rec_size);
  7982. for (i = 0; i < nr_linfo; i++) {
  7983. err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
  7984. if (err) {
  7985. if (err == -E2BIG) {
  7986. verbose(env, "nonzero tailing record in line_info");
  7987. if (put_user(expected_size,
  7988. &uattr->line_info_rec_size))
  7989. err = -EFAULT;
  7990. }
  7991. goto err_free;
  7992. }
  7993. if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
  7994. err = -EFAULT;
  7995. goto err_free;
  7996. }
  7997. /*
  7998. * Check insn_off to ensure
  7999. * 1) strictly increasing AND
  8000. * 2) bounded by prog->len
  8001. *
  8002. * The linfo[0].insn_off == 0 check logically falls into
  8003. * the later "missing bpf_line_info for func..." case
  8004. * because the first linfo[0].insn_off must be the
  8005. * first sub also and the first sub must have
  8006. * subprog_info[0].start == 0.
  8007. */
  8008. if ((i && linfo[i].insn_off <= prev_offset) ||
  8009. linfo[i].insn_off >= prog->len) {
  8010. verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
  8011. i, linfo[i].insn_off, prev_offset,
  8012. prog->len);
  8013. err = -EINVAL;
  8014. goto err_free;
  8015. }
  8016. if (!prog->insnsi[linfo[i].insn_off].code) {
  8017. verbose(env,
  8018. "Invalid insn code at line_info[%u].insn_off\n",
  8019. i);
  8020. err = -EINVAL;
  8021. goto err_free;
  8022. }
  8023. if (!btf_name_by_offset(btf, linfo[i].line_off) ||
  8024. !btf_name_by_offset(btf, linfo[i].file_name_off)) {
  8025. verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
  8026. err = -EINVAL;
  8027. goto err_free;
  8028. }
  8029. if (s != env->subprog_cnt) {
  8030. if (linfo[i].insn_off == sub[s].start) {
  8031. sub[s].linfo_idx = i;
  8032. s++;
  8033. } else if (sub[s].start < linfo[i].insn_off) {
  8034. verbose(env, "missing bpf_line_info for func#%u\n", s);
  8035. err = -EINVAL;
  8036. goto err_free;
  8037. }
  8038. }
  8039. prev_offset = linfo[i].insn_off;
  8040. ulinfo += rec_size;
  8041. }
  8042. if (s != env->subprog_cnt) {
  8043. verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
  8044. env->subprog_cnt - s, s);
  8045. err = -EINVAL;
  8046. goto err_free;
  8047. }
  8048. prog->aux->linfo = linfo;
  8049. prog->aux->nr_linfo = nr_linfo;
  8050. return 0;
  8051. err_free:
  8052. kvfree(linfo);
  8053. return err;
  8054. }
  8055. static int check_btf_info(struct bpf_verifier_env *env,
  8056. const union bpf_attr *attr,
  8057. union bpf_attr __user *uattr)
  8058. {
  8059. struct btf *btf;
  8060. int err;
  8061. if (!attr->func_info_cnt && !attr->line_info_cnt) {
  8062. if (check_abnormal_return(env))
  8063. return -EINVAL;
  8064. return 0;
  8065. }
  8066. btf = btf_get_by_fd(attr->prog_btf_fd);
  8067. if (IS_ERR(btf))
  8068. return PTR_ERR(btf);
  8069. env->prog->aux->btf = btf;
  8070. err = check_btf_func(env, attr, uattr);
  8071. if (err)
  8072. return err;
  8073. err = check_btf_line(env, attr, uattr);
  8074. if (err)
  8075. return err;
  8076. return 0;
  8077. }
  8078. /* check %cur's range satisfies %old's */
  8079. static bool range_within(struct bpf_reg_state *old,
  8080. struct bpf_reg_state *cur)
  8081. {
  8082. return old->umin_value <= cur->umin_value &&
  8083. old->umax_value >= cur->umax_value &&
  8084. old->smin_value <= cur->smin_value &&
  8085. old->smax_value >= cur->smax_value &&
  8086. old->u32_min_value <= cur->u32_min_value &&
  8087. old->u32_max_value >= cur->u32_max_value &&
  8088. old->s32_min_value <= cur->s32_min_value &&
  8089. old->s32_max_value >= cur->s32_max_value;
  8090. }
  8091. /* If in the old state two registers had the same id, then they need to have
  8092. * the same id in the new state as well. But that id could be different from
  8093. * the old state, so we need to track the mapping from old to new ids.
  8094. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
  8095. * regs with old id 5 must also have new id 9 for the new state to be safe. But
  8096. * regs with a different old id could still have new id 9, we don't care about
  8097. * that.
  8098. * So we look through our idmap to see if this old id has been seen before. If
  8099. * so, we require the new id to match; otherwise, we add the id pair to the map.
  8100. */
  8101. static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
  8102. {
  8103. unsigned int i;
  8104. for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
  8105. if (!idmap[i].old) {
  8106. /* Reached an empty slot; haven't seen this id before */
  8107. idmap[i].old = old_id;
  8108. idmap[i].cur = cur_id;
  8109. return true;
  8110. }
  8111. if (idmap[i].old == old_id)
  8112. return idmap[i].cur == cur_id;
  8113. }
  8114. /* We ran out of idmap slots, which should be impossible */
  8115. WARN_ON_ONCE(1);
  8116. return false;
  8117. }
  8118. static void clean_func_state(struct bpf_verifier_env *env,
  8119. struct bpf_func_state *st)
  8120. {
  8121. enum bpf_reg_liveness live;
  8122. int i, j;
  8123. for (i = 0; i < BPF_REG_FP; i++) {
  8124. live = st->regs[i].live;
  8125. /* liveness must not touch this register anymore */
  8126. st->regs[i].live |= REG_LIVE_DONE;
  8127. if (!(live & REG_LIVE_READ))
  8128. /* since the register is unused, clear its state
  8129. * to make further comparison simpler
  8130. */
  8131. __mark_reg_not_init(env, &st->regs[i]);
  8132. }
  8133. for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
  8134. live = st->stack[i].spilled_ptr.live;
  8135. /* liveness must not touch this stack slot anymore */
  8136. st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
  8137. if (!(live & REG_LIVE_READ)) {
  8138. __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
  8139. for (j = 0; j < BPF_REG_SIZE; j++)
  8140. st->stack[i].slot_type[j] = STACK_INVALID;
  8141. }
  8142. }
  8143. }
  8144. static void clean_verifier_state(struct bpf_verifier_env *env,
  8145. struct bpf_verifier_state *st)
  8146. {
  8147. int i;
  8148. if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
  8149. /* all regs in this state in all frames were already marked */
  8150. return;
  8151. for (i = 0; i <= st->curframe; i++)
  8152. clean_func_state(env, st->frame[i]);
  8153. }
  8154. /* the parentage chains form a tree.
  8155. * the verifier states are added to state lists at given insn and
  8156. * pushed into state stack for future exploration.
  8157. * when the verifier reaches bpf_exit insn some of the verifer states
  8158. * stored in the state lists have their final liveness state already,
  8159. * but a lot of states will get revised from liveness point of view when
  8160. * the verifier explores other branches.
  8161. * Example:
  8162. * 1: r0 = 1
  8163. * 2: if r1 == 100 goto pc+1
  8164. * 3: r0 = 2
  8165. * 4: exit
  8166. * when the verifier reaches exit insn the register r0 in the state list of
  8167. * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
  8168. * of insn 2 and goes exploring further. At the insn 4 it will walk the
  8169. * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
  8170. *
  8171. * Since the verifier pushes the branch states as it sees them while exploring
  8172. * the program the condition of walking the branch instruction for the second
  8173. * time means that all states below this branch were already explored and
  8174. * their final liveness markes are already propagated.
  8175. * Hence when the verifier completes the search of state list in is_state_visited()
  8176. * we can call this clean_live_states() function to mark all liveness states
  8177. * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
  8178. * will not be used.
  8179. * This function also clears the registers and stack for states that !READ
  8180. * to simplify state merging.
  8181. *
  8182. * Important note here that walking the same branch instruction in the callee
  8183. * doesn't meant that the states are DONE. The verifier has to compare
  8184. * the callsites
  8185. */
  8186. static void clean_live_states(struct bpf_verifier_env *env, int insn,
  8187. struct bpf_verifier_state *cur)
  8188. {
  8189. struct bpf_verifier_state_list *sl;
  8190. int i;
  8191. sl = *explored_state(env, insn);
  8192. while (sl) {
  8193. if (sl->state.branches)
  8194. goto next;
  8195. if (sl->state.insn_idx != insn ||
  8196. sl->state.curframe != cur->curframe)
  8197. goto next;
  8198. for (i = 0; i <= cur->curframe; i++)
  8199. if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
  8200. goto next;
  8201. clean_verifier_state(env, &sl->state);
  8202. next:
  8203. sl = sl->next;
  8204. }
  8205. }
  8206. /* Returns true if (rold safe implies rcur safe) */
  8207. static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
  8208. struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
  8209. {
  8210. bool equal;
  8211. if (!(rold->live & REG_LIVE_READ))
  8212. /* explored state didn't use this */
  8213. return true;
  8214. equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
  8215. if (rold->type == PTR_TO_STACK)
  8216. /* two stack pointers are equal only if they're pointing to
  8217. * the same stack frame, since fp-8 in foo != fp-8 in bar
  8218. */
  8219. return equal && rold->frameno == rcur->frameno;
  8220. if (equal)
  8221. return true;
  8222. if (rold->type == NOT_INIT)
  8223. /* explored state can't have used this */
  8224. return true;
  8225. if (rcur->type == NOT_INIT)
  8226. return false;
  8227. switch (rold->type) {
  8228. case SCALAR_VALUE:
  8229. if (env->explore_alu_limits)
  8230. return false;
  8231. if (rcur->type == SCALAR_VALUE) {
  8232. if (!rold->precise && !rcur->precise)
  8233. return true;
  8234. /* new val must satisfy old val knowledge */
  8235. return range_within(rold, rcur) &&
  8236. tnum_in(rold->var_off, rcur->var_off);
  8237. } else {
  8238. /* We're trying to use a pointer in place of a scalar.
  8239. * Even if the scalar was unbounded, this could lead to
  8240. * pointer leaks because scalars are allowed to leak
  8241. * while pointers are not. We could make this safe in
  8242. * special cases if root is calling us, but it's
  8243. * probably not worth the hassle.
  8244. */
  8245. return false;
  8246. }
  8247. case PTR_TO_MAP_VALUE:
  8248. /* If the new min/max/var_off satisfy the old ones and
  8249. * everything else matches, we are OK.
  8250. * 'id' is not compared, since it's only used for maps with
  8251. * bpf_spin_lock inside map element and in such cases if
  8252. * the rest of the prog is valid for one map element then
  8253. * it's valid for all map elements regardless of the key
  8254. * used in bpf_map_lookup()
  8255. */
  8256. return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
  8257. range_within(rold, rcur) &&
  8258. tnum_in(rold->var_off, rcur->var_off);
  8259. case PTR_TO_MAP_VALUE_OR_NULL:
  8260. /* a PTR_TO_MAP_VALUE could be safe to use as a
  8261. * PTR_TO_MAP_VALUE_OR_NULL into the same map.
  8262. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
  8263. * checked, doing so could have affected others with the same
  8264. * id, and we can't check for that because we lost the id when
  8265. * we converted to a PTR_TO_MAP_VALUE.
  8266. */
  8267. if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
  8268. return false;
  8269. if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
  8270. return false;
  8271. /* Check our ids match any regs they're supposed to */
  8272. return check_ids(rold->id, rcur->id, idmap);
  8273. case PTR_TO_PACKET_META:
  8274. case PTR_TO_PACKET:
  8275. if (rcur->type != rold->type)
  8276. return false;
  8277. /* We must have at least as much range as the old ptr
  8278. * did, so that any accesses which were safe before are
  8279. * still safe. This is true even if old range < old off,
  8280. * since someone could have accessed through (ptr - k), or
  8281. * even done ptr -= k in a register, to get a safe access.
  8282. */
  8283. if (rold->range > rcur->range)
  8284. return false;
  8285. /* If the offsets don't match, we can't trust our alignment;
  8286. * nor can we be sure that we won't fall out of range.
  8287. */
  8288. if (rold->off != rcur->off)
  8289. return false;
  8290. /* id relations must be preserved */
  8291. if (rold->id && !check_ids(rold->id, rcur->id, idmap))
  8292. return false;
  8293. /* new val must satisfy old val knowledge */
  8294. return range_within(rold, rcur) &&
  8295. tnum_in(rold->var_off, rcur->var_off);
  8296. case PTR_TO_CTX:
  8297. case CONST_PTR_TO_MAP:
  8298. case PTR_TO_PACKET_END:
  8299. case PTR_TO_FLOW_KEYS:
  8300. case PTR_TO_SOCKET:
  8301. case PTR_TO_SOCKET_OR_NULL:
  8302. case PTR_TO_SOCK_COMMON:
  8303. case PTR_TO_SOCK_COMMON_OR_NULL:
  8304. case PTR_TO_TCP_SOCK:
  8305. case PTR_TO_TCP_SOCK_OR_NULL:
  8306. case PTR_TO_XDP_SOCK:
  8307. /* Only valid matches are exact, which memcmp() above
  8308. * would have accepted
  8309. */
  8310. default:
  8311. /* Don't know what's going on, just say it's not safe */
  8312. return false;
  8313. }
  8314. /* Shouldn't get here; if we do, say it's not safe */
  8315. WARN_ON_ONCE(1);
  8316. return false;
  8317. }
  8318. static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
  8319. struct bpf_func_state *cur, struct bpf_id_pair *idmap)
  8320. {
  8321. int i, spi;
  8322. /* walk slots of the explored stack and ignore any additional
  8323. * slots in the current stack, since explored(safe) state
  8324. * didn't use them
  8325. */
  8326. for (i = 0; i < old->allocated_stack; i++) {
  8327. spi = i / BPF_REG_SIZE;
  8328. if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
  8329. i += BPF_REG_SIZE - 1;
  8330. /* explored state didn't use this */
  8331. continue;
  8332. }
  8333. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
  8334. continue;
  8335. /* explored stack has more populated slots than current stack
  8336. * and these slots were used
  8337. */
  8338. if (i >= cur->allocated_stack)
  8339. return false;
  8340. /* if old state was safe with misc data in the stack
  8341. * it will be safe with zero-initialized stack.
  8342. * The opposite is not true
  8343. */
  8344. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
  8345. cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
  8346. continue;
  8347. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
  8348. cur->stack[spi].slot_type[i % BPF_REG_SIZE])
  8349. /* Ex: old explored (safe) state has STACK_SPILL in
  8350. * this stack slot, but current has STACK_MISC ->
  8351. * this verifier states are not equivalent,
  8352. * return false to continue verification of this path
  8353. */
  8354. return false;
  8355. if (i % BPF_REG_SIZE)
  8356. continue;
  8357. if (old->stack[spi].slot_type[0] != STACK_SPILL)
  8358. continue;
  8359. if (!regsafe(env, &old->stack[spi].spilled_ptr,
  8360. &cur->stack[spi].spilled_ptr, idmap))
  8361. /* when explored and current stack slot are both storing
  8362. * spilled registers, check that stored pointers types
  8363. * are the same as well.
  8364. * Ex: explored safe path could have stored
  8365. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
  8366. * but current path has stored:
  8367. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
  8368. * such verifier states are not equivalent.
  8369. * return false to continue verification of this path
  8370. */
  8371. return false;
  8372. }
  8373. return true;
  8374. }
  8375. static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
  8376. {
  8377. if (old->acquired_refs != cur->acquired_refs)
  8378. return false;
  8379. return !memcmp(old->refs, cur->refs,
  8380. sizeof(*old->refs) * old->acquired_refs);
  8381. }
  8382. /* compare two verifier states
  8383. *
  8384. * all states stored in state_list are known to be valid, since
  8385. * verifier reached 'bpf_exit' instruction through them
  8386. *
  8387. * this function is called when verifier exploring different branches of
  8388. * execution popped from the state stack. If it sees an old state that has
  8389. * more strict register state and more strict stack state then this execution
  8390. * branch doesn't need to be explored further, since verifier already
  8391. * concluded that more strict state leads to valid finish.
  8392. *
  8393. * Therefore two states are equivalent if register state is more conservative
  8394. * and explored stack state is more conservative than the current one.
  8395. * Example:
  8396. * explored current
  8397. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  8398. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  8399. *
  8400. * In other words if current stack state (one being explored) has more
  8401. * valid slots than old one that already passed validation, it means
  8402. * the verifier can stop exploring and conclude that current state is valid too
  8403. *
  8404. * Similarly with registers. If explored state has register type as invalid
  8405. * whereas register type in current state is meaningful, it means that
  8406. * the current state will reach 'bpf_exit' instruction safely
  8407. */
  8408. static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
  8409. struct bpf_func_state *cur)
  8410. {
  8411. int i;
  8412. memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
  8413. for (i = 0; i < MAX_BPF_REG; i++)
  8414. if (!regsafe(env, &old->regs[i], &cur->regs[i],
  8415. env->idmap_scratch))
  8416. return false;
  8417. if (!stacksafe(env, old, cur, env->idmap_scratch))
  8418. return false;
  8419. if (!refsafe(old, cur))
  8420. return false;
  8421. return true;
  8422. }
  8423. static bool states_equal(struct bpf_verifier_env *env,
  8424. struct bpf_verifier_state *old,
  8425. struct bpf_verifier_state *cur)
  8426. {
  8427. int i;
  8428. if (old->curframe != cur->curframe)
  8429. return false;
  8430. /* Verification state from speculative execution simulation
  8431. * must never prune a non-speculative execution one.
  8432. */
  8433. if (old->speculative && !cur->speculative)
  8434. return false;
  8435. if (old->active_spin_lock != cur->active_spin_lock)
  8436. return false;
  8437. /* for states to be equal callsites have to be the same
  8438. * and all frame states need to be equivalent
  8439. */
  8440. for (i = 0; i <= old->curframe; i++) {
  8441. if (old->frame[i]->callsite != cur->frame[i]->callsite)
  8442. return false;
  8443. if (!func_states_equal(env, old->frame[i], cur->frame[i]))
  8444. return false;
  8445. }
  8446. return true;
  8447. }
  8448. /* Return 0 if no propagation happened. Return negative error code if error
  8449. * happened. Otherwise, return the propagated bit.
  8450. */
  8451. static int propagate_liveness_reg(struct bpf_verifier_env *env,
  8452. struct bpf_reg_state *reg,
  8453. struct bpf_reg_state *parent_reg)
  8454. {
  8455. u8 parent_flag = parent_reg->live & REG_LIVE_READ;
  8456. u8 flag = reg->live & REG_LIVE_READ;
  8457. int err;
  8458. /* When comes here, read flags of PARENT_REG or REG could be any of
  8459. * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
  8460. * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
  8461. */
  8462. if (parent_flag == REG_LIVE_READ64 ||
  8463. /* Or if there is no read flag from REG. */
  8464. !flag ||
  8465. /* Or if the read flag from REG is the same as PARENT_REG. */
  8466. parent_flag == flag)
  8467. return 0;
  8468. err = mark_reg_read(env, reg, parent_reg, flag);
  8469. if (err)
  8470. return err;
  8471. return flag;
  8472. }
  8473. /* A write screens off any subsequent reads; but write marks come from the
  8474. * straight-line code between a state and its parent. When we arrive at an
  8475. * equivalent state (jump target or such) we didn't arrive by the straight-line
  8476. * code, so read marks in the state must propagate to the parent regardless
  8477. * of the state's write marks. That's what 'parent == state->parent' comparison
  8478. * in mark_reg_read() is for.
  8479. */
  8480. static int propagate_liveness(struct bpf_verifier_env *env,
  8481. const struct bpf_verifier_state *vstate,
  8482. struct bpf_verifier_state *vparent)
  8483. {
  8484. struct bpf_reg_state *state_reg, *parent_reg;
  8485. struct bpf_func_state *state, *parent;
  8486. int i, frame, err = 0;
  8487. if (vparent->curframe != vstate->curframe) {
  8488. WARN(1, "propagate_live: parent frame %d current frame %d\n",
  8489. vparent->curframe, vstate->curframe);
  8490. return -EFAULT;
  8491. }
  8492. /* Propagate read liveness of registers... */
  8493. BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
  8494. for (frame = 0; frame <= vstate->curframe; frame++) {
  8495. parent = vparent->frame[frame];
  8496. state = vstate->frame[frame];
  8497. parent_reg = parent->regs;
  8498. state_reg = state->regs;
  8499. /* We don't need to worry about FP liveness, it's read-only */
  8500. for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
  8501. err = propagate_liveness_reg(env, &state_reg[i],
  8502. &parent_reg[i]);
  8503. if (err < 0)
  8504. return err;
  8505. if (err == REG_LIVE_READ64)
  8506. mark_insn_zext(env, &parent_reg[i]);
  8507. }
  8508. /* Propagate stack slots. */
  8509. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
  8510. i < parent->allocated_stack / BPF_REG_SIZE; i++) {
  8511. parent_reg = &parent->stack[i].spilled_ptr;
  8512. state_reg = &state->stack[i].spilled_ptr;
  8513. err = propagate_liveness_reg(env, state_reg,
  8514. parent_reg);
  8515. if (err < 0)
  8516. return err;
  8517. }
  8518. }
  8519. return 0;
  8520. }
  8521. /* find precise scalars in the previous equivalent state and
  8522. * propagate them into the current state
  8523. */
  8524. static int propagate_precision(struct bpf_verifier_env *env,
  8525. const struct bpf_verifier_state *old)
  8526. {
  8527. struct bpf_reg_state *state_reg;
  8528. struct bpf_func_state *state;
  8529. int i, err = 0;
  8530. state = old->frame[old->curframe];
  8531. state_reg = state->regs;
  8532. for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
  8533. if (state_reg->type != SCALAR_VALUE ||
  8534. !state_reg->precise)
  8535. continue;
  8536. if (env->log.level & BPF_LOG_LEVEL2)
  8537. verbose(env, "propagating r%d\n", i);
  8538. err = mark_chain_precision(env, i);
  8539. if (err < 0)
  8540. return err;
  8541. }
  8542. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  8543. if (state->stack[i].slot_type[0] != STACK_SPILL)
  8544. continue;
  8545. state_reg = &state->stack[i].spilled_ptr;
  8546. if (state_reg->type != SCALAR_VALUE ||
  8547. !state_reg->precise)
  8548. continue;
  8549. if (env->log.level & BPF_LOG_LEVEL2)
  8550. verbose(env, "propagating fp%d\n",
  8551. (-i - 1) * BPF_REG_SIZE);
  8552. err = mark_chain_precision_stack(env, i);
  8553. if (err < 0)
  8554. return err;
  8555. }
  8556. return 0;
  8557. }
  8558. static bool states_maybe_looping(struct bpf_verifier_state *old,
  8559. struct bpf_verifier_state *cur)
  8560. {
  8561. struct bpf_func_state *fold, *fcur;
  8562. int i, fr = cur->curframe;
  8563. if (old->curframe != fr)
  8564. return false;
  8565. fold = old->frame[fr];
  8566. fcur = cur->frame[fr];
  8567. for (i = 0; i < MAX_BPF_REG; i++)
  8568. if (memcmp(&fold->regs[i], &fcur->regs[i],
  8569. offsetof(struct bpf_reg_state, parent)))
  8570. return false;
  8571. return true;
  8572. }
  8573. static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
  8574. {
  8575. struct bpf_verifier_state_list *new_sl;
  8576. struct bpf_verifier_state_list *sl, **pprev;
  8577. struct bpf_verifier_state *cur = env->cur_state, *new;
  8578. int i, j, err, states_cnt = 0;
  8579. bool add_new_state = env->test_state_freq ? true : false;
  8580. cur->last_insn_idx = env->prev_insn_idx;
  8581. if (!env->insn_aux_data[insn_idx].prune_point)
  8582. /* this 'insn_idx' instruction wasn't marked, so we will not
  8583. * be doing state search here
  8584. */
  8585. return 0;
  8586. /* bpf progs typically have pruning point every 4 instructions
  8587. * http://vger.kernel.org/bpfconf2019.html#session-1
  8588. * Do not add new state for future pruning if the verifier hasn't seen
  8589. * at least 2 jumps and at least 8 instructions.
  8590. * This heuristics helps decrease 'total_states' and 'peak_states' metric.
  8591. * In tests that amounts to up to 50% reduction into total verifier
  8592. * memory consumption and 20% verifier time speedup.
  8593. */
  8594. if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
  8595. env->insn_processed - env->prev_insn_processed >= 8)
  8596. add_new_state = true;
  8597. pprev = explored_state(env, insn_idx);
  8598. sl = *pprev;
  8599. clean_live_states(env, insn_idx, cur);
  8600. while (sl) {
  8601. states_cnt++;
  8602. if (sl->state.insn_idx != insn_idx)
  8603. goto next;
  8604. if (sl->state.branches) {
  8605. if (states_maybe_looping(&sl->state, cur) &&
  8606. states_equal(env, &sl->state, cur)) {
  8607. verbose_linfo(env, insn_idx, "; ");
  8608. verbose(env, "infinite loop detected at insn %d\n", insn_idx);
  8609. return -EINVAL;
  8610. }
  8611. /* if the verifier is processing a loop, avoid adding new state
  8612. * too often, since different loop iterations have distinct
  8613. * states and may not help future pruning.
  8614. * This threshold shouldn't be too low to make sure that
  8615. * a loop with large bound will be rejected quickly.
  8616. * The most abusive loop will be:
  8617. * r1 += 1
  8618. * if r1 < 1000000 goto pc-2
  8619. * 1M insn_procssed limit / 100 == 10k peak states.
  8620. * This threshold shouldn't be too high either, since states
  8621. * at the end of the loop are likely to be useful in pruning.
  8622. */
  8623. if (env->jmps_processed - env->prev_jmps_processed < 20 &&
  8624. env->insn_processed - env->prev_insn_processed < 100)
  8625. add_new_state = false;
  8626. goto miss;
  8627. }
  8628. if (states_equal(env, &sl->state, cur)) {
  8629. sl->hit_cnt++;
  8630. /* reached equivalent register/stack state,
  8631. * prune the search.
  8632. * Registers read by the continuation are read by us.
  8633. * If we have any write marks in env->cur_state, they
  8634. * will prevent corresponding reads in the continuation
  8635. * from reaching our parent (an explored_state). Our
  8636. * own state will get the read marks recorded, but
  8637. * they'll be immediately forgotten as we're pruning
  8638. * this state and will pop a new one.
  8639. */
  8640. err = propagate_liveness(env, &sl->state, cur);
  8641. /* if previous state reached the exit with precision and
  8642. * current state is equivalent to it (except precsion marks)
  8643. * the precision needs to be propagated back in
  8644. * the current state.
  8645. */
  8646. err = err ? : push_jmp_history(env, cur);
  8647. err = err ? : propagate_precision(env, &sl->state);
  8648. if (err)
  8649. return err;
  8650. return 1;
  8651. }
  8652. miss:
  8653. /* when new state is not going to be added do not increase miss count.
  8654. * Otherwise several loop iterations will remove the state
  8655. * recorded earlier. The goal of these heuristics is to have
  8656. * states from some iterations of the loop (some in the beginning
  8657. * and some at the end) to help pruning.
  8658. */
  8659. if (add_new_state)
  8660. sl->miss_cnt++;
  8661. /* heuristic to determine whether this state is beneficial
  8662. * to keep checking from state equivalence point of view.
  8663. * Higher numbers increase max_states_per_insn and verification time,
  8664. * but do not meaningfully decrease insn_processed.
  8665. */
  8666. if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
  8667. /* the state is unlikely to be useful. Remove it to
  8668. * speed up verification
  8669. */
  8670. *pprev = sl->next;
  8671. if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
  8672. u32 br = sl->state.branches;
  8673. WARN_ONCE(br,
  8674. "BUG live_done but branches_to_explore %d\n",
  8675. br);
  8676. free_verifier_state(&sl->state, false);
  8677. kfree(sl);
  8678. env->peak_states--;
  8679. } else {
  8680. /* cannot free this state, since parentage chain may
  8681. * walk it later. Add it for free_list instead to
  8682. * be freed at the end of verification
  8683. */
  8684. sl->next = env->free_list;
  8685. env->free_list = sl;
  8686. }
  8687. sl = *pprev;
  8688. continue;
  8689. }
  8690. next:
  8691. pprev = &sl->next;
  8692. sl = *pprev;
  8693. }
  8694. if (env->max_states_per_insn < states_cnt)
  8695. env->max_states_per_insn = states_cnt;
  8696. if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
  8697. return push_jmp_history(env, cur);
  8698. if (!add_new_state)
  8699. return push_jmp_history(env, cur);
  8700. /* There were no equivalent states, remember the current one.
  8701. * Technically the current state is not proven to be safe yet,
  8702. * but it will either reach outer most bpf_exit (which means it's safe)
  8703. * or it will be rejected. When there are no loops the verifier won't be
  8704. * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
  8705. * again on the way to bpf_exit.
  8706. * When looping the sl->state.branches will be > 0 and this state
  8707. * will not be considered for equivalence until branches == 0.
  8708. */
  8709. new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
  8710. if (!new_sl)
  8711. return -ENOMEM;
  8712. env->total_states++;
  8713. env->peak_states++;
  8714. env->prev_jmps_processed = env->jmps_processed;
  8715. env->prev_insn_processed = env->insn_processed;
  8716. /* add new state to the head of linked list */
  8717. new = &new_sl->state;
  8718. err = copy_verifier_state(new, cur);
  8719. if (err) {
  8720. free_verifier_state(new, false);
  8721. kfree(new_sl);
  8722. return err;
  8723. }
  8724. new->insn_idx = insn_idx;
  8725. WARN_ONCE(new->branches != 1,
  8726. "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
  8727. cur->parent = new;
  8728. cur->first_insn_idx = insn_idx;
  8729. clear_jmp_history(cur);
  8730. new_sl->next = *explored_state(env, insn_idx);
  8731. *explored_state(env, insn_idx) = new_sl;
  8732. /* connect new state to parentage chain. Current frame needs all
  8733. * registers connected. Only r6 - r9 of the callers are alive (pushed
  8734. * to the stack implicitly by JITs) so in callers' frames connect just
  8735. * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
  8736. * the state of the call instruction (with WRITTEN set), and r0 comes
  8737. * from callee with its full parentage chain, anyway.
  8738. */
  8739. /* clear write marks in current state: the writes we did are not writes
  8740. * our child did, so they don't screen off its reads from us.
  8741. * (There are no read marks in current state, because reads always mark
  8742. * their parent and current state never has children yet. Only
  8743. * explored_states can get read marks.)
  8744. */
  8745. for (j = 0; j <= cur->curframe; j++) {
  8746. for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
  8747. cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
  8748. for (i = 0; i < BPF_REG_FP; i++)
  8749. cur->frame[j]->regs[i].live = REG_LIVE_NONE;
  8750. }
  8751. /* all stack frames are accessible from callee, clear them all */
  8752. for (j = 0; j <= cur->curframe; j++) {
  8753. struct bpf_func_state *frame = cur->frame[j];
  8754. struct bpf_func_state *newframe = new->frame[j];
  8755. for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
  8756. frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
  8757. frame->stack[i].spilled_ptr.parent =
  8758. &newframe->stack[i].spilled_ptr;
  8759. }
  8760. }
  8761. return 0;
  8762. }
  8763. /* Return true if it's OK to have the same insn return a different type. */
  8764. static bool reg_type_mismatch_ok(enum bpf_reg_type type)
  8765. {
  8766. switch (type) {
  8767. case PTR_TO_CTX:
  8768. case PTR_TO_SOCKET:
  8769. case PTR_TO_SOCKET_OR_NULL:
  8770. case PTR_TO_SOCK_COMMON:
  8771. case PTR_TO_SOCK_COMMON_OR_NULL:
  8772. case PTR_TO_TCP_SOCK:
  8773. case PTR_TO_TCP_SOCK_OR_NULL:
  8774. case PTR_TO_XDP_SOCK:
  8775. case PTR_TO_BTF_ID:
  8776. case PTR_TO_BTF_ID_OR_NULL:
  8777. return false;
  8778. default:
  8779. return true;
  8780. }
  8781. }
  8782. /* If an instruction was previously used with particular pointer types, then we
  8783. * need to be careful to avoid cases such as the below, where it may be ok
  8784. * for one branch accessing the pointer, but not ok for the other branch:
  8785. *
  8786. * R1 = sock_ptr
  8787. * goto X;
  8788. * ...
  8789. * R1 = some_other_valid_ptr;
  8790. * goto X;
  8791. * ...
  8792. * R2 = *(u32 *)(R1 + 0);
  8793. */
  8794. static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
  8795. {
  8796. return src != prev && (!reg_type_mismatch_ok(src) ||
  8797. !reg_type_mismatch_ok(prev));
  8798. }
  8799. static int do_check(struct bpf_verifier_env *env)
  8800. {
  8801. bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
  8802. struct bpf_verifier_state *state = env->cur_state;
  8803. struct bpf_insn *insns = env->prog->insnsi;
  8804. struct bpf_reg_state *regs;
  8805. int insn_cnt = env->prog->len;
  8806. bool do_print_state = false;
  8807. int prev_insn_idx = -1;
  8808. for (;;) {
  8809. struct bpf_insn *insn;
  8810. u8 class;
  8811. int err;
  8812. env->prev_insn_idx = prev_insn_idx;
  8813. if (env->insn_idx >= insn_cnt) {
  8814. verbose(env, "invalid insn idx %d insn_cnt %d\n",
  8815. env->insn_idx, insn_cnt);
  8816. return -EFAULT;
  8817. }
  8818. insn = &insns[env->insn_idx];
  8819. class = BPF_CLASS(insn->code);
  8820. if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
  8821. verbose(env,
  8822. "BPF program is too large. Processed %d insn\n",
  8823. env->insn_processed);
  8824. return -E2BIG;
  8825. }
  8826. err = is_state_visited(env, env->insn_idx);
  8827. if (err < 0)
  8828. return err;
  8829. if (err == 1) {
  8830. /* found equivalent state, can prune the search */
  8831. if (env->log.level & BPF_LOG_LEVEL) {
  8832. if (do_print_state)
  8833. verbose(env, "\nfrom %d to %d%s: safe\n",
  8834. env->prev_insn_idx, env->insn_idx,
  8835. env->cur_state->speculative ?
  8836. " (speculative execution)" : "");
  8837. else
  8838. verbose(env, "%d: safe\n", env->insn_idx);
  8839. }
  8840. goto process_bpf_exit;
  8841. }
  8842. if (signal_pending(current))
  8843. return -EAGAIN;
  8844. if (need_resched())
  8845. cond_resched();
  8846. if (env->log.level & BPF_LOG_LEVEL2 ||
  8847. (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
  8848. if (env->log.level & BPF_LOG_LEVEL2)
  8849. verbose(env, "%d:", env->insn_idx);
  8850. else
  8851. verbose(env, "\nfrom %d to %d%s:",
  8852. env->prev_insn_idx, env->insn_idx,
  8853. env->cur_state->speculative ?
  8854. " (speculative execution)" : "");
  8855. print_verifier_state(env, state->frame[state->curframe]);
  8856. do_print_state = false;
  8857. }
  8858. if (env->log.level & BPF_LOG_LEVEL) {
  8859. const struct bpf_insn_cbs cbs = {
  8860. .cb_print = verbose,
  8861. .private_data = env,
  8862. };
  8863. verbose_linfo(env, env->insn_idx, "; ");
  8864. verbose(env, "%d: ", env->insn_idx);
  8865. print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
  8866. }
  8867. if (bpf_prog_is_dev_bound(env->prog->aux)) {
  8868. err = bpf_prog_offload_verify_insn(env, env->insn_idx,
  8869. env->prev_insn_idx);
  8870. if (err)
  8871. return err;
  8872. }
  8873. regs = cur_regs(env);
  8874. sanitize_mark_insn_seen(env);
  8875. prev_insn_idx = env->insn_idx;
  8876. if (class == BPF_ALU || class == BPF_ALU64) {
  8877. err = check_alu_op(env, insn);
  8878. if (err)
  8879. return err;
  8880. } else if (class == BPF_LDX) {
  8881. enum bpf_reg_type *prev_src_type, src_reg_type;
  8882. /* check for reserved fields is already done */
  8883. /* check src operand */
  8884. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  8885. if (err)
  8886. return err;
  8887. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  8888. if (err)
  8889. return err;
  8890. src_reg_type = regs[insn->src_reg].type;
  8891. /* check that memory (src_reg + off) is readable,
  8892. * the state of dst_reg will be updated by this func
  8893. */
  8894. err = check_mem_access(env, env->insn_idx, insn->src_reg,
  8895. insn->off, BPF_SIZE(insn->code),
  8896. BPF_READ, insn->dst_reg, false);
  8897. if (err)
  8898. return err;
  8899. prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
  8900. if (*prev_src_type == NOT_INIT) {
  8901. /* saw a valid insn
  8902. * dst_reg = *(u32 *)(src_reg + off)
  8903. * save type to validate intersecting paths
  8904. */
  8905. *prev_src_type = src_reg_type;
  8906. } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
  8907. /* ABuser program is trying to use the same insn
  8908. * dst_reg = *(u32*) (src_reg + off)
  8909. * with different pointer types:
  8910. * src_reg == ctx in one branch and
  8911. * src_reg == stack|map in some other branch.
  8912. * Reject it.
  8913. */
  8914. verbose(env, "same insn cannot be used with different pointers\n");
  8915. return -EINVAL;
  8916. }
  8917. } else if (class == BPF_STX) {
  8918. enum bpf_reg_type *prev_dst_type, dst_reg_type;
  8919. if (BPF_MODE(insn->code) == BPF_XADD) {
  8920. err = check_xadd(env, env->insn_idx, insn);
  8921. if (err)
  8922. return err;
  8923. env->insn_idx++;
  8924. continue;
  8925. }
  8926. /* check src1 operand */
  8927. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  8928. if (err)
  8929. return err;
  8930. /* check src2 operand */
  8931. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  8932. if (err)
  8933. return err;
  8934. dst_reg_type = regs[insn->dst_reg].type;
  8935. /* check that memory (dst_reg + off) is writeable */
  8936. err = check_mem_access(env, env->insn_idx, insn->dst_reg,
  8937. insn->off, BPF_SIZE(insn->code),
  8938. BPF_WRITE, insn->src_reg, false);
  8939. if (err)
  8940. return err;
  8941. prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
  8942. if (*prev_dst_type == NOT_INIT) {
  8943. *prev_dst_type = dst_reg_type;
  8944. } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
  8945. verbose(env, "same insn cannot be used with different pointers\n");
  8946. return -EINVAL;
  8947. }
  8948. } else if (class == BPF_ST) {
  8949. if (BPF_MODE(insn->code) != BPF_MEM ||
  8950. insn->src_reg != BPF_REG_0) {
  8951. verbose(env, "BPF_ST uses reserved fields\n");
  8952. return -EINVAL;
  8953. }
  8954. /* check src operand */
  8955. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  8956. if (err)
  8957. return err;
  8958. if (is_ctx_reg(env, insn->dst_reg)) {
  8959. verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
  8960. insn->dst_reg,
  8961. reg_type_str[reg_state(env, insn->dst_reg)->type]);
  8962. return -EACCES;
  8963. }
  8964. /* check that memory (dst_reg + off) is writeable */
  8965. err = check_mem_access(env, env->insn_idx, insn->dst_reg,
  8966. insn->off, BPF_SIZE(insn->code),
  8967. BPF_WRITE, -1, false);
  8968. if (err)
  8969. return err;
  8970. } else if (class == BPF_JMP || class == BPF_JMP32) {
  8971. u8 opcode = BPF_OP(insn->code);
  8972. env->jmps_processed++;
  8973. if (opcode == BPF_CALL) {
  8974. if (BPF_SRC(insn->code) != BPF_K ||
  8975. insn->off != 0 ||
  8976. (insn->src_reg != BPF_REG_0 &&
  8977. insn->src_reg != BPF_PSEUDO_CALL) ||
  8978. insn->dst_reg != BPF_REG_0 ||
  8979. class == BPF_JMP32) {
  8980. verbose(env, "BPF_CALL uses reserved fields\n");
  8981. return -EINVAL;
  8982. }
  8983. if (env->cur_state->active_spin_lock &&
  8984. (insn->src_reg == BPF_PSEUDO_CALL ||
  8985. insn->imm != BPF_FUNC_spin_unlock)) {
  8986. verbose(env, "function calls are not allowed while holding a lock\n");
  8987. return -EINVAL;
  8988. }
  8989. if (insn->src_reg == BPF_PSEUDO_CALL)
  8990. err = check_func_call(env, insn, &env->insn_idx);
  8991. else
  8992. err = check_helper_call(env, insn->imm, env->insn_idx);
  8993. if (err)
  8994. return err;
  8995. } else if (opcode == BPF_JA) {
  8996. if (BPF_SRC(insn->code) != BPF_K ||
  8997. insn->imm != 0 ||
  8998. insn->src_reg != BPF_REG_0 ||
  8999. insn->dst_reg != BPF_REG_0 ||
  9000. class == BPF_JMP32) {
  9001. verbose(env, "BPF_JA uses reserved fields\n");
  9002. return -EINVAL;
  9003. }
  9004. env->insn_idx += insn->off + 1;
  9005. continue;
  9006. } else if (opcode == BPF_EXIT) {
  9007. if (BPF_SRC(insn->code) != BPF_K ||
  9008. insn->imm != 0 ||
  9009. insn->src_reg != BPF_REG_0 ||
  9010. insn->dst_reg != BPF_REG_0 ||
  9011. class == BPF_JMP32) {
  9012. verbose(env, "BPF_EXIT uses reserved fields\n");
  9013. return -EINVAL;
  9014. }
  9015. if (env->cur_state->active_spin_lock) {
  9016. verbose(env, "bpf_spin_unlock is missing\n");
  9017. return -EINVAL;
  9018. }
  9019. if (state->curframe) {
  9020. /* exit from nested function */
  9021. err = prepare_func_exit(env, &env->insn_idx);
  9022. if (err)
  9023. return err;
  9024. do_print_state = true;
  9025. continue;
  9026. }
  9027. err = check_reference_leak(env);
  9028. if (err)
  9029. return err;
  9030. err = check_return_code(env);
  9031. if (err)
  9032. return err;
  9033. process_bpf_exit:
  9034. update_branch_counts(env, env->cur_state);
  9035. err = pop_stack(env, &prev_insn_idx,
  9036. &env->insn_idx, pop_log);
  9037. if (err < 0) {
  9038. if (err != -ENOENT)
  9039. return err;
  9040. break;
  9041. } else {
  9042. do_print_state = true;
  9043. continue;
  9044. }
  9045. } else {
  9046. err = check_cond_jmp_op(env, insn, &env->insn_idx);
  9047. if (err)
  9048. return err;
  9049. }
  9050. } else if (class == BPF_LD) {
  9051. u8 mode = BPF_MODE(insn->code);
  9052. if (mode == BPF_ABS || mode == BPF_IND) {
  9053. err = check_ld_abs(env, insn);
  9054. if (err)
  9055. return err;
  9056. } else if (mode == BPF_IMM) {
  9057. err = check_ld_imm(env, insn);
  9058. if (err)
  9059. return err;
  9060. env->insn_idx++;
  9061. sanitize_mark_insn_seen(env);
  9062. } else {
  9063. verbose(env, "invalid BPF_LD mode\n");
  9064. return -EINVAL;
  9065. }
  9066. } else {
  9067. verbose(env, "unknown insn class %d\n", class);
  9068. return -EINVAL;
  9069. }
  9070. env->insn_idx++;
  9071. }
  9072. return 0;
  9073. }
  9074. /* replace pseudo btf_id with kernel symbol address */
  9075. static int check_pseudo_btf_id(struct bpf_verifier_env *env,
  9076. struct bpf_insn *insn,
  9077. struct bpf_insn_aux_data *aux)
  9078. {
  9079. const struct btf_var_secinfo *vsi;
  9080. const struct btf_type *datasec;
  9081. const struct btf_type *t;
  9082. const char *sym_name;
  9083. bool percpu = false;
  9084. u32 type, id = insn->imm;
  9085. s32 datasec_id;
  9086. u64 addr;
  9087. int i;
  9088. if (!btf_vmlinux) {
  9089. verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
  9090. return -EINVAL;
  9091. }
  9092. if (insn[1].imm != 0) {
  9093. verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
  9094. return -EINVAL;
  9095. }
  9096. t = btf_type_by_id(btf_vmlinux, id);
  9097. if (!t) {
  9098. verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
  9099. return -ENOENT;
  9100. }
  9101. if (!btf_type_is_var(t)) {
  9102. verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
  9103. id);
  9104. return -EINVAL;
  9105. }
  9106. sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
  9107. addr = kallsyms_lookup_name(sym_name);
  9108. if (!addr) {
  9109. verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
  9110. sym_name);
  9111. return -ENOENT;
  9112. }
  9113. datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
  9114. BTF_KIND_DATASEC);
  9115. if (datasec_id > 0) {
  9116. datasec = btf_type_by_id(btf_vmlinux, datasec_id);
  9117. for_each_vsi(i, datasec, vsi) {
  9118. if (vsi->type == id) {
  9119. percpu = true;
  9120. break;
  9121. }
  9122. }
  9123. }
  9124. insn[0].imm = (u32)addr;
  9125. insn[1].imm = addr >> 32;
  9126. type = t->type;
  9127. t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
  9128. if (percpu) {
  9129. aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
  9130. aux->btf_var.btf_id = type;
  9131. } else if (!btf_type_is_struct(t)) {
  9132. const struct btf_type *ret;
  9133. const char *tname;
  9134. u32 tsize;
  9135. /* resolve the type size of ksym. */
  9136. ret = btf_resolve_size(btf_vmlinux, t, &tsize);
  9137. if (IS_ERR(ret)) {
  9138. tname = btf_name_by_offset(btf_vmlinux, t->name_off);
  9139. verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
  9140. tname, PTR_ERR(ret));
  9141. return -EINVAL;
  9142. }
  9143. aux->btf_var.reg_type = PTR_TO_MEM;
  9144. aux->btf_var.mem_size = tsize;
  9145. } else {
  9146. aux->btf_var.reg_type = PTR_TO_BTF_ID;
  9147. aux->btf_var.btf_id = type;
  9148. }
  9149. return 0;
  9150. }
  9151. static int check_map_prealloc(struct bpf_map *map)
  9152. {
  9153. return (map->map_type != BPF_MAP_TYPE_HASH &&
  9154. map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
  9155. map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
  9156. !(map->map_flags & BPF_F_NO_PREALLOC);
  9157. }
  9158. static bool is_tracing_prog_type(enum bpf_prog_type type)
  9159. {
  9160. switch (type) {
  9161. case BPF_PROG_TYPE_KPROBE:
  9162. case BPF_PROG_TYPE_TRACEPOINT:
  9163. case BPF_PROG_TYPE_PERF_EVENT:
  9164. case BPF_PROG_TYPE_RAW_TRACEPOINT:
  9165. return true;
  9166. default:
  9167. return false;
  9168. }
  9169. }
  9170. static bool is_preallocated_map(struct bpf_map *map)
  9171. {
  9172. if (!check_map_prealloc(map))
  9173. return false;
  9174. if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
  9175. return false;
  9176. return true;
  9177. }
  9178. static int check_map_prog_compatibility(struct bpf_verifier_env *env,
  9179. struct bpf_map *map,
  9180. struct bpf_prog *prog)
  9181. {
  9182. enum bpf_prog_type prog_type = resolve_prog_type(prog);
  9183. /*
  9184. * Validate that trace type programs use preallocated hash maps.
  9185. *
  9186. * For programs attached to PERF events this is mandatory as the
  9187. * perf NMI can hit any arbitrary code sequence.
  9188. *
  9189. * All other trace types using preallocated hash maps are unsafe as
  9190. * well because tracepoint or kprobes can be inside locked regions
  9191. * of the memory allocator or at a place where a recursion into the
  9192. * memory allocator would see inconsistent state.
  9193. *
  9194. * On RT enabled kernels run-time allocation of all trace type
  9195. * programs is strictly prohibited due to lock type constraints. On
  9196. * !RT kernels it is allowed for backwards compatibility reasons for
  9197. * now, but warnings are emitted so developers are made aware of
  9198. * the unsafety and can fix their programs before this is enforced.
  9199. */
  9200. if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
  9201. if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
  9202. verbose(env, "perf_event programs can only use preallocated hash map\n");
  9203. return -EINVAL;
  9204. }
  9205. if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
  9206. verbose(env, "trace type programs can only use preallocated hash map\n");
  9207. return -EINVAL;
  9208. }
  9209. WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
  9210. verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
  9211. }
  9212. if ((is_tracing_prog_type(prog_type) ||
  9213. prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
  9214. map_value_has_spin_lock(map)) {
  9215. verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
  9216. return -EINVAL;
  9217. }
  9218. if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
  9219. !bpf_offload_prog_map_match(prog, map)) {
  9220. verbose(env, "offload device mismatch between prog and map\n");
  9221. return -EINVAL;
  9222. }
  9223. if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
  9224. verbose(env, "bpf_struct_ops map cannot be used in prog\n");
  9225. return -EINVAL;
  9226. }
  9227. if (prog->aux->sleepable)
  9228. switch (map->map_type) {
  9229. case BPF_MAP_TYPE_HASH:
  9230. case BPF_MAP_TYPE_LRU_HASH:
  9231. case BPF_MAP_TYPE_ARRAY:
  9232. if (!is_preallocated_map(map)) {
  9233. verbose(env,
  9234. "Sleepable programs can only use preallocated hash maps\n");
  9235. return -EINVAL;
  9236. }
  9237. break;
  9238. default:
  9239. verbose(env,
  9240. "Sleepable programs can only use array and hash maps\n");
  9241. return -EINVAL;
  9242. }
  9243. return 0;
  9244. }
  9245. static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
  9246. {
  9247. return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
  9248. map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
  9249. }
  9250. /* find and rewrite pseudo imm in ld_imm64 instructions:
  9251. *
  9252. * 1. if it accesses map FD, replace it with actual map pointer.
  9253. * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
  9254. *
  9255. * NOTE: btf_vmlinux is required for converting pseudo btf_id.
  9256. */
  9257. static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
  9258. {
  9259. struct bpf_insn *insn = env->prog->insnsi;
  9260. int insn_cnt = env->prog->len;
  9261. int i, j, err;
  9262. err = bpf_prog_calc_tag(env->prog);
  9263. if (err)
  9264. return err;
  9265. for (i = 0; i < insn_cnt; i++, insn++) {
  9266. if (BPF_CLASS(insn->code) == BPF_LDX &&
  9267. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  9268. verbose(env, "BPF_LDX uses reserved fields\n");
  9269. return -EINVAL;
  9270. }
  9271. if (BPF_CLASS(insn->code) == BPF_STX &&
  9272. ((BPF_MODE(insn->code) != BPF_MEM &&
  9273. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  9274. verbose(env, "BPF_STX uses reserved fields\n");
  9275. return -EINVAL;
  9276. }
  9277. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  9278. struct bpf_insn_aux_data *aux;
  9279. struct bpf_map *map;
  9280. struct fd f;
  9281. u64 addr;
  9282. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  9283. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  9284. insn[1].off != 0) {
  9285. verbose(env, "invalid bpf_ld_imm64 insn\n");
  9286. return -EINVAL;
  9287. }
  9288. if (insn[0].src_reg == 0)
  9289. /* valid generic load 64-bit imm */
  9290. goto next_insn;
  9291. if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
  9292. aux = &env->insn_aux_data[i];
  9293. err = check_pseudo_btf_id(env, insn, aux);
  9294. if (err)
  9295. return err;
  9296. goto next_insn;
  9297. }
  9298. /* In final convert_pseudo_ld_imm64() step, this is
  9299. * converted into regular 64-bit imm load insn.
  9300. */
  9301. if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
  9302. insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
  9303. (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
  9304. insn[1].imm != 0)) {
  9305. verbose(env,
  9306. "unrecognized bpf_ld_imm64 insn\n");
  9307. return -EINVAL;
  9308. }
  9309. f = fdget(insn[0].imm);
  9310. map = __bpf_map_get(f);
  9311. if (IS_ERR(map)) {
  9312. verbose(env, "fd %d is not pointing to valid bpf_map\n",
  9313. insn[0].imm);
  9314. return PTR_ERR(map);
  9315. }
  9316. err = check_map_prog_compatibility(env, map, env->prog);
  9317. if (err) {
  9318. fdput(f);
  9319. return err;
  9320. }
  9321. aux = &env->insn_aux_data[i];
  9322. if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
  9323. addr = (unsigned long)map;
  9324. } else {
  9325. u32 off = insn[1].imm;
  9326. if (off >= BPF_MAX_VAR_OFF) {
  9327. verbose(env, "direct value offset of %u is not allowed\n", off);
  9328. fdput(f);
  9329. return -EINVAL;
  9330. }
  9331. if (!map->ops->map_direct_value_addr) {
  9332. verbose(env, "no direct value access support for this map type\n");
  9333. fdput(f);
  9334. return -EINVAL;
  9335. }
  9336. err = map->ops->map_direct_value_addr(map, &addr, off);
  9337. if (err) {
  9338. verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
  9339. map->value_size, off);
  9340. fdput(f);
  9341. return err;
  9342. }
  9343. aux->map_off = off;
  9344. addr += off;
  9345. }
  9346. insn[0].imm = (u32)addr;
  9347. insn[1].imm = addr >> 32;
  9348. /* check whether we recorded this map already */
  9349. for (j = 0; j < env->used_map_cnt; j++) {
  9350. if (env->used_maps[j] == map) {
  9351. aux->map_index = j;
  9352. fdput(f);
  9353. goto next_insn;
  9354. }
  9355. }
  9356. if (env->used_map_cnt >= MAX_USED_MAPS) {
  9357. fdput(f);
  9358. return -E2BIG;
  9359. }
  9360. /* hold the map. If the program is rejected by verifier,
  9361. * the map will be released by release_maps() or it
  9362. * will be used by the valid program until it's unloaded
  9363. * and all maps are released in free_used_maps()
  9364. */
  9365. bpf_map_inc(map);
  9366. aux->map_index = env->used_map_cnt;
  9367. env->used_maps[env->used_map_cnt++] = map;
  9368. if (bpf_map_is_cgroup_storage(map) &&
  9369. bpf_cgroup_storage_assign(env->prog->aux, map)) {
  9370. verbose(env, "only one cgroup storage of each type is allowed\n");
  9371. fdput(f);
  9372. return -EBUSY;
  9373. }
  9374. fdput(f);
  9375. next_insn:
  9376. insn++;
  9377. i++;
  9378. continue;
  9379. }
  9380. /* Basic sanity check before we invest more work here. */
  9381. if (!bpf_opcode_in_insntable(insn->code)) {
  9382. verbose(env, "unknown opcode %02x\n", insn->code);
  9383. return -EINVAL;
  9384. }
  9385. }
  9386. /* now all pseudo BPF_LD_IMM64 instructions load valid
  9387. * 'struct bpf_map *' into a register instead of user map_fd.
  9388. * These pointers will be used later by verifier to validate map access.
  9389. */
  9390. return 0;
  9391. }
  9392. /* drop refcnt of maps used by the rejected program */
  9393. static void release_maps(struct bpf_verifier_env *env)
  9394. {
  9395. __bpf_free_used_maps(env->prog->aux, env->used_maps,
  9396. env->used_map_cnt);
  9397. }
  9398. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  9399. static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
  9400. {
  9401. struct bpf_insn *insn = env->prog->insnsi;
  9402. int insn_cnt = env->prog->len;
  9403. int i;
  9404. for (i = 0; i < insn_cnt; i++, insn++)
  9405. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  9406. insn->src_reg = 0;
  9407. }
  9408. /* single env->prog->insni[off] instruction was replaced with the range
  9409. * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
  9410. * [0, off) and [off, end) to new locations, so the patched range stays zero
  9411. */
  9412. static void adjust_insn_aux_data(struct bpf_verifier_env *env,
  9413. struct bpf_insn_aux_data *new_data,
  9414. struct bpf_prog *new_prog, u32 off, u32 cnt)
  9415. {
  9416. struct bpf_insn_aux_data *old_data = env->insn_aux_data;
  9417. struct bpf_insn *insn = new_prog->insnsi;
  9418. u32 old_seen = old_data[off].seen;
  9419. u32 prog_len;
  9420. int i;
  9421. /* aux info at OFF always needs adjustment, no matter fast path
  9422. * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
  9423. * original insn at old prog.
  9424. */
  9425. old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
  9426. if (cnt == 1)
  9427. return;
  9428. prog_len = new_prog->len;
  9429. memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
  9430. memcpy(new_data + off + cnt - 1, old_data + off,
  9431. sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
  9432. for (i = off; i < off + cnt - 1; i++) {
  9433. /* Expand insni[off]'s seen count to the patched range. */
  9434. new_data[i].seen = old_seen;
  9435. new_data[i].zext_dst = insn_has_def32(env, insn + i);
  9436. }
  9437. env->insn_aux_data = new_data;
  9438. vfree(old_data);
  9439. }
  9440. static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
  9441. {
  9442. int i;
  9443. if (len == 1)
  9444. return;
  9445. /* NOTE: fake 'exit' subprog should be updated as well. */
  9446. for (i = 0; i <= env->subprog_cnt; i++) {
  9447. if (env->subprog_info[i].start <= off)
  9448. continue;
  9449. env->subprog_info[i].start += len - 1;
  9450. }
  9451. }
  9452. static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
  9453. {
  9454. struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
  9455. int i, sz = prog->aux->size_poke_tab;
  9456. struct bpf_jit_poke_descriptor *desc;
  9457. for (i = 0; i < sz; i++) {
  9458. desc = &tab[i];
  9459. if (desc->insn_idx <= off)
  9460. continue;
  9461. desc->insn_idx += len - 1;
  9462. }
  9463. }
  9464. static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
  9465. const struct bpf_insn *patch, u32 len)
  9466. {
  9467. struct bpf_prog *new_prog;
  9468. struct bpf_insn_aux_data *new_data = NULL;
  9469. if (len > 1) {
  9470. new_data = vzalloc(array_size(env->prog->len + len - 1,
  9471. sizeof(struct bpf_insn_aux_data)));
  9472. if (!new_data)
  9473. return NULL;
  9474. }
  9475. new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
  9476. if (IS_ERR(new_prog)) {
  9477. if (PTR_ERR(new_prog) == -ERANGE)
  9478. verbose(env,
  9479. "insn %d cannot be patched due to 16-bit range\n",
  9480. env->insn_aux_data[off].orig_idx);
  9481. vfree(new_data);
  9482. return NULL;
  9483. }
  9484. adjust_insn_aux_data(env, new_data, new_prog, off, len);
  9485. adjust_subprog_starts(env, off, len);
  9486. adjust_poke_descs(new_prog, off, len);
  9487. return new_prog;
  9488. }
  9489. static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
  9490. u32 off, u32 cnt)
  9491. {
  9492. int i, j;
  9493. /* find first prog starting at or after off (first to remove) */
  9494. for (i = 0; i < env->subprog_cnt; i++)
  9495. if (env->subprog_info[i].start >= off)
  9496. break;
  9497. /* find first prog starting at or after off + cnt (first to stay) */
  9498. for (j = i; j < env->subprog_cnt; j++)
  9499. if (env->subprog_info[j].start >= off + cnt)
  9500. break;
  9501. /* if j doesn't start exactly at off + cnt, we are just removing
  9502. * the front of previous prog
  9503. */
  9504. if (env->subprog_info[j].start != off + cnt)
  9505. j--;
  9506. if (j > i) {
  9507. struct bpf_prog_aux *aux = env->prog->aux;
  9508. int move;
  9509. /* move fake 'exit' subprog as well */
  9510. move = env->subprog_cnt + 1 - j;
  9511. memmove(env->subprog_info + i,
  9512. env->subprog_info + j,
  9513. sizeof(*env->subprog_info) * move);
  9514. env->subprog_cnt -= j - i;
  9515. /* remove func_info */
  9516. if (aux->func_info) {
  9517. move = aux->func_info_cnt - j;
  9518. memmove(aux->func_info + i,
  9519. aux->func_info + j,
  9520. sizeof(*aux->func_info) * move);
  9521. aux->func_info_cnt -= j - i;
  9522. /* func_info->insn_off is set after all code rewrites,
  9523. * in adjust_btf_func() - no need to adjust
  9524. */
  9525. }
  9526. } else {
  9527. /* convert i from "first prog to remove" to "first to adjust" */
  9528. if (env->subprog_info[i].start == off)
  9529. i++;
  9530. }
  9531. /* update fake 'exit' subprog as well */
  9532. for (; i <= env->subprog_cnt; i++)
  9533. env->subprog_info[i].start -= cnt;
  9534. return 0;
  9535. }
  9536. static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
  9537. u32 cnt)
  9538. {
  9539. struct bpf_prog *prog = env->prog;
  9540. u32 i, l_off, l_cnt, nr_linfo;
  9541. struct bpf_line_info *linfo;
  9542. nr_linfo = prog->aux->nr_linfo;
  9543. if (!nr_linfo)
  9544. return 0;
  9545. linfo = prog->aux->linfo;
  9546. /* find first line info to remove, count lines to be removed */
  9547. for (i = 0; i < nr_linfo; i++)
  9548. if (linfo[i].insn_off >= off)
  9549. break;
  9550. l_off = i;
  9551. l_cnt = 0;
  9552. for (; i < nr_linfo; i++)
  9553. if (linfo[i].insn_off < off + cnt)
  9554. l_cnt++;
  9555. else
  9556. break;
  9557. /* First live insn doesn't match first live linfo, it needs to "inherit"
  9558. * last removed linfo. prog is already modified, so prog->len == off
  9559. * means no live instructions after (tail of the program was removed).
  9560. */
  9561. if (prog->len != off && l_cnt &&
  9562. (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
  9563. l_cnt--;
  9564. linfo[--i].insn_off = off + cnt;
  9565. }
  9566. /* remove the line info which refer to the removed instructions */
  9567. if (l_cnt) {
  9568. memmove(linfo + l_off, linfo + i,
  9569. sizeof(*linfo) * (nr_linfo - i));
  9570. prog->aux->nr_linfo -= l_cnt;
  9571. nr_linfo = prog->aux->nr_linfo;
  9572. }
  9573. /* pull all linfo[i].insn_off >= off + cnt in by cnt */
  9574. for (i = l_off; i < nr_linfo; i++)
  9575. linfo[i].insn_off -= cnt;
  9576. /* fix up all subprogs (incl. 'exit') which start >= off */
  9577. for (i = 0; i <= env->subprog_cnt; i++)
  9578. if (env->subprog_info[i].linfo_idx > l_off) {
  9579. /* program may have started in the removed region but
  9580. * may not be fully removed
  9581. */
  9582. if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
  9583. env->subprog_info[i].linfo_idx -= l_cnt;
  9584. else
  9585. env->subprog_info[i].linfo_idx = l_off;
  9586. }
  9587. return 0;
  9588. }
  9589. static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
  9590. {
  9591. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  9592. unsigned int orig_prog_len = env->prog->len;
  9593. int err;
  9594. if (bpf_prog_is_dev_bound(env->prog->aux))
  9595. bpf_prog_offload_remove_insns(env, off, cnt);
  9596. err = bpf_remove_insns(env->prog, off, cnt);
  9597. if (err)
  9598. return err;
  9599. err = adjust_subprog_starts_after_remove(env, off, cnt);
  9600. if (err)
  9601. return err;
  9602. err = bpf_adj_linfo_after_remove(env, off, cnt);
  9603. if (err)
  9604. return err;
  9605. memmove(aux_data + off, aux_data + off + cnt,
  9606. sizeof(*aux_data) * (orig_prog_len - off - cnt));
  9607. return 0;
  9608. }
  9609. /* The verifier does more data flow analysis than llvm and will not
  9610. * explore branches that are dead at run time. Malicious programs can
  9611. * have dead code too. Therefore replace all dead at-run-time code
  9612. * with 'ja -1'.
  9613. *
  9614. * Just nops are not optimal, e.g. if they would sit at the end of the
  9615. * program and through another bug we would manage to jump there, then
  9616. * we'd execute beyond program memory otherwise. Returning exception
  9617. * code also wouldn't work since we can have subprogs where the dead
  9618. * code could be located.
  9619. */
  9620. static void sanitize_dead_code(struct bpf_verifier_env *env)
  9621. {
  9622. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  9623. struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
  9624. struct bpf_insn *insn = env->prog->insnsi;
  9625. const int insn_cnt = env->prog->len;
  9626. int i;
  9627. for (i = 0; i < insn_cnt; i++) {
  9628. if (aux_data[i].seen)
  9629. continue;
  9630. memcpy(insn + i, &trap, sizeof(trap));
  9631. aux_data[i].zext_dst = false;
  9632. }
  9633. }
  9634. static bool insn_is_cond_jump(u8 code)
  9635. {
  9636. u8 op;
  9637. if (BPF_CLASS(code) == BPF_JMP32)
  9638. return true;
  9639. if (BPF_CLASS(code) != BPF_JMP)
  9640. return false;
  9641. op = BPF_OP(code);
  9642. return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
  9643. }
  9644. static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
  9645. {
  9646. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  9647. struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
  9648. struct bpf_insn *insn = env->prog->insnsi;
  9649. const int insn_cnt = env->prog->len;
  9650. int i;
  9651. for (i = 0; i < insn_cnt; i++, insn++) {
  9652. if (!insn_is_cond_jump(insn->code))
  9653. continue;
  9654. if (!aux_data[i + 1].seen)
  9655. ja.off = insn->off;
  9656. else if (!aux_data[i + 1 + insn->off].seen)
  9657. ja.off = 0;
  9658. else
  9659. continue;
  9660. if (bpf_prog_is_dev_bound(env->prog->aux))
  9661. bpf_prog_offload_replace_insn(env, i, &ja);
  9662. memcpy(insn, &ja, sizeof(ja));
  9663. }
  9664. }
  9665. static int opt_remove_dead_code(struct bpf_verifier_env *env)
  9666. {
  9667. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  9668. int insn_cnt = env->prog->len;
  9669. int i, err;
  9670. for (i = 0; i < insn_cnt; i++) {
  9671. int j;
  9672. j = 0;
  9673. while (i + j < insn_cnt && !aux_data[i + j].seen)
  9674. j++;
  9675. if (!j)
  9676. continue;
  9677. err = verifier_remove_insns(env, i, j);
  9678. if (err)
  9679. return err;
  9680. insn_cnt = env->prog->len;
  9681. }
  9682. return 0;
  9683. }
  9684. static int opt_remove_nops(struct bpf_verifier_env *env)
  9685. {
  9686. const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
  9687. struct bpf_insn *insn = env->prog->insnsi;
  9688. int insn_cnt = env->prog->len;
  9689. int i, err;
  9690. for (i = 0; i < insn_cnt; i++) {
  9691. if (memcmp(&insn[i], &ja, sizeof(ja)))
  9692. continue;
  9693. err = verifier_remove_insns(env, i, 1);
  9694. if (err)
  9695. return err;
  9696. insn_cnt--;
  9697. i--;
  9698. }
  9699. return 0;
  9700. }
  9701. static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
  9702. const union bpf_attr *attr)
  9703. {
  9704. struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
  9705. struct bpf_insn_aux_data *aux = env->insn_aux_data;
  9706. int i, patch_len, delta = 0, len = env->prog->len;
  9707. struct bpf_insn *insns = env->prog->insnsi;
  9708. struct bpf_prog *new_prog;
  9709. bool rnd_hi32;
  9710. rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
  9711. zext_patch[1] = BPF_ZEXT_REG(0);
  9712. rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
  9713. rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
  9714. rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
  9715. for (i = 0; i < len; i++) {
  9716. int adj_idx = i + delta;
  9717. struct bpf_insn insn;
  9718. insn = insns[adj_idx];
  9719. if (!aux[adj_idx].zext_dst) {
  9720. u8 code, class;
  9721. u32 imm_rnd;
  9722. if (!rnd_hi32)
  9723. continue;
  9724. code = insn.code;
  9725. class = BPF_CLASS(code);
  9726. if (insn_no_def(&insn))
  9727. continue;
  9728. /* NOTE: arg "reg" (the fourth one) is only used for
  9729. * BPF_STX which has been ruled out in above
  9730. * check, it is safe to pass NULL here.
  9731. */
  9732. if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
  9733. if (class == BPF_LD &&
  9734. BPF_MODE(code) == BPF_IMM)
  9735. i++;
  9736. continue;
  9737. }
  9738. /* ctx load could be transformed into wider load. */
  9739. if (class == BPF_LDX &&
  9740. aux[adj_idx].ptr_type == PTR_TO_CTX)
  9741. continue;
  9742. imm_rnd = get_random_int();
  9743. rnd_hi32_patch[0] = insn;
  9744. rnd_hi32_patch[1].imm = imm_rnd;
  9745. rnd_hi32_patch[3].dst_reg = insn.dst_reg;
  9746. patch = rnd_hi32_patch;
  9747. patch_len = 4;
  9748. goto apply_patch_buffer;
  9749. }
  9750. if (!bpf_jit_needs_zext())
  9751. continue;
  9752. zext_patch[0] = insn;
  9753. zext_patch[1].dst_reg = insn.dst_reg;
  9754. zext_patch[1].src_reg = insn.dst_reg;
  9755. patch = zext_patch;
  9756. patch_len = 2;
  9757. apply_patch_buffer:
  9758. new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
  9759. if (!new_prog)
  9760. return -ENOMEM;
  9761. env->prog = new_prog;
  9762. insns = new_prog->insnsi;
  9763. aux = env->insn_aux_data;
  9764. delta += patch_len - 1;
  9765. }
  9766. return 0;
  9767. }
  9768. /* convert load instructions that access fields of a context type into a
  9769. * sequence of instructions that access fields of the underlying structure:
  9770. * struct __sk_buff -> struct sk_buff
  9771. * struct bpf_sock_ops -> struct sock
  9772. */
  9773. static int convert_ctx_accesses(struct bpf_verifier_env *env)
  9774. {
  9775. const struct bpf_verifier_ops *ops = env->ops;
  9776. int i, cnt, size, ctx_field_size, delta = 0;
  9777. const int insn_cnt = env->prog->len;
  9778. struct bpf_insn insn_buf[16], *insn;
  9779. u32 target_size, size_default, off;
  9780. struct bpf_prog *new_prog;
  9781. enum bpf_access_type type;
  9782. bool is_narrower_load;
  9783. if (ops->gen_prologue || env->seen_direct_write) {
  9784. if (!ops->gen_prologue) {
  9785. verbose(env, "bpf verifier is misconfigured\n");
  9786. return -EINVAL;
  9787. }
  9788. cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
  9789. env->prog);
  9790. if (cnt >= ARRAY_SIZE(insn_buf)) {
  9791. verbose(env, "bpf verifier is misconfigured\n");
  9792. return -EINVAL;
  9793. } else if (cnt) {
  9794. new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
  9795. if (!new_prog)
  9796. return -ENOMEM;
  9797. env->prog = new_prog;
  9798. delta += cnt - 1;
  9799. }
  9800. }
  9801. if (bpf_prog_is_dev_bound(env->prog->aux))
  9802. return 0;
  9803. insn = env->prog->insnsi + delta;
  9804. for (i = 0; i < insn_cnt; i++, insn++) {
  9805. bpf_convert_ctx_access_t convert_ctx_access;
  9806. bool ctx_access;
  9807. if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
  9808. insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
  9809. insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  9810. insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
  9811. type = BPF_READ;
  9812. ctx_access = true;
  9813. } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
  9814. insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
  9815. insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  9816. insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
  9817. insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
  9818. insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
  9819. insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
  9820. insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
  9821. type = BPF_WRITE;
  9822. ctx_access = BPF_CLASS(insn->code) == BPF_STX;
  9823. } else {
  9824. continue;
  9825. }
  9826. if (type == BPF_WRITE &&
  9827. env->insn_aux_data[i + delta].sanitize_stack_spill) {
  9828. struct bpf_insn patch[] = {
  9829. *insn,
  9830. BPF_ST_NOSPEC(),
  9831. };
  9832. cnt = ARRAY_SIZE(patch);
  9833. new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
  9834. if (!new_prog)
  9835. return -ENOMEM;
  9836. delta += cnt - 1;
  9837. env->prog = new_prog;
  9838. insn = new_prog->insnsi + i + delta;
  9839. continue;
  9840. }
  9841. if (!ctx_access)
  9842. continue;
  9843. switch (env->insn_aux_data[i + delta].ptr_type) {
  9844. case PTR_TO_CTX:
  9845. if (!ops->convert_ctx_access)
  9846. continue;
  9847. convert_ctx_access = ops->convert_ctx_access;
  9848. break;
  9849. case PTR_TO_SOCKET:
  9850. case PTR_TO_SOCK_COMMON:
  9851. convert_ctx_access = bpf_sock_convert_ctx_access;
  9852. break;
  9853. case PTR_TO_TCP_SOCK:
  9854. convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
  9855. break;
  9856. case PTR_TO_XDP_SOCK:
  9857. convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
  9858. break;
  9859. case PTR_TO_BTF_ID:
  9860. if (type == BPF_READ) {
  9861. insn->code = BPF_LDX | BPF_PROBE_MEM |
  9862. BPF_SIZE((insn)->code);
  9863. env->prog->aux->num_exentries++;
  9864. } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
  9865. verbose(env, "Writes through BTF pointers are not allowed\n");
  9866. return -EINVAL;
  9867. }
  9868. continue;
  9869. default:
  9870. continue;
  9871. }
  9872. ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
  9873. size = BPF_LDST_BYTES(insn);
  9874. /* If the read access is a narrower load of the field,
  9875. * convert to a 4/8-byte load, to minimum program type specific
  9876. * convert_ctx_access changes. If conversion is successful,
  9877. * we will apply proper mask to the result.
  9878. */
  9879. is_narrower_load = size < ctx_field_size;
  9880. size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
  9881. off = insn->off;
  9882. if (is_narrower_load) {
  9883. u8 size_code;
  9884. if (type == BPF_WRITE) {
  9885. verbose(env, "bpf verifier narrow ctx access misconfigured\n");
  9886. return -EINVAL;
  9887. }
  9888. size_code = BPF_H;
  9889. if (ctx_field_size == 4)
  9890. size_code = BPF_W;
  9891. else if (ctx_field_size == 8)
  9892. size_code = BPF_DW;
  9893. insn->off = off & ~(size_default - 1);
  9894. insn->code = BPF_LDX | BPF_MEM | size_code;
  9895. }
  9896. target_size = 0;
  9897. cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
  9898. &target_size);
  9899. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
  9900. (ctx_field_size && !target_size)) {
  9901. verbose(env, "bpf verifier is misconfigured\n");
  9902. return -EINVAL;
  9903. }
  9904. if (is_narrower_load && size < target_size) {
  9905. u8 shift = bpf_ctx_narrow_access_offset(
  9906. off, size, size_default) * 8;
  9907. if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
  9908. verbose(env, "bpf verifier narrow ctx load misconfigured\n");
  9909. return -EINVAL;
  9910. }
  9911. if (ctx_field_size <= 4) {
  9912. if (shift)
  9913. insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
  9914. insn->dst_reg,
  9915. shift);
  9916. insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
  9917. (1 << size * 8) - 1);
  9918. } else {
  9919. if (shift)
  9920. insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
  9921. insn->dst_reg,
  9922. shift);
  9923. insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
  9924. (1ULL << size * 8) - 1);
  9925. }
  9926. }
  9927. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  9928. if (!new_prog)
  9929. return -ENOMEM;
  9930. delta += cnt - 1;
  9931. /* keep walking new program and skip insns we just inserted */
  9932. env->prog = new_prog;
  9933. insn = new_prog->insnsi + i + delta;
  9934. }
  9935. return 0;
  9936. }
  9937. static int jit_subprogs(struct bpf_verifier_env *env)
  9938. {
  9939. struct bpf_prog *prog = env->prog, **func, *tmp;
  9940. int i, j, subprog_start, subprog_end = 0, len, subprog;
  9941. struct bpf_map *map_ptr;
  9942. struct bpf_insn *insn;
  9943. void *old_bpf_func;
  9944. int err, num_exentries;
  9945. if (env->subprog_cnt <= 1)
  9946. return 0;
  9947. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  9948. if (insn->code != (BPF_JMP | BPF_CALL) ||
  9949. insn->src_reg != BPF_PSEUDO_CALL)
  9950. continue;
  9951. /* Upon error here we cannot fall back to interpreter but
  9952. * need a hard reject of the program. Thus -EFAULT is
  9953. * propagated in any case.
  9954. */
  9955. subprog = find_subprog(env, i + insn->imm + 1);
  9956. if (subprog < 0) {
  9957. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  9958. i + insn->imm + 1);
  9959. return -EFAULT;
  9960. }
  9961. /* temporarily remember subprog id inside insn instead of
  9962. * aux_data, since next loop will split up all insns into funcs
  9963. */
  9964. insn->off = subprog;
  9965. /* remember original imm in case JIT fails and fallback
  9966. * to interpreter will be needed
  9967. */
  9968. env->insn_aux_data[i].call_imm = insn->imm;
  9969. /* point imm to __bpf_call_base+1 from JITs point of view */
  9970. insn->imm = 1;
  9971. }
  9972. err = bpf_prog_alloc_jited_linfo(prog);
  9973. if (err)
  9974. goto out_undo_insn;
  9975. err = -ENOMEM;
  9976. func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
  9977. if (!func)
  9978. goto out_undo_insn;
  9979. for (i = 0; i < env->subprog_cnt; i++) {
  9980. subprog_start = subprog_end;
  9981. subprog_end = env->subprog_info[i + 1].start;
  9982. len = subprog_end - subprog_start;
  9983. /* BPF_PROG_RUN doesn't call subprogs directly,
  9984. * hence main prog stats include the runtime of subprogs.
  9985. * subprogs don't have IDs and not reachable via prog_get_next_id
  9986. * func[i]->aux->stats will never be accessed and stays NULL
  9987. */
  9988. func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
  9989. if (!func[i])
  9990. goto out_free;
  9991. memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
  9992. len * sizeof(struct bpf_insn));
  9993. func[i]->type = prog->type;
  9994. func[i]->len = len;
  9995. if (bpf_prog_calc_tag(func[i]))
  9996. goto out_free;
  9997. func[i]->is_func = 1;
  9998. func[i]->aux->func_idx = i;
  9999. /* the btf and func_info will be freed only at prog->aux */
  10000. func[i]->aux->btf = prog->aux->btf;
  10001. func[i]->aux->func_info = prog->aux->func_info;
  10002. for (j = 0; j < prog->aux->size_poke_tab; j++) {
  10003. u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
  10004. int ret;
  10005. if (!(insn_idx >= subprog_start &&
  10006. insn_idx <= subprog_end))
  10007. continue;
  10008. ret = bpf_jit_add_poke_descriptor(func[i],
  10009. &prog->aux->poke_tab[j]);
  10010. if (ret < 0) {
  10011. verbose(env, "adding tail call poke descriptor failed\n");
  10012. goto out_free;
  10013. }
  10014. func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
  10015. map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
  10016. ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
  10017. if (ret < 0) {
  10018. verbose(env, "tracking tail call prog failed\n");
  10019. goto out_free;
  10020. }
  10021. }
  10022. /* Use bpf_prog_F_tag to indicate functions in stack traces.
  10023. * Long term would need debug info to populate names
  10024. */
  10025. func[i]->aux->name[0] = 'F';
  10026. func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
  10027. func[i]->jit_requested = 1;
  10028. func[i]->aux->linfo = prog->aux->linfo;
  10029. func[i]->aux->nr_linfo = prog->aux->nr_linfo;
  10030. func[i]->aux->jited_linfo = prog->aux->jited_linfo;
  10031. func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
  10032. num_exentries = 0;
  10033. insn = func[i]->insnsi;
  10034. for (j = 0; j < func[i]->len; j++, insn++) {
  10035. if (BPF_CLASS(insn->code) == BPF_LDX &&
  10036. BPF_MODE(insn->code) == BPF_PROBE_MEM)
  10037. num_exentries++;
  10038. }
  10039. func[i]->aux->num_exentries = num_exentries;
  10040. func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
  10041. func[i] = bpf_int_jit_compile(func[i]);
  10042. if (!func[i]->jited) {
  10043. err = -ENOTSUPP;
  10044. goto out_free;
  10045. }
  10046. cond_resched();
  10047. }
  10048. /* Untrack main program's aux structs so that during map_poke_run()
  10049. * we will not stumble upon the unfilled poke descriptors; each
  10050. * of the main program's poke descs got distributed across subprogs
  10051. * and got tracked onto map, so we are sure that none of them will
  10052. * be missed after the operation below
  10053. */
  10054. for (i = 0; i < prog->aux->size_poke_tab; i++) {
  10055. map_ptr = prog->aux->poke_tab[i].tail_call.map;
  10056. map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
  10057. }
  10058. /* at this point all bpf functions were successfully JITed
  10059. * now populate all bpf_calls with correct addresses and
  10060. * run last pass of JIT
  10061. */
  10062. for (i = 0; i < env->subprog_cnt; i++) {
  10063. insn = func[i]->insnsi;
  10064. for (j = 0; j < func[i]->len; j++, insn++) {
  10065. if (insn->code != (BPF_JMP | BPF_CALL) ||
  10066. insn->src_reg != BPF_PSEUDO_CALL)
  10067. continue;
  10068. subprog = insn->off;
  10069. insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
  10070. __bpf_call_base;
  10071. }
  10072. /* we use the aux data to keep a list of the start addresses
  10073. * of the JITed images for each function in the program
  10074. *
  10075. * for some architectures, such as powerpc64, the imm field
  10076. * might not be large enough to hold the offset of the start
  10077. * address of the callee's JITed image from __bpf_call_base
  10078. *
  10079. * in such cases, we can lookup the start address of a callee
  10080. * by using its subprog id, available from the off field of
  10081. * the call instruction, as an index for this list
  10082. */
  10083. func[i]->aux->func = func;
  10084. func[i]->aux->func_cnt = env->subprog_cnt;
  10085. }
  10086. for (i = 0; i < env->subprog_cnt; i++) {
  10087. old_bpf_func = func[i]->bpf_func;
  10088. tmp = bpf_int_jit_compile(func[i]);
  10089. if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
  10090. verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
  10091. err = -ENOTSUPP;
  10092. goto out_free;
  10093. }
  10094. cond_resched();
  10095. }
  10096. /* finally lock prog and jit images for all functions and
  10097. * populate kallsysm
  10098. */
  10099. for (i = 0; i < env->subprog_cnt; i++) {
  10100. bpf_prog_lock_ro(func[i]);
  10101. bpf_prog_kallsyms_add(func[i]);
  10102. }
  10103. /* Last step: make now unused interpreter insns from main
  10104. * prog consistent for later dump requests, so they can
  10105. * later look the same as if they were interpreted only.
  10106. */
  10107. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  10108. if (insn->code != (BPF_JMP | BPF_CALL) ||
  10109. insn->src_reg != BPF_PSEUDO_CALL)
  10110. continue;
  10111. insn->off = env->insn_aux_data[i].call_imm;
  10112. subprog = find_subprog(env, i + insn->off + 1);
  10113. insn->imm = subprog;
  10114. }
  10115. prog->jited = 1;
  10116. prog->bpf_func = func[0]->bpf_func;
  10117. prog->aux->func = func;
  10118. prog->aux->func_cnt = env->subprog_cnt;
  10119. bpf_prog_free_unused_jited_linfo(prog);
  10120. return 0;
  10121. out_free:
  10122. for (i = 0; i < env->subprog_cnt; i++) {
  10123. if (!func[i])
  10124. continue;
  10125. for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
  10126. map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
  10127. map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
  10128. }
  10129. bpf_jit_free(func[i]);
  10130. }
  10131. kfree(func);
  10132. out_undo_insn:
  10133. /* cleanup main prog to be interpreted */
  10134. prog->jit_requested = 0;
  10135. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  10136. if (insn->code != (BPF_JMP | BPF_CALL) ||
  10137. insn->src_reg != BPF_PSEUDO_CALL)
  10138. continue;
  10139. insn->off = 0;
  10140. insn->imm = env->insn_aux_data[i].call_imm;
  10141. }
  10142. bpf_prog_free_jited_linfo(prog);
  10143. return err;
  10144. }
  10145. static int fixup_call_args(struct bpf_verifier_env *env)
  10146. {
  10147. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  10148. struct bpf_prog *prog = env->prog;
  10149. struct bpf_insn *insn = prog->insnsi;
  10150. int i, depth;
  10151. #endif
  10152. int err = 0;
  10153. if (env->prog->jit_requested &&
  10154. !bpf_prog_is_dev_bound(env->prog->aux)) {
  10155. err = jit_subprogs(env);
  10156. if (err == 0)
  10157. return 0;
  10158. if (err == -EFAULT)
  10159. return err;
  10160. }
  10161. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  10162. if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
  10163. /* When JIT fails the progs with bpf2bpf calls and tail_calls
  10164. * have to be rejected, since interpreter doesn't support them yet.
  10165. */
  10166. verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
  10167. return -EINVAL;
  10168. }
  10169. for (i = 0; i < prog->len; i++, insn++) {
  10170. if (insn->code != (BPF_JMP | BPF_CALL) ||
  10171. insn->src_reg != BPF_PSEUDO_CALL)
  10172. continue;
  10173. depth = get_callee_stack_depth(env, insn, i);
  10174. if (depth < 0)
  10175. return depth;
  10176. bpf_patch_call_args(insn, depth);
  10177. }
  10178. err = 0;
  10179. #endif
  10180. return err;
  10181. }
  10182. /* fixup insn->imm field of bpf_call instructions
  10183. * and inline eligible helpers as explicit sequence of BPF instructions
  10184. *
  10185. * this function is called after eBPF program passed verification
  10186. */
  10187. static int fixup_bpf_calls(struct bpf_verifier_env *env)
  10188. {
  10189. struct bpf_prog *prog = env->prog;
  10190. bool expect_blinding = bpf_jit_blinding_enabled(prog);
  10191. struct bpf_insn *insn = prog->insnsi;
  10192. const struct bpf_func_proto *fn;
  10193. const int insn_cnt = prog->len;
  10194. const struct bpf_map_ops *ops;
  10195. struct bpf_insn_aux_data *aux;
  10196. struct bpf_insn insn_buf[16];
  10197. struct bpf_prog *new_prog;
  10198. struct bpf_map *map_ptr;
  10199. int i, ret, cnt, delta = 0;
  10200. for (i = 0; i < insn_cnt; i++, insn++) {
  10201. if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
  10202. insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
  10203. insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
  10204. insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
  10205. bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
  10206. bool isdiv = BPF_OP(insn->code) == BPF_DIV;
  10207. struct bpf_insn *patchlet;
  10208. struct bpf_insn chk_and_div[] = {
  10209. /* [R,W]x div 0 -> 0 */
  10210. BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
  10211. BPF_JNE | BPF_K, insn->src_reg,
  10212. 0, 2, 0),
  10213. BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
  10214. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  10215. *insn,
  10216. };
  10217. struct bpf_insn chk_and_mod[] = {
  10218. /* [R,W]x mod 0 -> [R,W]x */
  10219. BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
  10220. BPF_JEQ | BPF_K, insn->src_reg,
  10221. 0, 1 + (is64 ? 0 : 1), 0),
  10222. *insn,
  10223. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  10224. BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
  10225. };
  10226. patchlet = isdiv ? chk_and_div : chk_and_mod;
  10227. cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
  10228. ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
  10229. new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
  10230. if (!new_prog)
  10231. return -ENOMEM;
  10232. delta += cnt - 1;
  10233. env->prog = prog = new_prog;
  10234. insn = new_prog->insnsi + i + delta;
  10235. continue;
  10236. }
  10237. if (BPF_CLASS(insn->code) == BPF_LD &&
  10238. (BPF_MODE(insn->code) == BPF_ABS ||
  10239. BPF_MODE(insn->code) == BPF_IND)) {
  10240. cnt = env->ops->gen_ld_abs(insn, insn_buf);
  10241. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  10242. verbose(env, "bpf verifier is misconfigured\n");
  10243. return -EINVAL;
  10244. }
  10245. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  10246. if (!new_prog)
  10247. return -ENOMEM;
  10248. delta += cnt - 1;
  10249. env->prog = prog = new_prog;
  10250. insn = new_prog->insnsi + i + delta;
  10251. continue;
  10252. }
  10253. if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
  10254. insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
  10255. const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
  10256. const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
  10257. struct bpf_insn insn_buf[16];
  10258. struct bpf_insn *patch = &insn_buf[0];
  10259. bool issrc, isneg, isimm;
  10260. u32 off_reg;
  10261. aux = &env->insn_aux_data[i + delta];
  10262. if (!aux->alu_state ||
  10263. aux->alu_state == BPF_ALU_NON_POINTER)
  10264. continue;
  10265. isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
  10266. issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
  10267. BPF_ALU_SANITIZE_SRC;
  10268. isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
  10269. off_reg = issrc ? insn->src_reg : insn->dst_reg;
  10270. if (isimm) {
  10271. *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
  10272. } else {
  10273. if (isneg)
  10274. *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
  10275. *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
  10276. *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
  10277. *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
  10278. *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
  10279. *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
  10280. *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
  10281. }
  10282. if (!issrc)
  10283. *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
  10284. insn->src_reg = BPF_REG_AX;
  10285. if (isneg)
  10286. insn->code = insn->code == code_add ?
  10287. code_sub : code_add;
  10288. *patch++ = *insn;
  10289. if (issrc && isneg && !isimm)
  10290. *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
  10291. cnt = patch - insn_buf;
  10292. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  10293. if (!new_prog)
  10294. return -ENOMEM;
  10295. delta += cnt - 1;
  10296. env->prog = prog = new_prog;
  10297. insn = new_prog->insnsi + i + delta;
  10298. continue;
  10299. }
  10300. if (insn->code != (BPF_JMP | BPF_CALL))
  10301. continue;
  10302. if (insn->src_reg == BPF_PSEUDO_CALL)
  10303. continue;
  10304. if (insn->imm == BPF_FUNC_get_route_realm)
  10305. prog->dst_needed = 1;
  10306. if (insn->imm == BPF_FUNC_get_prandom_u32)
  10307. bpf_user_rnd_init_once();
  10308. if (insn->imm == BPF_FUNC_override_return)
  10309. prog->kprobe_override = 1;
  10310. if (insn->imm == BPF_FUNC_tail_call) {
  10311. /* If we tail call into other programs, we
  10312. * cannot make any assumptions since they can
  10313. * be replaced dynamically during runtime in
  10314. * the program array.
  10315. */
  10316. prog->cb_access = 1;
  10317. if (!allow_tail_call_in_subprogs(env))
  10318. prog->aux->stack_depth = MAX_BPF_STACK;
  10319. prog->aux->max_pkt_offset = MAX_PACKET_OFF;
  10320. /* mark bpf_tail_call as different opcode to avoid
  10321. * conditional branch in the interpeter for every normal
  10322. * call and to prevent accidental JITing by JIT compiler
  10323. * that doesn't support bpf_tail_call yet
  10324. */
  10325. insn->imm = 0;
  10326. insn->code = BPF_JMP | BPF_TAIL_CALL;
  10327. aux = &env->insn_aux_data[i + delta];
  10328. if (env->bpf_capable && !expect_blinding &&
  10329. prog->jit_requested &&
  10330. !bpf_map_key_poisoned(aux) &&
  10331. !bpf_map_ptr_poisoned(aux) &&
  10332. !bpf_map_ptr_unpriv(aux)) {
  10333. struct bpf_jit_poke_descriptor desc = {
  10334. .reason = BPF_POKE_REASON_TAIL_CALL,
  10335. .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
  10336. .tail_call.key = bpf_map_key_immediate(aux),
  10337. .insn_idx = i + delta,
  10338. };
  10339. ret = bpf_jit_add_poke_descriptor(prog, &desc);
  10340. if (ret < 0) {
  10341. verbose(env, "adding tail call poke descriptor failed\n");
  10342. return ret;
  10343. }
  10344. insn->imm = ret + 1;
  10345. continue;
  10346. }
  10347. if (!bpf_map_ptr_unpriv(aux))
  10348. continue;
  10349. /* instead of changing every JIT dealing with tail_call
  10350. * emit two extra insns:
  10351. * if (index >= max_entries) goto out;
  10352. * index &= array->index_mask;
  10353. * to avoid out-of-bounds cpu speculation
  10354. */
  10355. if (bpf_map_ptr_poisoned(aux)) {
  10356. verbose(env, "tail_call abusing map_ptr\n");
  10357. return -EINVAL;
  10358. }
  10359. map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
  10360. insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
  10361. map_ptr->max_entries, 2);
  10362. insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
  10363. container_of(map_ptr,
  10364. struct bpf_array,
  10365. map)->index_mask);
  10366. insn_buf[2] = *insn;
  10367. cnt = 3;
  10368. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  10369. if (!new_prog)
  10370. return -ENOMEM;
  10371. delta += cnt - 1;
  10372. env->prog = prog = new_prog;
  10373. insn = new_prog->insnsi + i + delta;
  10374. continue;
  10375. }
  10376. /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
  10377. * and other inlining handlers are currently limited to 64 bit
  10378. * only.
  10379. */
  10380. if (prog->jit_requested && BITS_PER_LONG == 64 &&
  10381. (insn->imm == BPF_FUNC_map_lookup_elem ||
  10382. insn->imm == BPF_FUNC_map_update_elem ||
  10383. insn->imm == BPF_FUNC_map_delete_elem ||
  10384. insn->imm == BPF_FUNC_map_push_elem ||
  10385. insn->imm == BPF_FUNC_map_pop_elem ||
  10386. insn->imm == BPF_FUNC_map_peek_elem)) {
  10387. aux = &env->insn_aux_data[i + delta];
  10388. if (bpf_map_ptr_poisoned(aux))
  10389. goto patch_call_imm;
  10390. map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
  10391. ops = map_ptr->ops;
  10392. if (insn->imm == BPF_FUNC_map_lookup_elem &&
  10393. ops->map_gen_lookup) {
  10394. cnt = ops->map_gen_lookup(map_ptr, insn_buf);
  10395. if (cnt == -EOPNOTSUPP)
  10396. goto patch_map_ops_generic;
  10397. if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  10398. verbose(env, "bpf verifier is misconfigured\n");
  10399. return -EINVAL;
  10400. }
  10401. new_prog = bpf_patch_insn_data(env, i + delta,
  10402. insn_buf, cnt);
  10403. if (!new_prog)
  10404. return -ENOMEM;
  10405. delta += cnt - 1;
  10406. env->prog = prog = new_prog;
  10407. insn = new_prog->insnsi + i + delta;
  10408. continue;
  10409. }
  10410. BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
  10411. (void *(*)(struct bpf_map *map, void *key))NULL));
  10412. BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
  10413. (int (*)(struct bpf_map *map, void *key))NULL));
  10414. BUILD_BUG_ON(!__same_type(ops->map_update_elem,
  10415. (int (*)(struct bpf_map *map, void *key, void *value,
  10416. u64 flags))NULL));
  10417. BUILD_BUG_ON(!__same_type(ops->map_push_elem,
  10418. (int (*)(struct bpf_map *map, void *value,
  10419. u64 flags))NULL));
  10420. BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
  10421. (int (*)(struct bpf_map *map, void *value))NULL));
  10422. BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
  10423. (int (*)(struct bpf_map *map, void *value))NULL));
  10424. patch_map_ops_generic:
  10425. switch (insn->imm) {
  10426. case BPF_FUNC_map_lookup_elem:
  10427. insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
  10428. __bpf_call_base;
  10429. continue;
  10430. case BPF_FUNC_map_update_elem:
  10431. insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
  10432. __bpf_call_base;
  10433. continue;
  10434. case BPF_FUNC_map_delete_elem:
  10435. insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
  10436. __bpf_call_base;
  10437. continue;
  10438. case BPF_FUNC_map_push_elem:
  10439. insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
  10440. __bpf_call_base;
  10441. continue;
  10442. case BPF_FUNC_map_pop_elem:
  10443. insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
  10444. __bpf_call_base;
  10445. continue;
  10446. case BPF_FUNC_map_peek_elem:
  10447. insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
  10448. __bpf_call_base;
  10449. continue;
  10450. }
  10451. goto patch_call_imm;
  10452. }
  10453. if (prog->jit_requested && BITS_PER_LONG == 64 &&
  10454. insn->imm == BPF_FUNC_jiffies64) {
  10455. struct bpf_insn ld_jiffies_addr[2] = {
  10456. BPF_LD_IMM64(BPF_REG_0,
  10457. (unsigned long)&jiffies),
  10458. };
  10459. insn_buf[0] = ld_jiffies_addr[0];
  10460. insn_buf[1] = ld_jiffies_addr[1];
  10461. insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
  10462. BPF_REG_0, 0);
  10463. cnt = 3;
  10464. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
  10465. cnt);
  10466. if (!new_prog)
  10467. return -ENOMEM;
  10468. delta += cnt - 1;
  10469. env->prog = prog = new_prog;
  10470. insn = new_prog->insnsi + i + delta;
  10471. continue;
  10472. }
  10473. patch_call_imm:
  10474. fn = env->ops->get_func_proto(insn->imm, env->prog);
  10475. /* all functions that have prototype and verifier allowed
  10476. * programs to call them, must be real in-kernel functions
  10477. */
  10478. if (!fn->func) {
  10479. verbose(env,
  10480. "kernel subsystem misconfigured func %s#%d\n",
  10481. func_id_name(insn->imm), insn->imm);
  10482. return -EFAULT;
  10483. }
  10484. insn->imm = fn->func - __bpf_call_base;
  10485. }
  10486. /* Since poke tab is now finalized, publish aux to tracker. */
  10487. for (i = 0; i < prog->aux->size_poke_tab; i++) {
  10488. map_ptr = prog->aux->poke_tab[i].tail_call.map;
  10489. if (!map_ptr->ops->map_poke_track ||
  10490. !map_ptr->ops->map_poke_untrack ||
  10491. !map_ptr->ops->map_poke_run) {
  10492. verbose(env, "bpf verifier is misconfigured\n");
  10493. return -EINVAL;
  10494. }
  10495. ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
  10496. if (ret < 0) {
  10497. verbose(env, "tracking tail call prog failed\n");
  10498. return ret;
  10499. }
  10500. }
  10501. return 0;
  10502. }
  10503. static void free_states(struct bpf_verifier_env *env)
  10504. {
  10505. struct bpf_verifier_state_list *sl, *sln;
  10506. int i;
  10507. sl = env->free_list;
  10508. while (sl) {
  10509. sln = sl->next;
  10510. free_verifier_state(&sl->state, false);
  10511. kfree(sl);
  10512. sl = sln;
  10513. }
  10514. env->free_list = NULL;
  10515. if (!env->explored_states)
  10516. return;
  10517. for (i = 0; i < state_htab_size(env); i++) {
  10518. sl = env->explored_states[i];
  10519. while (sl) {
  10520. sln = sl->next;
  10521. free_verifier_state(&sl->state, false);
  10522. kfree(sl);
  10523. sl = sln;
  10524. }
  10525. env->explored_states[i] = NULL;
  10526. }
  10527. }
  10528. static int do_check_common(struct bpf_verifier_env *env, int subprog)
  10529. {
  10530. bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
  10531. struct bpf_verifier_state *state;
  10532. struct bpf_reg_state *regs;
  10533. int ret, i;
  10534. env->prev_linfo = NULL;
  10535. env->pass_cnt++;
  10536. state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
  10537. if (!state)
  10538. return -ENOMEM;
  10539. state->curframe = 0;
  10540. state->speculative = false;
  10541. state->branches = 1;
  10542. state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
  10543. if (!state->frame[0]) {
  10544. kfree(state);
  10545. return -ENOMEM;
  10546. }
  10547. env->cur_state = state;
  10548. init_func_state(env, state->frame[0],
  10549. BPF_MAIN_FUNC /* callsite */,
  10550. 0 /* frameno */,
  10551. subprog);
  10552. regs = state->frame[state->curframe]->regs;
  10553. if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
  10554. ret = btf_prepare_func_args(env, subprog, regs);
  10555. if (ret)
  10556. goto out;
  10557. for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
  10558. if (regs[i].type == PTR_TO_CTX)
  10559. mark_reg_known_zero(env, regs, i);
  10560. else if (regs[i].type == SCALAR_VALUE)
  10561. mark_reg_unknown(env, regs, i);
  10562. }
  10563. } else {
  10564. /* 1st arg to a function */
  10565. regs[BPF_REG_1].type = PTR_TO_CTX;
  10566. mark_reg_known_zero(env, regs, BPF_REG_1);
  10567. ret = btf_check_func_arg_match(env, subprog, regs);
  10568. if (ret == -EFAULT)
  10569. /* unlikely verifier bug. abort.
  10570. * ret == 0 and ret < 0 are sadly acceptable for
  10571. * main() function due to backward compatibility.
  10572. * Like socket filter program may be written as:
  10573. * int bpf_prog(struct pt_regs *ctx)
  10574. * and never dereference that ctx in the program.
  10575. * 'struct pt_regs' is a type mismatch for socket
  10576. * filter that should be using 'struct __sk_buff'.
  10577. */
  10578. goto out;
  10579. }
  10580. ret = do_check(env);
  10581. out:
  10582. /* check for NULL is necessary, since cur_state can be freed inside
  10583. * do_check() under memory pressure.
  10584. */
  10585. if (env->cur_state) {
  10586. free_verifier_state(env->cur_state, true);
  10587. env->cur_state = NULL;
  10588. }
  10589. while (!pop_stack(env, NULL, NULL, false));
  10590. if (!ret && pop_log)
  10591. bpf_vlog_reset(&env->log, 0);
  10592. free_states(env);
  10593. return ret;
  10594. }
  10595. /* Verify all global functions in a BPF program one by one based on their BTF.
  10596. * All global functions must pass verification. Otherwise the whole program is rejected.
  10597. * Consider:
  10598. * int bar(int);
  10599. * int foo(int f)
  10600. * {
  10601. * return bar(f);
  10602. * }
  10603. * int bar(int b)
  10604. * {
  10605. * ...
  10606. * }
  10607. * foo() will be verified first for R1=any_scalar_value. During verification it
  10608. * will be assumed that bar() already verified successfully and call to bar()
  10609. * from foo() will be checked for type match only. Later bar() will be verified
  10610. * independently to check that it's safe for R1=any_scalar_value.
  10611. */
  10612. static int do_check_subprogs(struct bpf_verifier_env *env)
  10613. {
  10614. struct bpf_prog_aux *aux = env->prog->aux;
  10615. int i, ret;
  10616. if (!aux->func_info)
  10617. return 0;
  10618. for (i = 1; i < env->subprog_cnt; i++) {
  10619. if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
  10620. continue;
  10621. env->insn_idx = env->subprog_info[i].start;
  10622. WARN_ON_ONCE(env->insn_idx == 0);
  10623. ret = do_check_common(env, i);
  10624. if (ret) {
  10625. return ret;
  10626. } else if (env->log.level & BPF_LOG_LEVEL) {
  10627. verbose(env,
  10628. "Func#%d is safe for any args that match its prototype\n",
  10629. i);
  10630. }
  10631. }
  10632. return 0;
  10633. }
  10634. static int do_check_main(struct bpf_verifier_env *env)
  10635. {
  10636. int ret;
  10637. env->insn_idx = 0;
  10638. ret = do_check_common(env, 0);
  10639. if (!ret)
  10640. env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
  10641. return ret;
  10642. }
  10643. static void print_verification_stats(struct bpf_verifier_env *env)
  10644. {
  10645. int i;
  10646. if (env->log.level & BPF_LOG_STATS) {
  10647. verbose(env, "verification time %lld usec\n",
  10648. div_u64(env->verification_time, 1000));
  10649. verbose(env, "stack depth ");
  10650. for (i = 0; i < env->subprog_cnt; i++) {
  10651. u32 depth = env->subprog_info[i].stack_depth;
  10652. verbose(env, "%d", depth);
  10653. if (i + 1 < env->subprog_cnt)
  10654. verbose(env, "+");
  10655. }
  10656. verbose(env, "\n");
  10657. }
  10658. verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
  10659. "total_states %d peak_states %d mark_read %d\n",
  10660. env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
  10661. env->max_states_per_insn, env->total_states,
  10662. env->peak_states, env->longest_mark_read_walk);
  10663. }
  10664. static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
  10665. {
  10666. const struct btf_type *t, *func_proto;
  10667. const struct bpf_struct_ops *st_ops;
  10668. const struct btf_member *member;
  10669. struct bpf_prog *prog = env->prog;
  10670. u32 btf_id, member_idx;
  10671. const char *mname;
  10672. if (!prog->gpl_compatible) {
  10673. verbose(env, "struct ops programs must have a GPL compatible license\n");
  10674. return -EINVAL;
  10675. }
  10676. btf_id = prog->aux->attach_btf_id;
  10677. st_ops = bpf_struct_ops_find(btf_id);
  10678. if (!st_ops) {
  10679. verbose(env, "attach_btf_id %u is not a supported struct\n",
  10680. btf_id);
  10681. return -ENOTSUPP;
  10682. }
  10683. t = st_ops->type;
  10684. member_idx = prog->expected_attach_type;
  10685. if (member_idx >= btf_type_vlen(t)) {
  10686. verbose(env, "attach to invalid member idx %u of struct %s\n",
  10687. member_idx, st_ops->name);
  10688. return -EINVAL;
  10689. }
  10690. member = &btf_type_member(t)[member_idx];
  10691. mname = btf_name_by_offset(btf_vmlinux, member->name_off);
  10692. func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
  10693. NULL);
  10694. if (!func_proto) {
  10695. verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
  10696. mname, member_idx, st_ops->name);
  10697. return -EINVAL;
  10698. }
  10699. if (st_ops->check_member) {
  10700. int err = st_ops->check_member(t, member);
  10701. if (err) {
  10702. verbose(env, "attach to unsupported member %s of struct %s\n",
  10703. mname, st_ops->name);
  10704. return err;
  10705. }
  10706. }
  10707. prog->aux->attach_func_proto = func_proto;
  10708. prog->aux->attach_func_name = mname;
  10709. env->ops = st_ops->verifier_ops;
  10710. return 0;
  10711. }
  10712. #define SECURITY_PREFIX "security_"
  10713. static int check_attach_modify_return(unsigned long addr, const char *func_name)
  10714. {
  10715. if (within_error_injection_list(addr) ||
  10716. !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
  10717. return 0;
  10718. return -EINVAL;
  10719. }
  10720. /* non exhaustive list of sleepable bpf_lsm_*() functions */
  10721. BTF_SET_START(btf_sleepable_lsm_hooks)
  10722. #ifdef CONFIG_BPF_LSM
  10723. BTF_ID(func, bpf_lsm_bprm_committed_creds)
  10724. #else
  10725. BTF_ID_UNUSED
  10726. #endif
  10727. BTF_SET_END(btf_sleepable_lsm_hooks)
  10728. static int check_sleepable_lsm_hook(u32 btf_id)
  10729. {
  10730. return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
  10731. }
  10732. /* list of non-sleepable functions that are otherwise on
  10733. * ALLOW_ERROR_INJECTION list
  10734. */
  10735. BTF_SET_START(btf_non_sleepable_error_inject)
  10736. /* Three functions below can be called from sleepable and non-sleepable context.
  10737. * Assume non-sleepable from bpf safety point of view.
  10738. */
  10739. BTF_ID(func, __add_to_page_cache_locked)
  10740. BTF_ID(func, should_fail_alloc_page)
  10741. BTF_ID(func, should_failslab)
  10742. BTF_SET_END(btf_non_sleepable_error_inject)
  10743. static int check_non_sleepable_error_inject(u32 btf_id)
  10744. {
  10745. return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
  10746. }
  10747. int bpf_check_attach_target(struct bpf_verifier_log *log,
  10748. const struct bpf_prog *prog,
  10749. const struct bpf_prog *tgt_prog,
  10750. u32 btf_id,
  10751. struct bpf_attach_target_info *tgt_info)
  10752. {
  10753. bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
  10754. const char prefix[] = "btf_trace_";
  10755. int ret = 0, subprog = -1, i;
  10756. const struct btf_type *t;
  10757. bool conservative = true;
  10758. const char *tname;
  10759. struct btf *btf;
  10760. long addr = 0;
  10761. if (!btf_id) {
  10762. bpf_log(log, "Tracing programs must provide btf_id\n");
  10763. return -EINVAL;
  10764. }
  10765. btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
  10766. if (!btf) {
  10767. bpf_log(log,
  10768. "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
  10769. return -EINVAL;
  10770. }
  10771. t = btf_type_by_id(btf, btf_id);
  10772. if (!t) {
  10773. bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
  10774. return -EINVAL;
  10775. }
  10776. tname = btf_name_by_offset(btf, t->name_off);
  10777. if (!tname) {
  10778. bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
  10779. return -EINVAL;
  10780. }
  10781. if (tgt_prog) {
  10782. struct bpf_prog_aux *aux = tgt_prog->aux;
  10783. for (i = 0; i < aux->func_info_cnt; i++)
  10784. if (aux->func_info[i].type_id == btf_id) {
  10785. subprog = i;
  10786. break;
  10787. }
  10788. if (subprog == -1) {
  10789. bpf_log(log, "Subprog %s doesn't exist\n", tname);
  10790. return -EINVAL;
  10791. }
  10792. conservative = aux->func_info_aux[subprog].unreliable;
  10793. if (prog_extension) {
  10794. if (conservative) {
  10795. bpf_log(log,
  10796. "Cannot replace static functions\n");
  10797. return -EINVAL;
  10798. }
  10799. if (!prog->jit_requested) {
  10800. bpf_log(log,
  10801. "Extension programs should be JITed\n");
  10802. return -EINVAL;
  10803. }
  10804. }
  10805. if (!tgt_prog->jited) {
  10806. bpf_log(log, "Can attach to only JITed progs\n");
  10807. return -EINVAL;
  10808. }
  10809. if (tgt_prog->type == prog->type) {
  10810. /* Cannot fentry/fexit another fentry/fexit program.
  10811. * Cannot attach program extension to another extension.
  10812. * It's ok to attach fentry/fexit to extension program.
  10813. */
  10814. bpf_log(log, "Cannot recursively attach\n");
  10815. return -EINVAL;
  10816. }
  10817. if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
  10818. prog_extension &&
  10819. (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
  10820. tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
  10821. /* Program extensions can extend all program types
  10822. * except fentry/fexit. The reason is the following.
  10823. * The fentry/fexit programs are used for performance
  10824. * analysis, stats and can be attached to any program
  10825. * type except themselves. When extension program is
  10826. * replacing XDP function it is necessary to allow
  10827. * performance analysis of all functions. Both original
  10828. * XDP program and its program extension. Hence
  10829. * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
  10830. * allowed. If extending of fentry/fexit was allowed it
  10831. * would be possible to create long call chain
  10832. * fentry->extension->fentry->extension beyond
  10833. * reasonable stack size. Hence extending fentry is not
  10834. * allowed.
  10835. */
  10836. bpf_log(log, "Cannot extend fentry/fexit\n");
  10837. return -EINVAL;
  10838. }
  10839. } else {
  10840. if (prog_extension) {
  10841. bpf_log(log, "Cannot replace kernel functions\n");
  10842. return -EINVAL;
  10843. }
  10844. }
  10845. switch (prog->expected_attach_type) {
  10846. case BPF_TRACE_RAW_TP:
  10847. if (tgt_prog) {
  10848. bpf_log(log,
  10849. "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
  10850. return -EINVAL;
  10851. }
  10852. if (!btf_type_is_typedef(t)) {
  10853. bpf_log(log, "attach_btf_id %u is not a typedef\n",
  10854. btf_id);
  10855. return -EINVAL;
  10856. }
  10857. if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
  10858. bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
  10859. btf_id, tname);
  10860. return -EINVAL;
  10861. }
  10862. tname += sizeof(prefix) - 1;
  10863. t = btf_type_by_id(btf, t->type);
  10864. if (!btf_type_is_ptr(t))
  10865. /* should never happen in valid vmlinux build */
  10866. return -EINVAL;
  10867. t = btf_type_by_id(btf, t->type);
  10868. if (!btf_type_is_func_proto(t))
  10869. /* should never happen in valid vmlinux build */
  10870. return -EINVAL;
  10871. break;
  10872. case BPF_TRACE_ITER:
  10873. if (!btf_type_is_func(t)) {
  10874. bpf_log(log, "attach_btf_id %u is not a function\n",
  10875. btf_id);
  10876. return -EINVAL;
  10877. }
  10878. t = btf_type_by_id(btf, t->type);
  10879. if (!btf_type_is_func_proto(t))
  10880. return -EINVAL;
  10881. ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
  10882. if (ret)
  10883. return ret;
  10884. break;
  10885. default:
  10886. if (!prog_extension)
  10887. return -EINVAL;
  10888. fallthrough;
  10889. case BPF_MODIFY_RETURN:
  10890. case BPF_LSM_MAC:
  10891. case BPF_TRACE_FENTRY:
  10892. case BPF_TRACE_FEXIT:
  10893. if (!btf_type_is_func(t)) {
  10894. bpf_log(log, "attach_btf_id %u is not a function\n",
  10895. btf_id);
  10896. return -EINVAL;
  10897. }
  10898. if (prog_extension &&
  10899. btf_check_type_match(log, prog, btf, t))
  10900. return -EINVAL;
  10901. t = btf_type_by_id(btf, t->type);
  10902. if (!btf_type_is_func_proto(t))
  10903. return -EINVAL;
  10904. if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
  10905. (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
  10906. prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
  10907. return -EINVAL;
  10908. if (tgt_prog && conservative)
  10909. t = NULL;
  10910. ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
  10911. if (ret < 0)
  10912. return ret;
  10913. if (tgt_prog) {
  10914. if (subprog == 0)
  10915. addr = (long) tgt_prog->bpf_func;
  10916. else
  10917. addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
  10918. } else {
  10919. addr = kallsyms_lookup_name(tname);
  10920. if (!addr) {
  10921. bpf_log(log,
  10922. "The address of function %s cannot be found\n",
  10923. tname);
  10924. return -ENOENT;
  10925. }
  10926. }
  10927. if (prog->aux->sleepable) {
  10928. ret = -EINVAL;
  10929. switch (prog->type) {
  10930. case BPF_PROG_TYPE_TRACING:
  10931. /* fentry/fexit/fmod_ret progs can be sleepable only if they are
  10932. * attached to ALLOW_ERROR_INJECTION and are not in denylist.
  10933. */
  10934. if (!check_non_sleepable_error_inject(btf_id) &&
  10935. within_error_injection_list(addr))
  10936. ret = 0;
  10937. break;
  10938. case BPF_PROG_TYPE_LSM:
  10939. /* LSM progs check that they are attached to bpf_lsm_*() funcs.
  10940. * Only some of them are sleepable.
  10941. */
  10942. if (check_sleepable_lsm_hook(btf_id))
  10943. ret = 0;
  10944. break;
  10945. default:
  10946. break;
  10947. }
  10948. if (ret) {
  10949. bpf_log(log, "%s is not sleepable\n", tname);
  10950. return ret;
  10951. }
  10952. } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
  10953. if (tgt_prog) {
  10954. bpf_log(log, "can't modify return codes of BPF programs\n");
  10955. return -EINVAL;
  10956. }
  10957. ret = check_attach_modify_return(addr, tname);
  10958. if (ret) {
  10959. bpf_log(log, "%s() is not modifiable\n", tname);
  10960. return ret;
  10961. }
  10962. }
  10963. break;
  10964. }
  10965. tgt_info->tgt_addr = addr;
  10966. tgt_info->tgt_name = tname;
  10967. tgt_info->tgt_type = t;
  10968. return 0;
  10969. }
  10970. static int check_attach_btf_id(struct bpf_verifier_env *env)
  10971. {
  10972. struct bpf_prog *prog = env->prog;
  10973. struct bpf_prog *tgt_prog = prog->aux->dst_prog;
  10974. struct bpf_attach_target_info tgt_info = {};
  10975. u32 btf_id = prog->aux->attach_btf_id;
  10976. struct bpf_trampoline *tr;
  10977. int ret;
  10978. u64 key;
  10979. if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
  10980. prog->type != BPF_PROG_TYPE_LSM) {
  10981. verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
  10982. return -EINVAL;
  10983. }
  10984. if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
  10985. return check_struct_ops_btf_id(env);
  10986. if (prog->type != BPF_PROG_TYPE_TRACING &&
  10987. prog->type != BPF_PROG_TYPE_LSM &&
  10988. prog->type != BPF_PROG_TYPE_EXT)
  10989. return 0;
  10990. ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
  10991. if (ret)
  10992. return ret;
  10993. if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
  10994. /* to make freplace equivalent to their targets, they need to
  10995. * inherit env->ops and expected_attach_type for the rest of the
  10996. * verification
  10997. */
  10998. env->ops = bpf_verifier_ops[tgt_prog->type];
  10999. prog->expected_attach_type = tgt_prog->expected_attach_type;
  11000. }
  11001. /* store info about the attachment target that will be used later */
  11002. prog->aux->attach_func_proto = tgt_info.tgt_type;
  11003. prog->aux->attach_func_name = tgt_info.tgt_name;
  11004. if (tgt_prog) {
  11005. prog->aux->saved_dst_prog_type = tgt_prog->type;
  11006. prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
  11007. }
  11008. if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
  11009. prog->aux->attach_btf_trace = true;
  11010. return 0;
  11011. } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
  11012. if (!bpf_iter_prog_supported(prog))
  11013. return -EINVAL;
  11014. return 0;
  11015. }
  11016. if (prog->type == BPF_PROG_TYPE_LSM) {
  11017. ret = bpf_lsm_verify_prog(&env->log, prog);
  11018. if (ret < 0)
  11019. return ret;
  11020. }
  11021. key = bpf_trampoline_compute_key(tgt_prog, btf_id);
  11022. tr = bpf_trampoline_get(key, &tgt_info);
  11023. if (!tr)
  11024. return -ENOMEM;
  11025. prog->aux->dst_trampoline = tr;
  11026. return 0;
  11027. }
  11028. struct btf *bpf_get_btf_vmlinux(void)
  11029. {
  11030. if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
  11031. mutex_lock(&bpf_verifier_lock);
  11032. if (!btf_vmlinux)
  11033. btf_vmlinux = btf_parse_vmlinux();
  11034. mutex_unlock(&bpf_verifier_lock);
  11035. }
  11036. return btf_vmlinux;
  11037. }
  11038. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
  11039. union bpf_attr __user *uattr)
  11040. {
  11041. u64 start_time = ktime_get_ns();
  11042. struct bpf_verifier_env *env;
  11043. struct bpf_verifier_log *log;
  11044. int i, len, ret = -EINVAL;
  11045. bool is_priv;
  11046. /* no program is valid */
  11047. if (ARRAY_SIZE(bpf_verifier_ops) == 0)
  11048. return -EINVAL;
  11049. /* 'struct bpf_verifier_env' can be global, but since it's not small,
  11050. * allocate/free it every time bpf_check() is called
  11051. */
  11052. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  11053. if (!env)
  11054. return -ENOMEM;
  11055. log = &env->log;
  11056. len = (*prog)->len;
  11057. env->insn_aux_data =
  11058. vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
  11059. ret = -ENOMEM;
  11060. if (!env->insn_aux_data)
  11061. goto err_free_env;
  11062. for (i = 0; i < len; i++)
  11063. env->insn_aux_data[i].orig_idx = i;
  11064. env->prog = *prog;
  11065. env->ops = bpf_verifier_ops[env->prog->type];
  11066. is_priv = bpf_capable();
  11067. bpf_get_btf_vmlinux();
  11068. /* grab the mutex to protect few globals used by verifier */
  11069. if (!is_priv)
  11070. mutex_lock(&bpf_verifier_lock);
  11071. if (attr->log_level || attr->log_buf || attr->log_size) {
  11072. /* user requested verbose verifier output
  11073. * and supplied buffer to store the verification trace
  11074. */
  11075. log->level = attr->log_level;
  11076. log->ubuf = (char __user *) (unsigned long) attr->log_buf;
  11077. log->len_total = attr->log_size;
  11078. /* log attributes have to be sane */
  11079. if (!bpf_verifier_log_attr_valid(log)) {
  11080. ret = -EINVAL;
  11081. goto err_unlock;
  11082. }
  11083. }
  11084. if (IS_ERR(btf_vmlinux)) {
  11085. /* Either gcc or pahole or kernel are broken. */
  11086. verbose(env, "in-kernel BTF is malformed\n");
  11087. ret = PTR_ERR(btf_vmlinux);
  11088. goto skip_full_check;
  11089. }
  11090. env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
  11091. if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
  11092. env->strict_alignment = true;
  11093. if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
  11094. env->strict_alignment = false;
  11095. env->allow_ptr_leaks = bpf_allow_ptr_leaks();
  11096. env->allow_uninit_stack = bpf_allow_uninit_stack();
  11097. env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
  11098. env->bypass_spec_v1 = bpf_bypass_spec_v1();
  11099. env->bypass_spec_v4 = bpf_bypass_spec_v4();
  11100. env->bpf_capable = bpf_capable();
  11101. if (is_priv)
  11102. env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
  11103. env->explored_states = kvcalloc(state_htab_size(env),
  11104. sizeof(struct bpf_verifier_state_list *),
  11105. GFP_USER);
  11106. ret = -ENOMEM;
  11107. if (!env->explored_states)
  11108. goto skip_full_check;
  11109. ret = check_subprogs(env);
  11110. if (ret < 0)
  11111. goto skip_full_check;
  11112. ret = check_btf_info(env, attr, uattr);
  11113. if (ret < 0)
  11114. goto skip_full_check;
  11115. ret = check_attach_btf_id(env);
  11116. if (ret)
  11117. goto skip_full_check;
  11118. ret = resolve_pseudo_ldimm64(env);
  11119. if (ret < 0)
  11120. goto skip_full_check;
  11121. if (bpf_prog_is_dev_bound(env->prog->aux)) {
  11122. ret = bpf_prog_offload_verifier_prep(env->prog);
  11123. if (ret)
  11124. goto skip_full_check;
  11125. }
  11126. ret = check_cfg(env);
  11127. if (ret < 0)
  11128. goto skip_full_check;
  11129. ret = do_check_subprogs(env);
  11130. ret = ret ?: do_check_main(env);
  11131. if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
  11132. ret = bpf_prog_offload_finalize(env);
  11133. skip_full_check:
  11134. kvfree(env->explored_states);
  11135. if (ret == 0)
  11136. ret = check_max_stack_depth(env);
  11137. /* instruction rewrites happen after this point */
  11138. if (is_priv) {
  11139. if (ret == 0)
  11140. opt_hard_wire_dead_code_branches(env);
  11141. if (ret == 0)
  11142. ret = opt_remove_dead_code(env);
  11143. if (ret == 0)
  11144. ret = opt_remove_nops(env);
  11145. } else {
  11146. if (ret == 0)
  11147. sanitize_dead_code(env);
  11148. }
  11149. if (ret == 0)
  11150. /* program is valid, convert *(u32*)(ctx + off) accesses */
  11151. ret = convert_ctx_accesses(env);
  11152. if (ret == 0)
  11153. ret = fixup_bpf_calls(env);
  11154. /* do 32-bit optimization after insn patching has done so those patched
  11155. * insns could be handled correctly.
  11156. */
  11157. if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
  11158. ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
  11159. env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
  11160. : false;
  11161. }
  11162. if (ret == 0)
  11163. ret = fixup_call_args(env);
  11164. env->verification_time = ktime_get_ns() - start_time;
  11165. print_verification_stats(env);
  11166. if (log->level && bpf_verifier_log_full(log))
  11167. ret = -ENOSPC;
  11168. if (log->level && !log->ubuf) {
  11169. ret = -EFAULT;
  11170. goto err_release_maps;
  11171. }
  11172. if (ret == 0 && env->used_map_cnt) {
  11173. /* if program passed verifier, update used_maps in bpf_prog_info */
  11174. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  11175. sizeof(env->used_maps[0]),
  11176. GFP_KERNEL);
  11177. if (!env->prog->aux->used_maps) {
  11178. ret = -ENOMEM;
  11179. goto err_release_maps;
  11180. }
  11181. memcpy(env->prog->aux->used_maps, env->used_maps,
  11182. sizeof(env->used_maps[0]) * env->used_map_cnt);
  11183. env->prog->aux->used_map_cnt = env->used_map_cnt;
  11184. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  11185. * bpf_ld_imm64 instructions
  11186. */
  11187. convert_pseudo_ld_imm64(env);
  11188. }
  11189. if (ret == 0)
  11190. adjust_btf_func(env);
  11191. err_release_maps:
  11192. if (!env->prog->aux->used_maps)
  11193. /* if we didn't copy map pointers into bpf_prog_info, release
  11194. * them now. Otherwise free_used_maps() will release them.
  11195. */
  11196. release_maps(env);
  11197. /* extension progs temporarily inherit the attach_type of their targets
  11198. for verification purposes, so set it back to zero before returning
  11199. */
  11200. if (env->prog->type == BPF_PROG_TYPE_EXT)
  11201. env->prog->expected_attach_type = 0;
  11202. *prog = env->prog;
  11203. err_unlock:
  11204. if (!is_priv)
  11205. mutex_unlock(&bpf_verifier_lock);
  11206. vfree(env->insn_aux_data);
  11207. err_free_env:
  11208. kfree(env);
  11209. return ret;
  11210. }