verifier.c 176 KB

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