verifier.c 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995
  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. /* dst_input() and dst_output() can't write for now */
  1195. if (t == BPF_WRITE)
  1196. return false;
  1197. /* fallthrough */
  1198. case BPF_PROG_TYPE_SCHED_CLS:
  1199. case BPF_PROG_TYPE_SCHED_ACT:
  1200. case BPF_PROG_TYPE_XDP:
  1201. case BPF_PROG_TYPE_LWT_XMIT:
  1202. case BPF_PROG_TYPE_SK_SKB:
  1203. case BPF_PROG_TYPE_SK_MSG:
  1204. if (meta)
  1205. return meta->pkt_access;
  1206. env->seen_direct_write = true;
  1207. return true;
  1208. default:
  1209. return false;
  1210. }
  1211. }
  1212. static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
  1213. int off, int size, bool zero_size_allowed)
  1214. {
  1215. struct bpf_reg_state *regs = cur_regs(env);
  1216. struct bpf_reg_state *reg = &regs[regno];
  1217. if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
  1218. (u64)off + size > reg->range) {
  1219. verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
  1220. off, size, regno, reg->id, reg->off, reg->range);
  1221. return -EACCES;
  1222. }
  1223. return 0;
  1224. }
  1225. static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
  1226. int size, bool zero_size_allowed)
  1227. {
  1228. struct bpf_reg_state *regs = cur_regs(env);
  1229. struct bpf_reg_state *reg = &regs[regno];
  1230. int err;
  1231. /* We may have added a variable offset to the packet pointer; but any
  1232. * reg->range we have comes after that. We are only checking the fixed
  1233. * offset.
  1234. */
  1235. /* We don't allow negative numbers, because we aren't tracking enough
  1236. * detail to prove they're safe.
  1237. */
  1238. if (reg->smin_value < 0) {
  1239. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  1240. regno);
  1241. return -EACCES;
  1242. }
  1243. err = __check_packet_access(env, regno, off, size, zero_size_allowed);
  1244. if (err) {
  1245. verbose(env, "R%d offset is outside of the packet\n", regno);
  1246. return err;
  1247. }
  1248. return err;
  1249. }
  1250. /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
  1251. static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
  1252. enum bpf_access_type t, enum bpf_reg_type *reg_type)
  1253. {
  1254. struct bpf_insn_access_aux info = {
  1255. .reg_type = *reg_type,
  1256. };
  1257. if (env->ops->is_valid_access &&
  1258. env->ops->is_valid_access(off, size, t, env->prog, &info)) {
  1259. /* A non zero info.ctx_field_size indicates that this field is a
  1260. * candidate for later verifier transformation to load the whole
  1261. * field and then apply a mask when accessed with a narrower
  1262. * access than actual ctx access size. A zero info.ctx_field_size
  1263. * will only allow for whole field access and rejects any other
  1264. * type of narrower access.
  1265. */
  1266. *reg_type = info.reg_type;
  1267. env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
  1268. /* remember the offset of last byte accessed in ctx */
  1269. if (env->prog->aux->max_ctx_offset < off + size)
  1270. env->prog->aux->max_ctx_offset = off + size;
  1271. return 0;
  1272. }
  1273. verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
  1274. return -EACCES;
  1275. }
  1276. static bool __is_pointer_value(bool allow_ptr_leaks,
  1277. const struct bpf_reg_state *reg)
  1278. {
  1279. if (allow_ptr_leaks)
  1280. return false;
  1281. return reg->type != SCALAR_VALUE;
  1282. }
  1283. static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
  1284. {
  1285. return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
  1286. }
  1287. static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
  1288. {
  1289. const struct bpf_reg_state *reg = cur_regs(env) + regno;
  1290. return reg->type == PTR_TO_CTX;
  1291. }
  1292. static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
  1293. {
  1294. const struct bpf_reg_state *reg = cur_regs(env) + regno;
  1295. return type_is_pkt_pointer(reg->type);
  1296. }
  1297. static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
  1298. const struct bpf_reg_state *reg,
  1299. int off, int size, bool strict)
  1300. {
  1301. struct tnum reg_off;
  1302. int ip_align;
  1303. /* Byte size accesses are always allowed. */
  1304. if (!strict || size == 1)
  1305. return 0;
  1306. /* For platforms that do not have a Kconfig enabling
  1307. * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
  1308. * NET_IP_ALIGN is universally set to '2'. And on platforms
  1309. * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
  1310. * to this code only in strict mode where we want to emulate
  1311. * the NET_IP_ALIGN==2 checking. Therefore use an
  1312. * unconditional IP align value of '2'.
  1313. */
  1314. ip_align = 2;
  1315. reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
  1316. if (!tnum_is_aligned(reg_off, size)) {
  1317. char tn_buf[48];
  1318. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1319. verbose(env,
  1320. "misaligned packet access off %d+%s+%d+%d size %d\n",
  1321. ip_align, tn_buf, reg->off, off, size);
  1322. return -EACCES;
  1323. }
  1324. return 0;
  1325. }
  1326. static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
  1327. const struct bpf_reg_state *reg,
  1328. const char *pointer_desc,
  1329. int off, int size, bool strict)
  1330. {
  1331. struct tnum reg_off;
  1332. /* Byte size accesses are always allowed. */
  1333. if (!strict || size == 1)
  1334. return 0;
  1335. reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
  1336. if (!tnum_is_aligned(reg_off, size)) {
  1337. char tn_buf[48];
  1338. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1339. verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
  1340. pointer_desc, tn_buf, reg->off, off, size);
  1341. return -EACCES;
  1342. }
  1343. return 0;
  1344. }
  1345. static int check_ptr_alignment(struct bpf_verifier_env *env,
  1346. const struct bpf_reg_state *reg, int off,
  1347. int size, bool strict_alignment_once)
  1348. {
  1349. bool strict = env->strict_alignment || strict_alignment_once;
  1350. const char *pointer_desc = "";
  1351. switch (reg->type) {
  1352. case PTR_TO_PACKET:
  1353. case PTR_TO_PACKET_META:
  1354. /* Special case, because of NET_IP_ALIGN. Given metadata sits
  1355. * right in front, treat it the very same way.
  1356. */
  1357. return check_pkt_ptr_alignment(env, reg, off, size, strict);
  1358. case PTR_TO_MAP_VALUE:
  1359. pointer_desc = "value ";
  1360. break;
  1361. case PTR_TO_CTX:
  1362. pointer_desc = "context ";
  1363. break;
  1364. case PTR_TO_STACK:
  1365. pointer_desc = "stack ";
  1366. /* The stack spill tracking logic in check_stack_write()
  1367. * and check_stack_read() relies on stack accesses being
  1368. * aligned.
  1369. */
  1370. strict = true;
  1371. break;
  1372. default:
  1373. break;
  1374. }
  1375. return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
  1376. strict);
  1377. }
  1378. static int update_stack_depth(struct bpf_verifier_env *env,
  1379. const struct bpf_func_state *func,
  1380. int off)
  1381. {
  1382. u16 stack = env->subprog_info[func->subprogno].stack_depth;
  1383. if (stack >= -off)
  1384. return 0;
  1385. /* update known max for given subprogram */
  1386. env->subprog_info[func->subprogno].stack_depth = -off;
  1387. return 0;
  1388. }
  1389. /* starting from main bpf function walk all instructions of the function
  1390. * and recursively walk all callees that given function can call.
  1391. * Ignore jump and exit insns.
  1392. * Since recursion is prevented by check_cfg() this algorithm
  1393. * only needs a local stack of MAX_CALL_FRAMES to remember callsites
  1394. */
  1395. static int check_max_stack_depth(struct bpf_verifier_env *env)
  1396. {
  1397. int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
  1398. struct bpf_subprog_info *subprog = env->subprog_info;
  1399. struct bpf_insn *insn = env->prog->insnsi;
  1400. int ret_insn[MAX_CALL_FRAMES];
  1401. int ret_prog[MAX_CALL_FRAMES];
  1402. process_func:
  1403. /* round up to 32-bytes, since this is granularity
  1404. * of interpreter stack size
  1405. */
  1406. depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
  1407. if (depth > MAX_BPF_STACK) {
  1408. verbose(env, "combined stack size of %d calls is %d. Too large\n",
  1409. frame + 1, depth);
  1410. return -EACCES;
  1411. }
  1412. continue_func:
  1413. subprog_end = subprog[idx + 1].start;
  1414. for (; i < subprog_end; i++) {
  1415. if (insn[i].code != (BPF_JMP | BPF_CALL))
  1416. continue;
  1417. if (insn[i].src_reg != BPF_PSEUDO_CALL)
  1418. continue;
  1419. /* remember insn and function to return to */
  1420. ret_insn[frame] = i + 1;
  1421. ret_prog[frame] = idx;
  1422. /* find the callee */
  1423. i = i + insn[i].imm + 1;
  1424. idx = find_subprog(env, i);
  1425. if (idx < 0) {
  1426. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  1427. i);
  1428. return -EFAULT;
  1429. }
  1430. frame++;
  1431. if (frame >= MAX_CALL_FRAMES) {
  1432. WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
  1433. return -EFAULT;
  1434. }
  1435. goto process_func;
  1436. }
  1437. /* end of for() loop means the last insn of the 'subprog'
  1438. * was reached. Doesn't matter whether it was JA or EXIT
  1439. */
  1440. if (frame == 0)
  1441. return 0;
  1442. depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
  1443. frame--;
  1444. i = ret_insn[frame];
  1445. idx = ret_prog[frame];
  1446. goto continue_func;
  1447. }
  1448. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  1449. static int get_callee_stack_depth(struct bpf_verifier_env *env,
  1450. const struct bpf_insn *insn, int idx)
  1451. {
  1452. int start = idx + insn->imm + 1, subprog;
  1453. subprog = find_subprog(env, start);
  1454. if (subprog < 0) {
  1455. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  1456. start);
  1457. return -EFAULT;
  1458. }
  1459. return env->subprog_info[subprog].stack_depth;
  1460. }
  1461. #endif
  1462. static int check_ctx_reg(struct bpf_verifier_env *env,
  1463. const struct bpf_reg_state *reg, int regno)
  1464. {
  1465. /* Access to ctx or passing it to a helper is only allowed in
  1466. * its original, unmodified form.
  1467. */
  1468. if (reg->off) {
  1469. verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
  1470. regno, reg->off);
  1471. return -EACCES;
  1472. }
  1473. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  1474. char tn_buf[48];
  1475. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1476. verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
  1477. return -EACCES;
  1478. }
  1479. return 0;
  1480. }
  1481. /* truncate register to smaller size (in bytes)
  1482. * must be called with size < BPF_REG_SIZE
  1483. */
  1484. static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
  1485. {
  1486. u64 mask;
  1487. /* clear high bits in bit representation */
  1488. reg->var_off = tnum_cast(reg->var_off, size);
  1489. /* fix arithmetic bounds */
  1490. mask = ((u64)1 << (size * 8)) - 1;
  1491. if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
  1492. reg->umin_value &= mask;
  1493. reg->umax_value &= mask;
  1494. } else {
  1495. reg->umin_value = 0;
  1496. reg->umax_value = mask;
  1497. }
  1498. reg->smin_value = reg->umin_value;
  1499. reg->smax_value = reg->umax_value;
  1500. }
  1501. /* check whether memory at (regno + off) is accessible for t = (read | write)
  1502. * if t==write, value_regno is a register which value is stored into memory
  1503. * if t==read, value_regno is a register which will receive the value from memory
  1504. * if t==write && value_regno==-1, some unknown value is stored into memory
  1505. * if t==read && value_regno==-1, don't care what we read from memory
  1506. */
  1507. static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
  1508. int off, int bpf_size, enum bpf_access_type t,
  1509. int value_regno, bool strict_alignment_once)
  1510. {
  1511. struct bpf_reg_state *regs = cur_regs(env);
  1512. struct bpf_reg_state *reg = regs + regno;
  1513. struct bpf_func_state *state;
  1514. int size, err = 0;
  1515. size = bpf_size_to_bytes(bpf_size);
  1516. if (size < 0)
  1517. return size;
  1518. /* alignment checks will add in reg->off themselves */
  1519. err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
  1520. if (err)
  1521. return err;
  1522. /* for access checks, reg->off is just part of off */
  1523. off += reg->off;
  1524. if (reg->type == PTR_TO_MAP_VALUE) {
  1525. if (t == BPF_WRITE && value_regno >= 0 &&
  1526. is_pointer_value(env, value_regno)) {
  1527. verbose(env, "R%d leaks addr into map\n", value_regno);
  1528. return -EACCES;
  1529. }
  1530. err = check_map_access(env, regno, off, size, false);
  1531. if (!err && t == BPF_READ && value_regno >= 0)
  1532. mark_reg_unknown(env, regs, value_regno);
  1533. } else if (reg->type == PTR_TO_CTX) {
  1534. enum bpf_reg_type reg_type = SCALAR_VALUE;
  1535. if (t == BPF_WRITE && value_regno >= 0 &&
  1536. is_pointer_value(env, value_regno)) {
  1537. verbose(env, "R%d leaks addr into ctx\n", value_regno);
  1538. return -EACCES;
  1539. }
  1540. err = check_ctx_reg(env, reg, regno);
  1541. if (err < 0)
  1542. return err;
  1543. err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
  1544. if (!err && t == BPF_READ && value_regno >= 0) {
  1545. /* ctx access returns either a scalar, or a
  1546. * PTR_TO_PACKET[_META,_END]. In the latter
  1547. * case, we know the offset is zero.
  1548. */
  1549. if (reg_type == SCALAR_VALUE)
  1550. mark_reg_unknown(env, regs, value_regno);
  1551. else
  1552. mark_reg_known_zero(env, regs,
  1553. value_regno);
  1554. regs[value_regno].id = 0;
  1555. regs[value_regno].off = 0;
  1556. regs[value_regno].range = 0;
  1557. regs[value_regno].type = reg_type;
  1558. }
  1559. } else if (reg->type == PTR_TO_STACK) {
  1560. /* stack accesses must be at a fixed offset, so that we can
  1561. * determine what type of data were returned.
  1562. * See check_stack_read().
  1563. */
  1564. if (!tnum_is_const(reg->var_off)) {
  1565. char tn_buf[48];
  1566. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1567. verbose(env, "variable stack access var_off=%s off=%d size=%d",
  1568. tn_buf, off, size);
  1569. return -EACCES;
  1570. }
  1571. off += reg->var_off.value;
  1572. if (off >= 0 || off < -MAX_BPF_STACK) {
  1573. verbose(env, "invalid stack off=%d size=%d\n", off,
  1574. size);
  1575. return -EACCES;
  1576. }
  1577. state = func(env, reg);
  1578. err = update_stack_depth(env, state, off);
  1579. if (err)
  1580. return err;
  1581. if (t == BPF_WRITE)
  1582. err = check_stack_write(env, state, off, size,
  1583. value_regno, insn_idx);
  1584. else
  1585. err = check_stack_read(env, state, off, size,
  1586. value_regno);
  1587. } else if (reg_is_pkt_pointer(reg)) {
  1588. if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
  1589. verbose(env, "cannot write into packet\n");
  1590. return -EACCES;
  1591. }
  1592. if (t == BPF_WRITE && value_regno >= 0 &&
  1593. is_pointer_value(env, value_regno)) {
  1594. verbose(env, "R%d leaks addr into packet\n",
  1595. value_regno);
  1596. return -EACCES;
  1597. }
  1598. err = check_packet_access(env, regno, off, size, false);
  1599. if (!err && t == BPF_READ && value_regno >= 0)
  1600. mark_reg_unknown(env, regs, value_regno);
  1601. } else {
  1602. verbose(env, "R%d invalid mem access '%s'\n", regno,
  1603. reg_type_str[reg->type]);
  1604. return -EACCES;
  1605. }
  1606. if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
  1607. regs[value_regno].type == SCALAR_VALUE) {
  1608. /* b/h/w load zero-extends, mark upper bits as known 0 */
  1609. coerce_reg_to_size(&regs[value_regno], size);
  1610. }
  1611. return err;
  1612. }
  1613. static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
  1614. {
  1615. int err;
  1616. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  1617. insn->imm != 0) {
  1618. verbose(env, "BPF_XADD uses reserved fields\n");
  1619. return -EINVAL;
  1620. }
  1621. /* check src1 operand */
  1622. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  1623. if (err)
  1624. return err;
  1625. /* check src2 operand */
  1626. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  1627. if (err)
  1628. return err;
  1629. if (is_pointer_value(env, insn->src_reg)) {
  1630. verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
  1631. return -EACCES;
  1632. }
  1633. if (is_ctx_reg(env, insn->dst_reg) ||
  1634. is_pkt_reg(env, insn->dst_reg)) {
  1635. verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
  1636. insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
  1637. "context" : "packet");
  1638. return -EACCES;
  1639. }
  1640. /* check whether atomic_add can read the memory */
  1641. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  1642. BPF_SIZE(insn->code), BPF_READ, -1, true);
  1643. if (err)
  1644. return err;
  1645. /* check whether atomic_add can write into the same memory */
  1646. return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  1647. BPF_SIZE(insn->code), BPF_WRITE, -1, true);
  1648. }
  1649. /* when register 'regno' is passed into function that will read 'access_size'
  1650. * bytes from that pointer, make sure that it's within stack boundary
  1651. * and all elements of stack are initialized.
  1652. * Unlike most pointer bounds-checking functions, this one doesn't take an
  1653. * 'off' argument, so it has to add in reg->off itself.
  1654. */
  1655. static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
  1656. int access_size, bool zero_size_allowed,
  1657. struct bpf_call_arg_meta *meta)
  1658. {
  1659. struct bpf_reg_state *reg = cur_regs(env) + regno;
  1660. struct bpf_func_state *state = func(env, reg);
  1661. int off, i, slot, spi;
  1662. if (reg->type != PTR_TO_STACK) {
  1663. /* Allow zero-byte read from NULL, regardless of pointer type */
  1664. if (zero_size_allowed && access_size == 0 &&
  1665. register_is_null(reg))
  1666. return 0;
  1667. verbose(env, "R%d type=%s expected=%s\n", regno,
  1668. reg_type_str[reg->type],
  1669. reg_type_str[PTR_TO_STACK]);
  1670. return -EACCES;
  1671. }
  1672. /* Only allow fixed-offset stack reads */
  1673. if (!tnum_is_const(reg->var_off)) {
  1674. char tn_buf[48];
  1675. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  1676. verbose(env, "invalid variable stack read R%d var_off=%s\n",
  1677. regno, tn_buf);
  1678. return -EACCES;
  1679. }
  1680. off = reg->off + reg->var_off.value;
  1681. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  1682. access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
  1683. verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
  1684. regno, off, access_size);
  1685. return -EACCES;
  1686. }
  1687. if (meta && meta->raw_mode) {
  1688. meta->access_size = access_size;
  1689. meta->regno = regno;
  1690. return 0;
  1691. }
  1692. for (i = 0; i < access_size; i++) {
  1693. u8 *stype;
  1694. slot = -(off + i) - 1;
  1695. spi = slot / BPF_REG_SIZE;
  1696. if (state->allocated_stack <= slot)
  1697. goto err;
  1698. stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
  1699. if (*stype == STACK_MISC)
  1700. goto mark;
  1701. if (*stype == STACK_ZERO) {
  1702. /* helper can write anything into the stack */
  1703. *stype = STACK_MISC;
  1704. goto mark;
  1705. }
  1706. err:
  1707. verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
  1708. off, i, access_size);
  1709. return -EACCES;
  1710. mark:
  1711. /* reading any byte out of 8-byte 'spill_slot' will cause
  1712. * the whole slot to be marked as 'read'
  1713. */
  1714. mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
  1715. spi, state->frameno);
  1716. }
  1717. return update_stack_depth(env, state, off);
  1718. }
  1719. static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
  1720. int access_size, bool zero_size_allowed,
  1721. struct bpf_call_arg_meta *meta)
  1722. {
  1723. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  1724. switch (reg->type) {
  1725. case PTR_TO_PACKET:
  1726. case PTR_TO_PACKET_META:
  1727. return check_packet_access(env, regno, reg->off, access_size,
  1728. zero_size_allowed);
  1729. case PTR_TO_MAP_VALUE:
  1730. return check_map_access(env, regno, reg->off, access_size,
  1731. zero_size_allowed);
  1732. default: /* scalar_value|ptr_to_stack or invalid ptr */
  1733. return check_stack_boundary(env, regno, access_size,
  1734. zero_size_allowed, meta);
  1735. }
  1736. }
  1737. static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
  1738. {
  1739. return type == ARG_PTR_TO_MEM ||
  1740. type == ARG_PTR_TO_MEM_OR_NULL ||
  1741. type == ARG_PTR_TO_UNINIT_MEM;
  1742. }
  1743. static bool arg_type_is_mem_size(enum bpf_arg_type type)
  1744. {
  1745. return type == ARG_CONST_SIZE ||
  1746. type == ARG_CONST_SIZE_OR_ZERO;
  1747. }
  1748. static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
  1749. enum bpf_arg_type arg_type,
  1750. struct bpf_call_arg_meta *meta)
  1751. {
  1752. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  1753. enum bpf_reg_type expected_type, type = reg->type;
  1754. int err = 0;
  1755. if (arg_type == ARG_DONTCARE)
  1756. return 0;
  1757. err = check_reg_arg(env, regno, SRC_OP);
  1758. if (err)
  1759. return err;
  1760. if (arg_type == ARG_ANYTHING) {
  1761. if (is_pointer_value(env, regno)) {
  1762. verbose(env, "R%d leaks addr into helper function\n",
  1763. regno);
  1764. return -EACCES;
  1765. }
  1766. return 0;
  1767. }
  1768. if (type_is_pkt_pointer(type) &&
  1769. !may_access_direct_pkt_data(env, meta, BPF_READ)) {
  1770. verbose(env, "helper access to the packet is not allowed\n");
  1771. return -EACCES;
  1772. }
  1773. if (arg_type == ARG_PTR_TO_MAP_KEY ||
  1774. arg_type == ARG_PTR_TO_MAP_VALUE) {
  1775. expected_type = PTR_TO_STACK;
  1776. if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
  1777. type != expected_type)
  1778. goto err_type;
  1779. } else if (arg_type == ARG_CONST_SIZE ||
  1780. arg_type == ARG_CONST_SIZE_OR_ZERO) {
  1781. expected_type = SCALAR_VALUE;
  1782. if (type != expected_type)
  1783. goto err_type;
  1784. } else if (arg_type == ARG_CONST_MAP_PTR) {
  1785. expected_type = CONST_PTR_TO_MAP;
  1786. if (type != expected_type)
  1787. goto err_type;
  1788. } else if (arg_type == ARG_PTR_TO_CTX) {
  1789. expected_type = PTR_TO_CTX;
  1790. if (type != expected_type)
  1791. goto err_type;
  1792. err = check_ctx_reg(env, reg, regno);
  1793. if (err < 0)
  1794. return err;
  1795. } else if (arg_type_is_mem_ptr(arg_type)) {
  1796. expected_type = PTR_TO_STACK;
  1797. /* One exception here. In case function allows for NULL to be
  1798. * passed in as argument, it's a SCALAR_VALUE type. Final test
  1799. * happens during stack boundary checking.
  1800. */
  1801. if (register_is_null(reg) &&
  1802. arg_type == ARG_PTR_TO_MEM_OR_NULL)
  1803. /* final test in check_stack_boundary() */;
  1804. else if (!type_is_pkt_pointer(type) &&
  1805. type != PTR_TO_MAP_VALUE &&
  1806. type != expected_type)
  1807. goto err_type;
  1808. meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
  1809. } else {
  1810. verbose(env, "unsupported arg_type %d\n", arg_type);
  1811. return -EFAULT;
  1812. }
  1813. if (arg_type == ARG_CONST_MAP_PTR) {
  1814. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  1815. meta->map_ptr = reg->map_ptr;
  1816. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  1817. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  1818. * check that [key, key + map->key_size) are within
  1819. * stack limits and initialized
  1820. */
  1821. if (!meta->map_ptr) {
  1822. /* in function declaration map_ptr must come before
  1823. * map_key, so that it's verified and known before
  1824. * we have to check map_key here. Otherwise it means
  1825. * that kernel subsystem misconfigured verifier
  1826. */
  1827. verbose(env, "invalid map_ptr to access map->key\n");
  1828. return -EACCES;
  1829. }
  1830. err = check_helper_mem_access(env, regno,
  1831. meta->map_ptr->key_size, false,
  1832. NULL);
  1833. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  1834. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  1835. * check [value, value + map->value_size) validity
  1836. */
  1837. if (!meta->map_ptr) {
  1838. /* kernel subsystem misconfigured verifier */
  1839. verbose(env, "invalid map_ptr to access map->value\n");
  1840. return -EACCES;
  1841. }
  1842. err = check_helper_mem_access(env, regno,
  1843. meta->map_ptr->value_size, false,
  1844. NULL);
  1845. } else if (arg_type_is_mem_size(arg_type)) {
  1846. bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
  1847. /* remember the mem_size which may be used later
  1848. * to refine return values.
  1849. */
  1850. meta->msize_smax_value = reg->smax_value;
  1851. meta->msize_umax_value = reg->umax_value;
  1852. /* The register is SCALAR_VALUE; the access check
  1853. * happens using its boundaries.
  1854. */
  1855. if (!tnum_is_const(reg->var_off))
  1856. /* For unprivileged variable accesses, disable raw
  1857. * mode so that the program is required to
  1858. * initialize all the memory that the helper could
  1859. * just partially fill up.
  1860. */
  1861. meta = NULL;
  1862. if (reg->smin_value < 0) {
  1863. verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
  1864. regno);
  1865. return -EACCES;
  1866. }
  1867. if (reg->umin_value == 0) {
  1868. err = check_helper_mem_access(env, regno - 1, 0,
  1869. zero_size_allowed,
  1870. meta);
  1871. if (err)
  1872. return err;
  1873. }
  1874. if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
  1875. verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
  1876. regno);
  1877. return -EACCES;
  1878. }
  1879. err = check_helper_mem_access(env, regno - 1,
  1880. reg->umax_value,
  1881. zero_size_allowed, meta);
  1882. }
  1883. return err;
  1884. err_type:
  1885. verbose(env, "R%d type=%s expected=%s\n", regno,
  1886. reg_type_str[type], reg_type_str[expected_type]);
  1887. return -EACCES;
  1888. }
  1889. static int check_map_func_compatibility(struct bpf_verifier_env *env,
  1890. struct bpf_map *map, int func_id)
  1891. {
  1892. if (!map)
  1893. return 0;
  1894. /* We need a two way check, first is from map perspective ... */
  1895. switch (map->map_type) {
  1896. case BPF_MAP_TYPE_PROG_ARRAY:
  1897. if (func_id != BPF_FUNC_tail_call)
  1898. goto error;
  1899. break;
  1900. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  1901. if (func_id != BPF_FUNC_perf_event_read &&
  1902. func_id != BPF_FUNC_perf_event_output &&
  1903. func_id != BPF_FUNC_perf_event_read_value)
  1904. goto error;
  1905. break;
  1906. case BPF_MAP_TYPE_STACK_TRACE:
  1907. if (func_id != BPF_FUNC_get_stackid)
  1908. goto error;
  1909. break;
  1910. case BPF_MAP_TYPE_CGROUP_ARRAY:
  1911. if (func_id != BPF_FUNC_skb_under_cgroup &&
  1912. func_id != BPF_FUNC_current_task_under_cgroup)
  1913. goto error;
  1914. break;
  1915. /* devmap returns a pointer to a live net_device ifindex that we cannot
  1916. * allow to be modified from bpf side. So do not allow lookup elements
  1917. * for now.
  1918. */
  1919. case BPF_MAP_TYPE_DEVMAP:
  1920. if (func_id != BPF_FUNC_redirect_map)
  1921. goto error;
  1922. break;
  1923. /* Restrict bpf side of cpumap and xskmap, open when use-cases
  1924. * appear.
  1925. */
  1926. case BPF_MAP_TYPE_CPUMAP:
  1927. case BPF_MAP_TYPE_XSKMAP:
  1928. if (func_id != BPF_FUNC_redirect_map)
  1929. goto error;
  1930. break;
  1931. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  1932. case BPF_MAP_TYPE_HASH_OF_MAPS:
  1933. if (func_id != BPF_FUNC_map_lookup_elem)
  1934. goto error;
  1935. break;
  1936. case BPF_MAP_TYPE_SOCKMAP:
  1937. if (func_id != BPF_FUNC_sk_redirect_map &&
  1938. func_id != BPF_FUNC_sock_map_update &&
  1939. func_id != BPF_FUNC_map_delete_elem &&
  1940. func_id != BPF_FUNC_msg_redirect_map)
  1941. goto error;
  1942. break;
  1943. case BPF_MAP_TYPE_SOCKHASH:
  1944. if (func_id != BPF_FUNC_sk_redirect_hash &&
  1945. func_id != BPF_FUNC_sock_hash_update &&
  1946. func_id != BPF_FUNC_map_delete_elem &&
  1947. func_id != BPF_FUNC_msg_redirect_hash)
  1948. goto error;
  1949. break;
  1950. default:
  1951. break;
  1952. }
  1953. /* ... and second from the function itself. */
  1954. switch (func_id) {
  1955. case BPF_FUNC_tail_call:
  1956. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  1957. goto error;
  1958. if (env->subprog_cnt > 1) {
  1959. verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
  1960. return -EINVAL;
  1961. }
  1962. break;
  1963. case BPF_FUNC_perf_event_read:
  1964. case BPF_FUNC_perf_event_output:
  1965. case BPF_FUNC_perf_event_read_value:
  1966. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  1967. goto error;
  1968. break;
  1969. case BPF_FUNC_get_stackid:
  1970. if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
  1971. goto error;
  1972. break;
  1973. case BPF_FUNC_current_task_under_cgroup:
  1974. case BPF_FUNC_skb_under_cgroup:
  1975. if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
  1976. goto error;
  1977. break;
  1978. case BPF_FUNC_redirect_map:
  1979. if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
  1980. map->map_type != BPF_MAP_TYPE_CPUMAP &&
  1981. map->map_type != BPF_MAP_TYPE_XSKMAP)
  1982. goto error;
  1983. break;
  1984. case BPF_FUNC_sk_redirect_map:
  1985. case BPF_FUNC_msg_redirect_map:
  1986. case BPF_FUNC_sock_map_update:
  1987. if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
  1988. goto error;
  1989. break;
  1990. case BPF_FUNC_sk_redirect_hash:
  1991. case BPF_FUNC_msg_redirect_hash:
  1992. case BPF_FUNC_sock_hash_update:
  1993. if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
  1994. goto error;
  1995. break;
  1996. default:
  1997. break;
  1998. }
  1999. return 0;
  2000. error:
  2001. verbose(env, "cannot pass map_type %d into func %s#%d\n",
  2002. map->map_type, func_id_name(func_id), func_id);
  2003. return -EINVAL;
  2004. }
  2005. static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
  2006. {
  2007. int count = 0;
  2008. if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
  2009. count++;
  2010. if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
  2011. count++;
  2012. if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
  2013. count++;
  2014. if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
  2015. count++;
  2016. if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
  2017. count++;
  2018. /* We only support one arg being in raw mode at the moment,
  2019. * which is sufficient for the helper functions we have
  2020. * right now.
  2021. */
  2022. return count <= 1;
  2023. }
  2024. static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
  2025. enum bpf_arg_type arg_next)
  2026. {
  2027. return (arg_type_is_mem_ptr(arg_curr) &&
  2028. !arg_type_is_mem_size(arg_next)) ||
  2029. (!arg_type_is_mem_ptr(arg_curr) &&
  2030. arg_type_is_mem_size(arg_next));
  2031. }
  2032. static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
  2033. {
  2034. /* bpf_xxx(..., buf, len) call will access 'len'
  2035. * bytes from memory 'buf'. Both arg types need
  2036. * to be paired, so make sure there's no buggy
  2037. * helper function specification.
  2038. */
  2039. if (arg_type_is_mem_size(fn->arg1_type) ||
  2040. arg_type_is_mem_ptr(fn->arg5_type) ||
  2041. check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
  2042. check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
  2043. check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
  2044. check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
  2045. return false;
  2046. return true;
  2047. }
  2048. static int check_func_proto(const struct bpf_func_proto *fn)
  2049. {
  2050. return check_raw_mode_ok(fn) &&
  2051. check_arg_pair_ok(fn) ? 0 : -EINVAL;
  2052. }
  2053. /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
  2054. * are now invalid, so turn them into unknown SCALAR_VALUE.
  2055. */
  2056. static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
  2057. struct bpf_func_state *state)
  2058. {
  2059. struct bpf_reg_state *regs = state->regs, *reg;
  2060. int i;
  2061. for (i = 0; i < MAX_BPF_REG; i++)
  2062. if (reg_is_pkt_pointer_any(&regs[i]))
  2063. mark_reg_unknown(env, regs, i);
  2064. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  2065. if (state->stack[i].slot_type[0] != STACK_SPILL)
  2066. continue;
  2067. reg = &state->stack[i].spilled_ptr;
  2068. if (reg_is_pkt_pointer_any(reg))
  2069. __mark_reg_unknown(reg);
  2070. }
  2071. }
  2072. static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
  2073. {
  2074. struct bpf_verifier_state *vstate = env->cur_state;
  2075. int i;
  2076. for (i = 0; i <= vstate->curframe; i++)
  2077. __clear_all_pkt_pointers(env, vstate->frame[i]);
  2078. }
  2079. static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  2080. int *insn_idx)
  2081. {
  2082. struct bpf_verifier_state *state = env->cur_state;
  2083. struct bpf_func_state *caller, *callee;
  2084. int i, subprog, target_insn;
  2085. if (state->curframe + 1 >= MAX_CALL_FRAMES) {
  2086. verbose(env, "the call stack of %d frames is too deep\n",
  2087. state->curframe + 2);
  2088. return -E2BIG;
  2089. }
  2090. target_insn = *insn_idx + insn->imm;
  2091. subprog = find_subprog(env, target_insn + 1);
  2092. if (subprog < 0) {
  2093. verbose(env, "verifier bug. No program starts at insn %d\n",
  2094. target_insn + 1);
  2095. return -EFAULT;
  2096. }
  2097. caller = state->frame[state->curframe];
  2098. if (state->frame[state->curframe + 1]) {
  2099. verbose(env, "verifier bug. Frame %d already allocated\n",
  2100. state->curframe + 1);
  2101. return -EFAULT;
  2102. }
  2103. callee = kzalloc(sizeof(*callee), GFP_KERNEL);
  2104. if (!callee)
  2105. return -ENOMEM;
  2106. state->frame[state->curframe + 1] = callee;
  2107. /* callee cannot access r0, r6 - r9 for reading and has to write
  2108. * into its own stack before reading from it.
  2109. * callee can read/write into caller's stack
  2110. */
  2111. init_func_state(env, callee,
  2112. /* remember the callsite, it will be used by bpf_exit */
  2113. *insn_idx /* callsite */,
  2114. state->curframe + 1 /* frameno within this callchain */,
  2115. subprog /* subprog number within this prog */);
  2116. /* copy r1 - r5 args that callee can access */
  2117. for (i = BPF_REG_1; i <= BPF_REG_5; i++)
  2118. callee->regs[i] = caller->regs[i];
  2119. /* after the call regsiters r0 - r5 were scratched */
  2120. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  2121. mark_reg_not_init(env, caller->regs, caller_saved[i]);
  2122. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  2123. }
  2124. /* only increment it after check_reg_arg() finished */
  2125. state->curframe++;
  2126. /* and go analyze first insn of the callee */
  2127. *insn_idx = target_insn;
  2128. if (env->log.level) {
  2129. verbose(env, "caller:\n");
  2130. print_verifier_state(env, caller);
  2131. verbose(env, "callee:\n");
  2132. print_verifier_state(env, callee);
  2133. }
  2134. return 0;
  2135. }
  2136. static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
  2137. {
  2138. struct bpf_verifier_state *state = env->cur_state;
  2139. struct bpf_func_state *caller, *callee;
  2140. struct bpf_reg_state *r0;
  2141. callee = state->frame[state->curframe];
  2142. r0 = &callee->regs[BPF_REG_0];
  2143. if (r0->type == PTR_TO_STACK) {
  2144. /* technically it's ok to return caller's stack pointer
  2145. * (or caller's caller's pointer) back to the caller,
  2146. * since these pointers are valid. Only current stack
  2147. * pointer will be invalid as soon as function exits,
  2148. * but let's be conservative
  2149. */
  2150. verbose(env, "cannot return stack pointer to the caller\n");
  2151. return -EINVAL;
  2152. }
  2153. state->curframe--;
  2154. caller = state->frame[state->curframe];
  2155. /* return to the caller whatever r0 had in the callee */
  2156. caller->regs[BPF_REG_0] = *r0;
  2157. *insn_idx = callee->callsite + 1;
  2158. if (env->log.level) {
  2159. verbose(env, "returning from callee:\n");
  2160. print_verifier_state(env, callee);
  2161. verbose(env, "to caller at %d:\n", *insn_idx);
  2162. print_verifier_state(env, caller);
  2163. }
  2164. /* clear everything in the callee */
  2165. free_func_state(callee);
  2166. state->frame[state->curframe + 1] = NULL;
  2167. return 0;
  2168. }
  2169. static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
  2170. int func_id,
  2171. struct bpf_call_arg_meta *meta)
  2172. {
  2173. struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
  2174. if (ret_type != RET_INTEGER ||
  2175. (func_id != BPF_FUNC_get_stack &&
  2176. func_id != BPF_FUNC_probe_read_str))
  2177. return;
  2178. ret_reg->smax_value = meta->msize_smax_value;
  2179. ret_reg->umax_value = meta->msize_umax_value;
  2180. __reg_deduce_bounds(ret_reg);
  2181. __reg_bound_offset(ret_reg);
  2182. }
  2183. static int
  2184. record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
  2185. int func_id, int insn_idx)
  2186. {
  2187. struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
  2188. if (func_id != BPF_FUNC_tail_call &&
  2189. func_id != BPF_FUNC_map_lookup_elem &&
  2190. func_id != BPF_FUNC_map_update_elem &&
  2191. func_id != BPF_FUNC_map_delete_elem)
  2192. return 0;
  2193. if (meta->map_ptr == NULL) {
  2194. verbose(env, "kernel subsystem misconfigured verifier\n");
  2195. return -EINVAL;
  2196. }
  2197. if (!BPF_MAP_PTR(aux->map_state))
  2198. bpf_map_ptr_store(aux, meta->map_ptr,
  2199. meta->map_ptr->unpriv_array);
  2200. else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
  2201. bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
  2202. meta->map_ptr->unpriv_array);
  2203. return 0;
  2204. }
  2205. static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
  2206. {
  2207. const struct bpf_func_proto *fn = NULL;
  2208. struct bpf_reg_state *regs;
  2209. struct bpf_call_arg_meta meta;
  2210. bool changes_data;
  2211. int i, err;
  2212. /* find function prototype */
  2213. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  2214. verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
  2215. func_id);
  2216. return -EINVAL;
  2217. }
  2218. if (env->ops->get_func_proto)
  2219. fn = env->ops->get_func_proto(func_id, env->prog);
  2220. if (!fn) {
  2221. verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
  2222. func_id);
  2223. return -EINVAL;
  2224. }
  2225. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  2226. if (!env->prog->gpl_compatible && fn->gpl_only) {
  2227. verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
  2228. return -EINVAL;
  2229. }
  2230. /* With LD_ABS/IND some JITs save/restore skb from r1. */
  2231. changes_data = bpf_helper_changes_pkt_data(fn->func);
  2232. if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
  2233. verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
  2234. func_id_name(func_id), func_id);
  2235. return -EINVAL;
  2236. }
  2237. memset(&meta, 0, sizeof(meta));
  2238. meta.pkt_access = fn->pkt_access;
  2239. err = check_func_proto(fn);
  2240. if (err) {
  2241. verbose(env, "kernel subsystem misconfigured func %s#%d\n",
  2242. func_id_name(func_id), func_id);
  2243. return err;
  2244. }
  2245. /* check args */
  2246. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
  2247. if (err)
  2248. return err;
  2249. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
  2250. if (err)
  2251. return err;
  2252. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
  2253. if (err)
  2254. return err;
  2255. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
  2256. if (err)
  2257. return err;
  2258. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
  2259. if (err)
  2260. return err;
  2261. err = record_func_map(env, &meta, func_id, insn_idx);
  2262. if (err)
  2263. return err;
  2264. /* Mark slots with STACK_MISC in case of raw mode, stack offset
  2265. * is inferred from register state.
  2266. */
  2267. for (i = 0; i < meta.access_size; i++) {
  2268. err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
  2269. BPF_WRITE, -1, false);
  2270. if (err)
  2271. return err;
  2272. }
  2273. regs = cur_regs(env);
  2274. /* reset caller saved regs */
  2275. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  2276. mark_reg_not_init(env, regs, caller_saved[i]);
  2277. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  2278. }
  2279. /* update return register (already marked as written above) */
  2280. if (fn->ret_type == RET_INTEGER) {
  2281. /* sets type to SCALAR_VALUE */
  2282. mark_reg_unknown(env, regs, BPF_REG_0);
  2283. } else if (fn->ret_type == RET_VOID) {
  2284. regs[BPF_REG_0].type = NOT_INIT;
  2285. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  2286. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  2287. /* There is no offset yet applied, variable or fixed */
  2288. mark_reg_known_zero(env, regs, BPF_REG_0);
  2289. regs[BPF_REG_0].off = 0;
  2290. /* remember map_ptr, so that check_map_access()
  2291. * can check 'value_size' boundary of memory access
  2292. * to map element returned from bpf_map_lookup_elem()
  2293. */
  2294. if (meta.map_ptr == NULL) {
  2295. verbose(env,
  2296. "kernel subsystem misconfigured verifier\n");
  2297. return -EINVAL;
  2298. }
  2299. regs[BPF_REG_0].map_ptr = meta.map_ptr;
  2300. regs[BPF_REG_0].id = ++env->id_gen;
  2301. } else {
  2302. verbose(env, "unknown return type %d of func %s#%d\n",
  2303. fn->ret_type, func_id_name(func_id), func_id);
  2304. return -EINVAL;
  2305. }
  2306. do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
  2307. err = check_map_func_compatibility(env, meta.map_ptr, func_id);
  2308. if (err)
  2309. return err;
  2310. if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
  2311. const char *err_str;
  2312. #ifdef CONFIG_PERF_EVENTS
  2313. err = get_callchain_buffers(sysctl_perf_event_max_stack);
  2314. err_str = "cannot get callchain buffer for func %s#%d\n";
  2315. #else
  2316. err = -ENOTSUPP;
  2317. err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
  2318. #endif
  2319. if (err) {
  2320. verbose(env, err_str, func_id_name(func_id), func_id);
  2321. return err;
  2322. }
  2323. env->prog->has_callchain_buf = true;
  2324. }
  2325. if (changes_data)
  2326. clear_all_pkt_pointers(env);
  2327. return 0;
  2328. }
  2329. static bool signed_add_overflows(s64 a, s64 b)
  2330. {
  2331. /* Do the add in u64, where overflow is well-defined */
  2332. s64 res = (s64)((u64)a + (u64)b);
  2333. if (b < 0)
  2334. return res > a;
  2335. return res < a;
  2336. }
  2337. static bool signed_sub_overflows(s64 a, s64 b)
  2338. {
  2339. /* Do the sub in u64, where overflow is well-defined */
  2340. s64 res = (s64)((u64)a - (u64)b);
  2341. if (b < 0)
  2342. return res < a;
  2343. return res > a;
  2344. }
  2345. static bool check_reg_sane_offset(struct bpf_verifier_env *env,
  2346. const struct bpf_reg_state *reg,
  2347. enum bpf_reg_type type)
  2348. {
  2349. bool known = tnum_is_const(reg->var_off);
  2350. s64 val = reg->var_off.value;
  2351. s64 smin = reg->smin_value;
  2352. if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
  2353. verbose(env, "math between %s pointer and %lld is not allowed\n",
  2354. reg_type_str[type], val);
  2355. return false;
  2356. }
  2357. if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
  2358. verbose(env, "%s pointer offset %d is not allowed\n",
  2359. reg_type_str[type], reg->off);
  2360. return false;
  2361. }
  2362. if (smin == S64_MIN) {
  2363. verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
  2364. reg_type_str[type]);
  2365. return false;
  2366. }
  2367. if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
  2368. verbose(env, "value %lld makes %s pointer be out of bounds\n",
  2369. smin, reg_type_str[type]);
  2370. return false;
  2371. }
  2372. return true;
  2373. }
  2374. /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
  2375. * Caller should also handle BPF_MOV case separately.
  2376. * If we return -EACCES, caller may want to try again treating pointer as a
  2377. * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
  2378. */
  2379. static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
  2380. struct bpf_insn *insn,
  2381. const struct bpf_reg_state *ptr_reg,
  2382. const struct bpf_reg_state *off_reg)
  2383. {
  2384. struct bpf_verifier_state *vstate = env->cur_state;
  2385. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2386. struct bpf_reg_state *regs = state->regs, *dst_reg;
  2387. bool known = tnum_is_const(off_reg->var_off);
  2388. s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
  2389. smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
  2390. u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
  2391. umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
  2392. u8 opcode = BPF_OP(insn->code);
  2393. u32 dst = insn->dst_reg;
  2394. dst_reg = &regs[dst];
  2395. if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
  2396. smin_val > smax_val || umin_val > umax_val) {
  2397. /* Taint dst register if offset had invalid bounds derived from
  2398. * e.g. dead branches.
  2399. */
  2400. __mark_reg_unknown(dst_reg);
  2401. return 0;
  2402. }
  2403. if (BPF_CLASS(insn->code) != BPF_ALU64) {
  2404. /* 32-bit ALU ops on pointers produce (meaningless) scalars */
  2405. verbose(env,
  2406. "R%d 32-bit pointer arithmetic prohibited\n",
  2407. dst);
  2408. return -EACCES;
  2409. }
  2410. if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  2411. verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
  2412. dst);
  2413. return -EACCES;
  2414. }
  2415. if (ptr_reg->type == CONST_PTR_TO_MAP) {
  2416. verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
  2417. dst);
  2418. return -EACCES;
  2419. }
  2420. if (ptr_reg->type == PTR_TO_PACKET_END) {
  2421. verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
  2422. dst);
  2423. return -EACCES;
  2424. }
  2425. /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
  2426. * The id may be overwritten later if we create a new variable offset.
  2427. */
  2428. dst_reg->type = ptr_reg->type;
  2429. dst_reg->id = ptr_reg->id;
  2430. if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
  2431. !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
  2432. return -EINVAL;
  2433. switch (opcode) {
  2434. case BPF_ADD:
  2435. /* We can take a fixed offset as long as it doesn't overflow
  2436. * the s32 'off' field
  2437. */
  2438. if (known && (ptr_reg->off + smin_val ==
  2439. (s64)(s32)(ptr_reg->off + smin_val))) {
  2440. /* pointer += K. Accumulate it into fixed offset */
  2441. dst_reg->smin_value = smin_ptr;
  2442. dst_reg->smax_value = smax_ptr;
  2443. dst_reg->umin_value = umin_ptr;
  2444. dst_reg->umax_value = umax_ptr;
  2445. dst_reg->var_off = ptr_reg->var_off;
  2446. dst_reg->off = ptr_reg->off + smin_val;
  2447. dst_reg->range = ptr_reg->range;
  2448. break;
  2449. }
  2450. /* A new variable offset is created. Note that off_reg->off
  2451. * == 0, since it's a scalar.
  2452. * dst_reg gets the pointer type and since some positive
  2453. * integer value was added to the pointer, give it a new 'id'
  2454. * if it's a PTR_TO_PACKET.
  2455. * this creates a new 'base' pointer, off_reg (variable) gets
  2456. * added into the variable offset, and we copy the fixed offset
  2457. * from ptr_reg.
  2458. */
  2459. if (signed_add_overflows(smin_ptr, smin_val) ||
  2460. signed_add_overflows(smax_ptr, smax_val)) {
  2461. dst_reg->smin_value = S64_MIN;
  2462. dst_reg->smax_value = S64_MAX;
  2463. } else {
  2464. dst_reg->smin_value = smin_ptr + smin_val;
  2465. dst_reg->smax_value = smax_ptr + smax_val;
  2466. }
  2467. if (umin_ptr + umin_val < umin_ptr ||
  2468. umax_ptr + umax_val < umax_ptr) {
  2469. dst_reg->umin_value = 0;
  2470. dst_reg->umax_value = U64_MAX;
  2471. } else {
  2472. dst_reg->umin_value = umin_ptr + umin_val;
  2473. dst_reg->umax_value = umax_ptr + umax_val;
  2474. }
  2475. dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
  2476. dst_reg->off = ptr_reg->off;
  2477. if (reg_is_pkt_pointer(ptr_reg)) {
  2478. dst_reg->id = ++env->id_gen;
  2479. /* something was added to pkt_ptr, set range to zero */
  2480. dst_reg->range = 0;
  2481. }
  2482. break;
  2483. case BPF_SUB:
  2484. if (dst_reg == off_reg) {
  2485. /* scalar -= pointer. Creates an unknown scalar */
  2486. verbose(env, "R%d tried to subtract pointer from scalar\n",
  2487. dst);
  2488. return -EACCES;
  2489. }
  2490. /* We don't allow subtraction from FP, because (according to
  2491. * test_verifier.c test "invalid fp arithmetic", JITs might not
  2492. * be able to deal with it.
  2493. */
  2494. if (ptr_reg->type == PTR_TO_STACK) {
  2495. verbose(env, "R%d subtraction from stack pointer prohibited\n",
  2496. dst);
  2497. return -EACCES;
  2498. }
  2499. if (known && (ptr_reg->off - smin_val ==
  2500. (s64)(s32)(ptr_reg->off - smin_val))) {
  2501. /* pointer -= K. Subtract it from fixed offset */
  2502. dst_reg->smin_value = smin_ptr;
  2503. dst_reg->smax_value = smax_ptr;
  2504. dst_reg->umin_value = umin_ptr;
  2505. dst_reg->umax_value = umax_ptr;
  2506. dst_reg->var_off = ptr_reg->var_off;
  2507. dst_reg->id = ptr_reg->id;
  2508. dst_reg->off = ptr_reg->off - smin_val;
  2509. dst_reg->range = ptr_reg->range;
  2510. break;
  2511. }
  2512. /* A new variable offset is created. If the subtrahend is known
  2513. * nonnegative, then any reg->range we had before is still good.
  2514. */
  2515. if (signed_sub_overflows(smin_ptr, smax_val) ||
  2516. signed_sub_overflows(smax_ptr, smin_val)) {
  2517. /* Overflow possible, we know nothing */
  2518. dst_reg->smin_value = S64_MIN;
  2519. dst_reg->smax_value = S64_MAX;
  2520. } else {
  2521. dst_reg->smin_value = smin_ptr - smax_val;
  2522. dst_reg->smax_value = smax_ptr - smin_val;
  2523. }
  2524. if (umin_ptr < umax_val) {
  2525. /* Overflow possible, we know nothing */
  2526. dst_reg->umin_value = 0;
  2527. dst_reg->umax_value = U64_MAX;
  2528. } else {
  2529. /* Cannot overflow (as long as bounds are consistent) */
  2530. dst_reg->umin_value = umin_ptr - umax_val;
  2531. dst_reg->umax_value = umax_ptr - umin_val;
  2532. }
  2533. dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
  2534. dst_reg->off = ptr_reg->off;
  2535. if (reg_is_pkt_pointer(ptr_reg)) {
  2536. dst_reg->id = ++env->id_gen;
  2537. /* something was added to pkt_ptr, set range to zero */
  2538. if (smin_val < 0)
  2539. dst_reg->range = 0;
  2540. }
  2541. break;
  2542. case BPF_AND:
  2543. case BPF_OR:
  2544. case BPF_XOR:
  2545. /* bitwise ops on pointers are troublesome, prohibit. */
  2546. verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
  2547. dst, bpf_alu_string[opcode >> 4]);
  2548. return -EACCES;
  2549. default:
  2550. /* other operators (e.g. MUL,LSH) produce non-pointer results */
  2551. verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
  2552. dst, bpf_alu_string[opcode >> 4]);
  2553. return -EACCES;
  2554. }
  2555. if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
  2556. return -EINVAL;
  2557. __update_reg_bounds(dst_reg);
  2558. __reg_deduce_bounds(dst_reg);
  2559. __reg_bound_offset(dst_reg);
  2560. return 0;
  2561. }
  2562. /* WARNING: This function does calculations on 64-bit values, but the actual
  2563. * execution may occur on 32-bit values. Therefore, things like bitshifts
  2564. * need extra checks in the 32-bit case.
  2565. */
  2566. static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
  2567. struct bpf_insn *insn,
  2568. struct bpf_reg_state *dst_reg,
  2569. struct bpf_reg_state src_reg)
  2570. {
  2571. struct bpf_reg_state *regs = cur_regs(env);
  2572. u8 opcode = BPF_OP(insn->code);
  2573. bool src_known, dst_known;
  2574. s64 smin_val, smax_val;
  2575. u64 umin_val, umax_val;
  2576. u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
  2577. smin_val = src_reg.smin_value;
  2578. smax_val = src_reg.smax_value;
  2579. umin_val = src_reg.umin_value;
  2580. umax_val = src_reg.umax_value;
  2581. src_known = tnum_is_const(src_reg.var_off);
  2582. dst_known = tnum_is_const(dst_reg->var_off);
  2583. if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
  2584. smin_val > smax_val || umin_val > umax_val) {
  2585. /* Taint dst register if offset had invalid bounds derived from
  2586. * e.g. dead branches.
  2587. */
  2588. __mark_reg_unknown(dst_reg);
  2589. return 0;
  2590. }
  2591. if (!src_known &&
  2592. opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
  2593. __mark_reg_unknown(dst_reg);
  2594. return 0;
  2595. }
  2596. switch (opcode) {
  2597. case BPF_ADD:
  2598. if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
  2599. signed_add_overflows(dst_reg->smax_value, smax_val)) {
  2600. dst_reg->smin_value = S64_MIN;
  2601. dst_reg->smax_value = S64_MAX;
  2602. } else {
  2603. dst_reg->smin_value += smin_val;
  2604. dst_reg->smax_value += smax_val;
  2605. }
  2606. if (dst_reg->umin_value + umin_val < umin_val ||
  2607. dst_reg->umax_value + umax_val < umax_val) {
  2608. dst_reg->umin_value = 0;
  2609. dst_reg->umax_value = U64_MAX;
  2610. } else {
  2611. dst_reg->umin_value += umin_val;
  2612. dst_reg->umax_value += umax_val;
  2613. }
  2614. dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
  2615. break;
  2616. case BPF_SUB:
  2617. if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
  2618. signed_sub_overflows(dst_reg->smax_value, smin_val)) {
  2619. /* Overflow possible, we know nothing */
  2620. dst_reg->smin_value = S64_MIN;
  2621. dst_reg->smax_value = S64_MAX;
  2622. } else {
  2623. dst_reg->smin_value -= smax_val;
  2624. dst_reg->smax_value -= smin_val;
  2625. }
  2626. if (dst_reg->umin_value < umax_val) {
  2627. /* Overflow possible, we know nothing */
  2628. dst_reg->umin_value = 0;
  2629. dst_reg->umax_value = U64_MAX;
  2630. } else {
  2631. /* Cannot overflow (as long as bounds are consistent) */
  2632. dst_reg->umin_value -= umax_val;
  2633. dst_reg->umax_value -= umin_val;
  2634. }
  2635. dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
  2636. break;
  2637. case BPF_MUL:
  2638. dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
  2639. if (smin_val < 0 || dst_reg->smin_value < 0) {
  2640. /* Ain't nobody got time to multiply that sign */
  2641. __mark_reg_unbounded(dst_reg);
  2642. __update_reg_bounds(dst_reg);
  2643. break;
  2644. }
  2645. /* Both values are positive, so we can work with unsigned and
  2646. * copy the result to signed (unless it exceeds S64_MAX).
  2647. */
  2648. if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
  2649. /* Potential overflow, we know nothing */
  2650. __mark_reg_unbounded(dst_reg);
  2651. /* (except what we can learn from the var_off) */
  2652. __update_reg_bounds(dst_reg);
  2653. break;
  2654. }
  2655. dst_reg->umin_value *= umin_val;
  2656. dst_reg->umax_value *= umax_val;
  2657. if (dst_reg->umax_value > S64_MAX) {
  2658. /* Overflow possible, we know nothing */
  2659. dst_reg->smin_value = S64_MIN;
  2660. dst_reg->smax_value = S64_MAX;
  2661. } else {
  2662. dst_reg->smin_value = dst_reg->umin_value;
  2663. dst_reg->smax_value = dst_reg->umax_value;
  2664. }
  2665. break;
  2666. case BPF_AND:
  2667. if (src_known && dst_known) {
  2668. __mark_reg_known(dst_reg, dst_reg->var_off.value &
  2669. src_reg.var_off.value);
  2670. break;
  2671. }
  2672. /* We get our minimum from the var_off, since that's inherently
  2673. * bitwise. Our maximum is the minimum of the operands' maxima.
  2674. */
  2675. dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
  2676. dst_reg->umin_value = dst_reg->var_off.value;
  2677. dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
  2678. if (dst_reg->smin_value < 0 || smin_val < 0) {
  2679. /* Lose signed bounds when ANDing negative numbers,
  2680. * ain't nobody got time for that.
  2681. */
  2682. dst_reg->smin_value = S64_MIN;
  2683. dst_reg->smax_value = S64_MAX;
  2684. } else {
  2685. /* ANDing two positives gives a positive, so safe to
  2686. * cast result into s64.
  2687. */
  2688. dst_reg->smin_value = dst_reg->umin_value;
  2689. dst_reg->smax_value = dst_reg->umax_value;
  2690. }
  2691. /* We may learn something more from the var_off */
  2692. __update_reg_bounds(dst_reg);
  2693. break;
  2694. case BPF_OR:
  2695. if (src_known && dst_known) {
  2696. __mark_reg_known(dst_reg, dst_reg->var_off.value |
  2697. src_reg.var_off.value);
  2698. break;
  2699. }
  2700. /* We get our maximum from the var_off, and our minimum is the
  2701. * maximum of the operands' minima
  2702. */
  2703. dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
  2704. dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
  2705. dst_reg->umax_value = dst_reg->var_off.value |
  2706. dst_reg->var_off.mask;
  2707. if (dst_reg->smin_value < 0 || smin_val < 0) {
  2708. /* Lose signed bounds when ORing negative numbers,
  2709. * ain't nobody got time for that.
  2710. */
  2711. dst_reg->smin_value = S64_MIN;
  2712. dst_reg->smax_value = S64_MAX;
  2713. } else {
  2714. /* ORing two positives gives a positive, so safe to
  2715. * cast result into s64.
  2716. */
  2717. dst_reg->smin_value = dst_reg->umin_value;
  2718. dst_reg->smax_value = dst_reg->umax_value;
  2719. }
  2720. /* We may learn something more from the var_off */
  2721. __update_reg_bounds(dst_reg);
  2722. break;
  2723. case BPF_LSH:
  2724. if (umax_val >= insn_bitness) {
  2725. /* Shifts greater than 31 or 63 are undefined.
  2726. * This includes shifts by a negative number.
  2727. */
  2728. mark_reg_unknown(env, regs, insn->dst_reg);
  2729. break;
  2730. }
  2731. /* We lose all sign bit information (except what we can pick
  2732. * up from var_off)
  2733. */
  2734. dst_reg->smin_value = S64_MIN;
  2735. dst_reg->smax_value = S64_MAX;
  2736. /* If we might shift our top bit out, then we know nothing */
  2737. if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
  2738. dst_reg->umin_value = 0;
  2739. dst_reg->umax_value = U64_MAX;
  2740. } else {
  2741. dst_reg->umin_value <<= umin_val;
  2742. dst_reg->umax_value <<= umax_val;
  2743. }
  2744. dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
  2745. /* We may learn something more from the var_off */
  2746. __update_reg_bounds(dst_reg);
  2747. break;
  2748. case BPF_RSH:
  2749. if (umax_val >= insn_bitness) {
  2750. /* Shifts greater than 31 or 63 are undefined.
  2751. * This includes shifts by a negative number.
  2752. */
  2753. mark_reg_unknown(env, regs, insn->dst_reg);
  2754. break;
  2755. }
  2756. /* BPF_RSH is an unsigned shift. If the value in dst_reg might
  2757. * be negative, then either:
  2758. * 1) src_reg might be zero, so the sign bit of the result is
  2759. * unknown, so we lose our signed bounds
  2760. * 2) it's known negative, thus the unsigned bounds capture the
  2761. * signed bounds
  2762. * 3) the signed bounds cross zero, so they tell us nothing
  2763. * about the result
  2764. * If the value in dst_reg is known nonnegative, then again the
  2765. * unsigned bounts capture the signed bounds.
  2766. * Thus, in all cases it suffices to blow away our signed bounds
  2767. * and rely on inferring new ones from the unsigned bounds and
  2768. * var_off of the result.
  2769. */
  2770. dst_reg->smin_value = S64_MIN;
  2771. dst_reg->smax_value = S64_MAX;
  2772. dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
  2773. dst_reg->umin_value >>= umax_val;
  2774. dst_reg->umax_value >>= umin_val;
  2775. /* We may learn something more from the var_off */
  2776. __update_reg_bounds(dst_reg);
  2777. break;
  2778. case BPF_ARSH:
  2779. if (umax_val >= insn_bitness) {
  2780. /* Shifts greater than 31 or 63 are undefined.
  2781. * This includes shifts by a negative number.
  2782. */
  2783. mark_reg_unknown(env, regs, insn->dst_reg);
  2784. break;
  2785. }
  2786. /* Upon reaching here, src_known is true and
  2787. * umax_val is equal to umin_val.
  2788. */
  2789. dst_reg->smin_value >>= umin_val;
  2790. dst_reg->smax_value >>= umin_val;
  2791. dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
  2792. /* blow away the dst_reg umin_value/umax_value and rely on
  2793. * dst_reg var_off to refine the result.
  2794. */
  2795. dst_reg->umin_value = 0;
  2796. dst_reg->umax_value = U64_MAX;
  2797. __update_reg_bounds(dst_reg);
  2798. break;
  2799. default:
  2800. mark_reg_unknown(env, regs, insn->dst_reg);
  2801. break;
  2802. }
  2803. if (BPF_CLASS(insn->code) != BPF_ALU64) {
  2804. /* 32-bit ALU ops are (32,32)->32 */
  2805. coerce_reg_to_size(dst_reg, 4);
  2806. coerce_reg_to_size(&src_reg, 4);
  2807. }
  2808. __reg_deduce_bounds(dst_reg);
  2809. __reg_bound_offset(dst_reg);
  2810. return 0;
  2811. }
  2812. /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
  2813. * and var_off.
  2814. */
  2815. static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
  2816. struct bpf_insn *insn)
  2817. {
  2818. struct bpf_verifier_state *vstate = env->cur_state;
  2819. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2820. struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
  2821. struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
  2822. u8 opcode = BPF_OP(insn->code);
  2823. dst_reg = &regs[insn->dst_reg];
  2824. src_reg = NULL;
  2825. if (dst_reg->type != SCALAR_VALUE)
  2826. ptr_reg = dst_reg;
  2827. if (BPF_SRC(insn->code) == BPF_X) {
  2828. src_reg = &regs[insn->src_reg];
  2829. if (src_reg->type != SCALAR_VALUE) {
  2830. if (dst_reg->type != SCALAR_VALUE) {
  2831. /* Combining two pointers by any ALU op yields
  2832. * an arbitrary scalar. Disallow all math except
  2833. * pointer subtraction
  2834. */
  2835. if (opcode == BPF_SUB){
  2836. mark_reg_unknown(env, regs, insn->dst_reg);
  2837. return 0;
  2838. }
  2839. verbose(env, "R%d pointer %s pointer prohibited\n",
  2840. insn->dst_reg,
  2841. bpf_alu_string[opcode >> 4]);
  2842. return -EACCES;
  2843. } else {
  2844. /* scalar += pointer
  2845. * This is legal, but we have to reverse our
  2846. * src/dest handling in computing the range
  2847. */
  2848. return adjust_ptr_min_max_vals(env, insn,
  2849. src_reg, dst_reg);
  2850. }
  2851. } else if (ptr_reg) {
  2852. /* pointer += scalar */
  2853. return adjust_ptr_min_max_vals(env, insn,
  2854. dst_reg, src_reg);
  2855. }
  2856. } else {
  2857. /* Pretend the src is a reg with a known value, since we only
  2858. * need to be able to read from this state.
  2859. */
  2860. off_reg.type = SCALAR_VALUE;
  2861. __mark_reg_known(&off_reg, insn->imm);
  2862. src_reg = &off_reg;
  2863. if (ptr_reg) /* pointer += K */
  2864. return adjust_ptr_min_max_vals(env, insn,
  2865. ptr_reg, src_reg);
  2866. }
  2867. /* Got here implies adding two SCALAR_VALUEs */
  2868. if (WARN_ON_ONCE(ptr_reg)) {
  2869. print_verifier_state(env, state);
  2870. verbose(env, "verifier internal error: unexpected ptr_reg\n");
  2871. return -EINVAL;
  2872. }
  2873. if (WARN_ON(!src_reg)) {
  2874. print_verifier_state(env, state);
  2875. verbose(env, "verifier internal error: no src_reg\n");
  2876. return -EINVAL;
  2877. }
  2878. return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
  2879. }
  2880. /* check validity of 32-bit and 64-bit arithmetic operations */
  2881. static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2882. {
  2883. struct bpf_reg_state *regs = cur_regs(env);
  2884. u8 opcode = BPF_OP(insn->code);
  2885. int err;
  2886. if (opcode == BPF_END || opcode == BPF_NEG) {
  2887. if (opcode == BPF_NEG) {
  2888. if (BPF_SRC(insn->code) != 0 ||
  2889. insn->src_reg != BPF_REG_0 ||
  2890. insn->off != 0 || insn->imm != 0) {
  2891. verbose(env, "BPF_NEG uses reserved fields\n");
  2892. return -EINVAL;
  2893. }
  2894. } else {
  2895. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  2896. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
  2897. BPF_CLASS(insn->code) == BPF_ALU64) {
  2898. verbose(env, "BPF_END uses reserved fields\n");
  2899. return -EINVAL;
  2900. }
  2901. }
  2902. /* check src operand */
  2903. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  2904. if (err)
  2905. return err;
  2906. if (is_pointer_value(env, insn->dst_reg)) {
  2907. verbose(env, "R%d pointer arithmetic prohibited\n",
  2908. insn->dst_reg);
  2909. return -EACCES;
  2910. }
  2911. /* check dest operand */
  2912. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  2913. if (err)
  2914. return err;
  2915. } else if (opcode == BPF_MOV) {
  2916. if (BPF_SRC(insn->code) == BPF_X) {
  2917. if (insn->imm != 0 || insn->off != 0) {
  2918. verbose(env, "BPF_MOV uses reserved fields\n");
  2919. return -EINVAL;
  2920. }
  2921. /* check src operand */
  2922. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  2923. if (err)
  2924. return err;
  2925. } else {
  2926. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  2927. verbose(env, "BPF_MOV uses reserved fields\n");
  2928. return -EINVAL;
  2929. }
  2930. }
  2931. /* check dest operand */
  2932. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  2933. if (err)
  2934. return err;
  2935. if (BPF_SRC(insn->code) == BPF_X) {
  2936. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  2937. /* case: R1 = R2
  2938. * copy register state to dest reg
  2939. */
  2940. regs[insn->dst_reg] = regs[insn->src_reg];
  2941. regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
  2942. } else {
  2943. /* R1 = (u32) R2 */
  2944. if (is_pointer_value(env, insn->src_reg)) {
  2945. verbose(env,
  2946. "R%d partial copy of pointer\n",
  2947. insn->src_reg);
  2948. return -EACCES;
  2949. }
  2950. mark_reg_unknown(env, regs, insn->dst_reg);
  2951. coerce_reg_to_size(&regs[insn->dst_reg], 4);
  2952. }
  2953. } else {
  2954. /* case: R = imm
  2955. * remember the value we stored into this reg
  2956. */
  2957. regs[insn->dst_reg].type = SCALAR_VALUE;
  2958. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  2959. __mark_reg_known(regs + insn->dst_reg,
  2960. insn->imm);
  2961. } else {
  2962. __mark_reg_known(regs + insn->dst_reg,
  2963. (u32)insn->imm);
  2964. }
  2965. }
  2966. } else if (opcode > BPF_END) {
  2967. verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
  2968. return -EINVAL;
  2969. } else { /* all other ALU ops: and, sub, xor, add, ... */
  2970. if (BPF_SRC(insn->code) == BPF_X) {
  2971. if (insn->imm != 0 || insn->off != 0) {
  2972. verbose(env, "BPF_ALU uses reserved fields\n");
  2973. return -EINVAL;
  2974. }
  2975. /* check src1 operand */
  2976. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  2977. if (err)
  2978. return err;
  2979. } else {
  2980. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  2981. verbose(env, "BPF_ALU uses reserved fields\n");
  2982. return -EINVAL;
  2983. }
  2984. }
  2985. /* check src2 operand */
  2986. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  2987. if (err)
  2988. return err;
  2989. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  2990. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  2991. verbose(env, "div by zero\n");
  2992. return -EINVAL;
  2993. }
  2994. if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
  2995. verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
  2996. return -EINVAL;
  2997. }
  2998. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  2999. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  3000. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  3001. if (insn->imm < 0 || insn->imm >= size) {
  3002. verbose(env, "invalid shift %d\n", insn->imm);
  3003. return -EINVAL;
  3004. }
  3005. }
  3006. /* check dest operand */
  3007. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  3008. if (err)
  3009. return err;
  3010. return adjust_reg_min_max_vals(env, insn);
  3011. }
  3012. return 0;
  3013. }
  3014. static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
  3015. struct bpf_reg_state *dst_reg,
  3016. enum bpf_reg_type type,
  3017. bool range_right_open)
  3018. {
  3019. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  3020. struct bpf_reg_state *regs = state->regs, *reg;
  3021. u16 new_range;
  3022. int i, j;
  3023. if (dst_reg->off < 0 ||
  3024. (dst_reg->off == 0 && range_right_open))
  3025. /* This doesn't give us any range */
  3026. return;
  3027. if (dst_reg->umax_value > MAX_PACKET_OFF ||
  3028. dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
  3029. /* Risk of overflow. For instance, ptr + (1<<63) may be less
  3030. * than pkt_end, but that's because it's also less than pkt.
  3031. */
  3032. return;
  3033. new_range = dst_reg->off;
  3034. if (range_right_open)
  3035. new_range--;
  3036. /* Examples for register markings:
  3037. *
  3038. * pkt_data in dst register:
  3039. *
  3040. * r2 = r3;
  3041. * r2 += 8;
  3042. * if (r2 > pkt_end) goto <handle exception>
  3043. * <access okay>
  3044. *
  3045. * r2 = r3;
  3046. * r2 += 8;
  3047. * if (r2 < pkt_end) goto <access okay>
  3048. * <handle exception>
  3049. *
  3050. * Where:
  3051. * r2 == dst_reg, pkt_end == src_reg
  3052. * r2=pkt(id=n,off=8,r=0)
  3053. * r3=pkt(id=n,off=0,r=0)
  3054. *
  3055. * pkt_data in src register:
  3056. *
  3057. * r2 = r3;
  3058. * r2 += 8;
  3059. * if (pkt_end >= r2) goto <access okay>
  3060. * <handle exception>
  3061. *
  3062. * r2 = r3;
  3063. * r2 += 8;
  3064. * if (pkt_end <= r2) goto <handle exception>
  3065. * <access okay>
  3066. *
  3067. * Where:
  3068. * pkt_end == dst_reg, r2 == src_reg
  3069. * r2=pkt(id=n,off=8,r=0)
  3070. * r3=pkt(id=n,off=0,r=0)
  3071. *
  3072. * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
  3073. * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
  3074. * and [r3, r3 + 8-1) respectively is safe to access depending on
  3075. * the check.
  3076. */
  3077. /* If our ids match, then we must have the same max_value. And we
  3078. * don't care about the other reg's fixed offset, since if it's too big
  3079. * the range won't allow anything.
  3080. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
  3081. */
  3082. for (i = 0; i < MAX_BPF_REG; i++)
  3083. if (regs[i].type == type && regs[i].id == dst_reg->id)
  3084. /* keep the maximum range already checked */
  3085. regs[i].range = max(regs[i].range, new_range);
  3086. for (j = 0; j <= vstate->curframe; j++) {
  3087. state = vstate->frame[j];
  3088. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  3089. if (state->stack[i].slot_type[0] != STACK_SPILL)
  3090. continue;
  3091. reg = &state->stack[i].spilled_ptr;
  3092. if (reg->type == type && reg->id == dst_reg->id)
  3093. reg->range = max(reg->range, new_range);
  3094. }
  3095. }
  3096. }
  3097. /* Adjusts the register min/max values in the case that the dst_reg is the
  3098. * variable register that we are working on, and src_reg is a constant or we're
  3099. * simply doing a BPF_K check.
  3100. * In JEQ/JNE cases we also adjust the var_off values.
  3101. */
  3102. static void reg_set_min_max(struct bpf_reg_state *true_reg,
  3103. struct bpf_reg_state *false_reg, u64 val,
  3104. u8 opcode)
  3105. {
  3106. /* If the dst_reg is a pointer, we can't learn anything about its
  3107. * variable offset from the compare (unless src_reg were a pointer into
  3108. * the same object, but we don't bother with that.
  3109. * Since false_reg and true_reg have the same type by construction, we
  3110. * only need to check one of them for pointerness.
  3111. */
  3112. if (__is_pointer_value(false, false_reg))
  3113. return;
  3114. switch (opcode) {
  3115. case BPF_JEQ:
  3116. /* If this is false then we know nothing Jon Snow, but if it is
  3117. * true then we know for sure.
  3118. */
  3119. __mark_reg_known(true_reg, val);
  3120. break;
  3121. case BPF_JNE:
  3122. /* If this is true we know nothing Jon Snow, but if it is false
  3123. * we know the value for sure;
  3124. */
  3125. __mark_reg_known(false_reg, val);
  3126. break;
  3127. case BPF_JGT:
  3128. false_reg->umax_value = min(false_reg->umax_value, val);
  3129. true_reg->umin_value = max(true_reg->umin_value, val + 1);
  3130. break;
  3131. case BPF_JSGT:
  3132. false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
  3133. true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
  3134. break;
  3135. case BPF_JLT:
  3136. false_reg->umin_value = max(false_reg->umin_value, val);
  3137. true_reg->umax_value = min(true_reg->umax_value, val - 1);
  3138. break;
  3139. case BPF_JSLT:
  3140. false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
  3141. true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
  3142. break;
  3143. case BPF_JGE:
  3144. false_reg->umax_value = min(false_reg->umax_value, val - 1);
  3145. true_reg->umin_value = max(true_reg->umin_value, val);
  3146. break;
  3147. case BPF_JSGE:
  3148. false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
  3149. true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
  3150. break;
  3151. case BPF_JLE:
  3152. false_reg->umin_value = max(false_reg->umin_value, val + 1);
  3153. true_reg->umax_value = min(true_reg->umax_value, val);
  3154. break;
  3155. case BPF_JSLE:
  3156. false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
  3157. true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
  3158. break;
  3159. default:
  3160. break;
  3161. }
  3162. __reg_deduce_bounds(false_reg);
  3163. __reg_deduce_bounds(true_reg);
  3164. /* We might have learned some bits from the bounds. */
  3165. __reg_bound_offset(false_reg);
  3166. __reg_bound_offset(true_reg);
  3167. /* Intersecting with the old var_off might have improved our bounds
  3168. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  3169. * then new var_off is (0; 0x7f...fc) which improves our umax.
  3170. */
  3171. __update_reg_bounds(false_reg);
  3172. __update_reg_bounds(true_reg);
  3173. }
  3174. /* Same as above, but for the case that dst_reg holds a constant and src_reg is
  3175. * the variable reg.
  3176. */
  3177. static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
  3178. struct bpf_reg_state *false_reg, u64 val,
  3179. u8 opcode)
  3180. {
  3181. if (__is_pointer_value(false, false_reg))
  3182. return;
  3183. switch (opcode) {
  3184. case BPF_JEQ:
  3185. /* If this is false then we know nothing Jon Snow, but if it is
  3186. * true then we know for sure.
  3187. */
  3188. __mark_reg_known(true_reg, val);
  3189. break;
  3190. case BPF_JNE:
  3191. /* If this is true we know nothing Jon Snow, but if it is false
  3192. * we know the value for sure;
  3193. */
  3194. __mark_reg_known(false_reg, val);
  3195. break;
  3196. case BPF_JGT:
  3197. true_reg->umax_value = min(true_reg->umax_value, val - 1);
  3198. false_reg->umin_value = max(false_reg->umin_value, val);
  3199. break;
  3200. case BPF_JSGT:
  3201. true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
  3202. false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
  3203. break;
  3204. case BPF_JLT:
  3205. true_reg->umin_value = max(true_reg->umin_value, val + 1);
  3206. false_reg->umax_value = min(false_reg->umax_value, val);
  3207. break;
  3208. case BPF_JSLT:
  3209. true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
  3210. false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
  3211. break;
  3212. case BPF_JGE:
  3213. true_reg->umax_value = min(true_reg->umax_value, val);
  3214. false_reg->umin_value = max(false_reg->umin_value, val + 1);
  3215. break;
  3216. case BPF_JSGE:
  3217. true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
  3218. false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
  3219. break;
  3220. case BPF_JLE:
  3221. true_reg->umin_value = max(true_reg->umin_value, val);
  3222. false_reg->umax_value = min(false_reg->umax_value, val - 1);
  3223. break;
  3224. case BPF_JSLE:
  3225. true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
  3226. false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
  3227. break;
  3228. default:
  3229. break;
  3230. }
  3231. __reg_deduce_bounds(false_reg);
  3232. __reg_deduce_bounds(true_reg);
  3233. /* We might have learned some bits from the bounds. */
  3234. __reg_bound_offset(false_reg);
  3235. __reg_bound_offset(true_reg);
  3236. /* Intersecting with the old var_off might have improved our bounds
  3237. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  3238. * then new var_off is (0; 0x7f...fc) which improves our umax.
  3239. */
  3240. __update_reg_bounds(false_reg);
  3241. __update_reg_bounds(true_reg);
  3242. }
  3243. /* Regs are known to be equal, so intersect their min/max/var_off */
  3244. static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
  3245. struct bpf_reg_state *dst_reg)
  3246. {
  3247. src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
  3248. dst_reg->umin_value);
  3249. src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
  3250. dst_reg->umax_value);
  3251. src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
  3252. dst_reg->smin_value);
  3253. src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
  3254. dst_reg->smax_value);
  3255. src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
  3256. dst_reg->var_off);
  3257. /* We might have learned new bounds from the var_off. */
  3258. __update_reg_bounds(src_reg);
  3259. __update_reg_bounds(dst_reg);
  3260. /* We might have learned something about the sign bit. */
  3261. __reg_deduce_bounds(src_reg);
  3262. __reg_deduce_bounds(dst_reg);
  3263. /* We might have learned some bits from the bounds. */
  3264. __reg_bound_offset(src_reg);
  3265. __reg_bound_offset(dst_reg);
  3266. /* Intersecting with the old var_off might have improved our bounds
  3267. * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  3268. * then new var_off is (0; 0x7f...fc) which improves our umax.
  3269. */
  3270. __update_reg_bounds(src_reg);
  3271. __update_reg_bounds(dst_reg);
  3272. }
  3273. static void reg_combine_min_max(struct bpf_reg_state *true_src,
  3274. struct bpf_reg_state *true_dst,
  3275. struct bpf_reg_state *false_src,
  3276. struct bpf_reg_state *false_dst,
  3277. u8 opcode)
  3278. {
  3279. switch (opcode) {
  3280. case BPF_JEQ:
  3281. __reg_combine_min_max(true_src, true_dst);
  3282. break;
  3283. case BPF_JNE:
  3284. __reg_combine_min_max(false_src, false_dst);
  3285. break;
  3286. }
  3287. }
  3288. static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
  3289. bool is_null)
  3290. {
  3291. struct bpf_reg_state *reg = &regs[regno];
  3292. if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
  3293. /* Old offset (both fixed and variable parts) should
  3294. * have been known-zero, because we don't allow pointer
  3295. * arithmetic on pointers that might be NULL.
  3296. */
  3297. if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
  3298. !tnum_equals_const(reg->var_off, 0) ||
  3299. reg->off)) {
  3300. __mark_reg_known_zero(reg);
  3301. reg->off = 0;
  3302. }
  3303. if (is_null) {
  3304. reg->type = SCALAR_VALUE;
  3305. } else if (reg->map_ptr->inner_map_meta) {
  3306. reg->type = CONST_PTR_TO_MAP;
  3307. reg->map_ptr = reg->map_ptr->inner_map_meta;
  3308. } else {
  3309. reg->type = PTR_TO_MAP_VALUE;
  3310. }
  3311. /* We don't need id from this point onwards anymore, thus we
  3312. * should better reset it, so that state pruning has chances
  3313. * to take effect.
  3314. */
  3315. reg->id = 0;
  3316. }
  3317. }
  3318. /* The logic is similar to find_good_pkt_pointers(), both could eventually
  3319. * be folded together at some point.
  3320. */
  3321. static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
  3322. bool is_null)
  3323. {
  3324. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  3325. struct bpf_reg_state *regs = state->regs;
  3326. u32 id = regs[regno].id;
  3327. int i, j;
  3328. for (i = 0; i < MAX_BPF_REG; i++)
  3329. mark_map_reg(regs, i, id, is_null);
  3330. for (j = 0; j <= vstate->curframe; j++) {
  3331. state = vstate->frame[j];
  3332. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  3333. if (state->stack[i].slot_type[0] != STACK_SPILL)
  3334. continue;
  3335. mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
  3336. }
  3337. }
  3338. }
  3339. static bool try_match_pkt_pointers(const struct bpf_insn *insn,
  3340. struct bpf_reg_state *dst_reg,
  3341. struct bpf_reg_state *src_reg,
  3342. struct bpf_verifier_state *this_branch,
  3343. struct bpf_verifier_state *other_branch)
  3344. {
  3345. if (BPF_SRC(insn->code) != BPF_X)
  3346. return false;
  3347. switch (BPF_OP(insn->code)) {
  3348. case BPF_JGT:
  3349. if ((dst_reg->type == PTR_TO_PACKET &&
  3350. src_reg->type == PTR_TO_PACKET_END) ||
  3351. (dst_reg->type == PTR_TO_PACKET_META &&
  3352. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  3353. /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
  3354. find_good_pkt_pointers(this_branch, dst_reg,
  3355. dst_reg->type, false);
  3356. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  3357. src_reg->type == PTR_TO_PACKET) ||
  3358. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  3359. src_reg->type == PTR_TO_PACKET_META)) {
  3360. /* pkt_end > pkt_data', pkt_data > pkt_meta' */
  3361. find_good_pkt_pointers(other_branch, src_reg,
  3362. src_reg->type, true);
  3363. } else {
  3364. return false;
  3365. }
  3366. break;
  3367. case BPF_JLT:
  3368. if ((dst_reg->type == PTR_TO_PACKET &&
  3369. src_reg->type == PTR_TO_PACKET_END) ||
  3370. (dst_reg->type == PTR_TO_PACKET_META &&
  3371. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  3372. /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
  3373. find_good_pkt_pointers(other_branch, dst_reg,
  3374. dst_reg->type, true);
  3375. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  3376. src_reg->type == PTR_TO_PACKET) ||
  3377. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  3378. src_reg->type == PTR_TO_PACKET_META)) {
  3379. /* pkt_end < pkt_data', pkt_data > pkt_meta' */
  3380. find_good_pkt_pointers(this_branch, src_reg,
  3381. src_reg->type, false);
  3382. } else {
  3383. return false;
  3384. }
  3385. break;
  3386. case BPF_JGE:
  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, true);
  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, false);
  3401. } else {
  3402. return false;
  3403. }
  3404. break;
  3405. case BPF_JLE:
  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, false);
  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, true);
  3420. } else {
  3421. return false;
  3422. }
  3423. break;
  3424. default:
  3425. return false;
  3426. }
  3427. return true;
  3428. }
  3429. static int check_cond_jmp_op(struct bpf_verifier_env *env,
  3430. struct bpf_insn *insn, int *insn_idx)
  3431. {
  3432. struct bpf_verifier_state *this_branch = env->cur_state;
  3433. struct bpf_verifier_state *other_branch;
  3434. struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
  3435. struct bpf_reg_state *dst_reg, *other_branch_regs;
  3436. u8 opcode = BPF_OP(insn->code);
  3437. int err;
  3438. if (opcode > BPF_JSLE) {
  3439. verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
  3440. return -EINVAL;
  3441. }
  3442. if (BPF_SRC(insn->code) == BPF_X) {
  3443. if (insn->imm != 0) {
  3444. verbose(env, "BPF_JMP uses reserved fields\n");
  3445. return -EINVAL;
  3446. }
  3447. /* check src1 operand */
  3448. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  3449. if (err)
  3450. return err;
  3451. if (is_pointer_value(env, insn->src_reg)) {
  3452. verbose(env, "R%d pointer comparison prohibited\n",
  3453. insn->src_reg);
  3454. return -EACCES;
  3455. }
  3456. } else {
  3457. if (insn->src_reg != BPF_REG_0) {
  3458. verbose(env, "BPF_JMP uses reserved fields\n");
  3459. return -EINVAL;
  3460. }
  3461. }
  3462. /* check src2 operand */
  3463. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  3464. if (err)
  3465. return err;
  3466. dst_reg = &regs[insn->dst_reg];
  3467. /* detect if R == 0 where R was initialized to zero earlier */
  3468. if (BPF_SRC(insn->code) == BPF_K &&
  3469. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  3470. dst_reg->type == SCALAR_VALUE &&
  3471. tnum_is_const(dst_reg->var_off)) {
  3472. if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
  3473. (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
  3474. /* if (imm == imm) goto pc+off;
  3475. * only follow the goto, ignore fall-through
  3476. */
  3477. *insn_idx += insn->off;
  3478. return 0;
  3479. } else {
  3480. /* if (imm != imm) goto pc+off;
  3481. * only follow fall-through branch, since
  3482. * that's where the program will go
  3483. */
  3484. return 0;
  3485. }
  3486. }
  3487. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  3488. if (!other_branch)
  3489. return -EFAULT;
  3490. other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
  3491. /* detect if we are comparing against a constant value so we can adjust
  3492. * our min/max values for our dst register.
  3493. * this is only legit if both are scalars (or pointers to the same
  3494. * object, I suppose, but we don't support that right now), because
  3495. * otherwise the different base pointers mean the offsets aren't
  3496. * comparable.
  3497. */
  3498. if (BPF_SRC(insn->code) == BPF_X) {
  3499. if (dst_reg->type == SCALAR_VALUE &&
  3500. regs[insn->src_reg].type == SCALAR_VALUE) {
  3501. if (tnum_is_const(regs[insn->src_reg].var_off))
  3502. reg_set_min_max(&other_branch_regs[insn->dst_reg],
  3503. dst_reg, regs[insn->src_reg].var_off.value,
  3504. opcode);
  3505. else if (tnum_is_const(dst_reg->var_off))
  3506. reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
  3507. &regs[insn->src_reg],
  3508. dst_reg->var_off.value, opcode);
  3509. else if (opcode == BPF_JEQ || opcode == BPF_JNE)
  3510. /* Comparing for equality, we can combine knowledge */
  3511. reg_combine_min_max(&other_branch_regs[insn->src_reg],
  3512. &other_branch_regs[insn->dst_reg],
  3513. &regs[insn->src_reg],
  3514. &regs[insn->dst_reg], opcode);
  3515. }
  3516. } else if (dst_reg->type == SCALAR_VALUE) {
  3517. reg_set_min_max(&other_branch_regs[insn->dst_reg],
  3518. dst_reg, insn->imm, opcode);
  3519. }
  3520. /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
  3521. if (BPF_SRC(insn->code) == BPF_K &&
  3522. insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  3523. dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  3524. /* Mark all identical map registers in each branch as either
  3525. * safe or unknown depending R == 0 or R != 0 conditional.
  3526. */
  3527. mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
  3528. mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
  3529. } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
  3530. this_branch, other_branch) &&
  3531. is_pointer_value(env, insn->dst_reg)) {
  3532. verbose(env, "R%d pointer comparison prohibited\n",
  3533. insn->dst_reg);
  3534. return -EACCES;
  3535. }
  3536. if (env->log.level)
  3537. print_verifier_state(env, this_branch->frame[this_branch->curframe]);
  3538. return 0;
  3539. }
  3540. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  3541. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  3542. {
  3543. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  3544. return (struct bpf_map *) (unsigned long) imm64;
  3545. }
  3546. /* verify BPF_LD_IMM64 instruction */
  3547. static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
  3548. {
  3549. struct bpf_reg_state *regs = cur_regs(env);
  3550. int err;
  3551. if (BPF_SIZE(insn->code) != BPF_DW) {
  3552. verbose(env, "invalid BPF_LD_IMM insn\n");
  3553. return -EINVAL;
  3554. }
  3555. if (insn->off != 0) {
  3556. verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
  3557. return -EINVAL;
  3558. }
  3559. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  3560. if (err)
  3561. return err;
  3562. if (insn->src_reg == 0) {
  3563. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  3564. regs[insn->dst_reg].type = SCALAR_VALUE;
  3565. __mark_reg_known(&regs[insn->dst_reg], imm);
  3566. return 0;
  3567. }
  3568. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  3569. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  3570. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  3571. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  3572. return 0;
  3573. }
  3574. static bool may_access_skb(enum bpf_prog_type type)
  3575. {
  3576. switch (type) {
  3577. case BPF_PROG_TYPE_SOCKET_FILTER:
  3578. case BPF_PROG_TYPE_SCHED_CLS:
  3579. case BPF_PROG_TYPE_SCHED_ACT:
  3580. return true;
  3581. default:
  3582. return false;
  3583. }
  3584. }
  3585. /* verify safety of LD_ABS|LD_IND instructions:
  3586. * - they can only appear in the programs where ctx == skb
  3587. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  3588. * preserve R6-R9, and store return value into R0
  3589. *
  3590. * Implicit input:
  3591. * ctx == skb == R6 == CTX
  3592. *
  3593. * Explicit input:
  3594. * SRC == any register
  3595. * IMM == 32-bit immediate
  3596. *
  3597. * Output:
  3598. * R0 - 8/16/32-bit skb data converted to cpu endianness
  3599. */
  3600. static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
  3601. {
  3602. struct bpf_reg_state *regs = cur_regs(env);
  3603. u8 mode = BPF_MODE(insn->code);
  3604. int i, err;
  3605. if (!may_access_skb(env->prog->type)) {
  3606. verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
  3607. return -EINVAL;
  3608. }
  3609. if (!env->ops->gen_ld_abs) {
  3610. verbose(env, "bpf verifier is misconfigured\n");
  3611. return -EINVAL;
  3612. }
  3613. if (env->subprog_cnt > 1) {
  3614. /* when program has LD_ABS insn JITs and interpreter assume
  3615. * that r1 == ctx == skb which is not the case for callees
  3616. * that can have arbitrary arguments. It's problematic
  3617. * for main prog as well since JITs would need to analyze
  3618. * all functions in order to make proper register save/restore
  3619. * decisions in the main prog. Hence disallow LD_ABS with calls
  3620. */
  3621. verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
  3622. return -EINVAL;
  3623. }
  3624. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  3625. BPF_SIZE(insn->code) == BPF_DW ||
  3626. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  3627. verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
  3628. return -EINVAL;
  3629. }
  3630. /* check whether implicit source operand (register R6) is readable */
  3631. err = check_reg_arg(env, BPF_REG_6, SRC_OP);
  3632. if (err)
  3633. return err;
  3634. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  3635. verbose(env,
  3636. "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  3637. return -EINVAL;
  3638. }
  3639. if (mode == BPF_IND) {
  3640. /* check explicit source operand */
  3641. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  3642. if (err)
  3643. return err;
  3644. }
  3645. /* reset caller saved regs to unreadable */
  3646. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  3647. mark_reg_not_init(env, regs, caller_saved[i]);
  3648. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  3649. }
  3650. /* mark destination R0 register as readable, since it contains
  3651. * the value fetched from the packet.
  3652. * Already marked as written above.
  3653. */
  3654. mark_reg_unknown(env, regs, BPF_REG_0);
  3655. return 0;
  3656. }
  3657. static int check_return_code(struct bpf_verifier_env *env)
  3658. {
  3659. struct bpf_reg_state *reg;
  3660. struct tnum range = tnum_range(0, 1);
  3661. switch (env->prog->type) {
  3662. case BPF_PROG_TYPE_CGROUP_SKB:
  3663. case BPF_PROG_TYPE_CGROUP_SOCK:
  3664. case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
  3665. case BPF_PROG_TYPE_SOCK_OPS:
  3666. case BPF_PROG_TYPE_CGROUP_DEVICE:
  3667. break;
  3668. default:
  3669. return 0;
  3670. }
  3671. reg = cur_regs(env) + BPF_REG_0;
  3672. if (reg->type != SCALAR_VALUE) {
  3673. verbose(env, "At program exit the register R0 is not a known value (%s)\n",
  3674. reg_type_str[reg->type]);
  3675. return -EINVAL;
  3676. }
  3677. if (!tnum_in(range, reg->var_off)) {
  3678. verbose(env, "At program exit the register R0 ");
  3679. if (!tnum_is_unknown(reg->var_off)) {
  3680. char tn_buf[48];
  3681. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  3682. verbose(env, "has value %s", tn_buf);
  3683. } else {
  3684. verbose(env, "has unknown scalar value");
  3685. }
  3686. verbose(env, " should have been 0 or 1\n");
  3687. return -EINVAL;
  3688. }
  3689. return 0;
  3690. }
  3691. /* non-recursive DFS pseudo code
  3692. * 1 procedure DFS-iterative(G,v):
  3693. * 2 label v as discovered
  3694. * 3 let S be a stack
  3695. * 4 S.push(v)
  3696. * 5 while S is not empty
  3697. * 6 t <- S.pop()
  3698. * 7 if t is what we're looking for:
  3699. * 8 return t
  3700. * 9 for all edges e in G.adjacentEdges(t) do
  3701. * 10 if edge e is already labelled
  3702. * 11 continue with the next edge
  3703. * 12 w <- G.adjacentVertex(t,e)
  3704. * 13 if vertex w is not discovered and not explored
  3705. * 14 label e as tree-edge
  3706. * 15 label w as discovered
  3707. * 16 S.push(w)
  3708. * 17 continue at 5
  3709. * 18 else if vertex w is discovered
  3710. * 19 label e as back-edge
  3711. * 20 else
  3712. * 21 // vertex w is explored
  3713. * 22 label e as forward- or cross-edge
  3714. * 23 label t as explored
  3715. * 24 S.pop()
  3716. *
  3717. * convention:
  3718. * 0x10 - discovered
  3719. * 0x11 - discovered and fall-through edge labelled
  3720. * 0x12 - discovered and fall-through and branch edges labelled
  3721. * 0x20 - explored
  3722. */
  3723. enum {
  3724. DISCOVERED = 0x10,
  3725. EXPLORED = 0x20,
  3726. FALLTHROUGH = 1,
  3727. BRANCH = 2,
  3728. };
  3729. #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
  3730. static int *insn_stack; /* stack of insns to process */
  3731. static int cur_stack; /* current stack index */
  3732. static int *insn_state;
  3733. /* t, w, e - match pseudo-code above:
  3734. * t - index of current instruction
  3735. * w - next instruction
  3736. * e - edge
  3737. */
  3738. static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
  3739. {
  3740. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  3741. return 0;
  3742. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  3743. return 0;
  3744. if (w < 0 || w >= env->prog->len) {
  3745. verbose(env, "jump out of range from insn %d to %d\n", t, w);
  3746. return -EINVAL;
  3747. }
  3748. if (e == BRANCH)
  3749. /* mark branch target for state pruning */
  3750. env->explored_states[w] = STATE_LIST_MARK;
  3751. if (insn_state[w] == 0) {
  3752. /* tree-edge */
  3753. insn_state[t] = DISCOVERED | e;
  3754. insn_state[w] = DISCOVERED;
  3755. if (cur_stack >= env->prog->len)
  3756. return -E2BIG;
  3757. insn_stack[cur_stack++] = w;
  3758. return 1;
  3759. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  3760. verbose(env, "back-edge from insn %d to %d\n", t, w);
  3761. return -EINVAL;
  3762. } else if (insn_state[w] == EXPLORED) {
  3763. /* forward- or cross-edge */
  3764. insn_state[t] = DISCOVERED | e;
  3765. } else {
  3766. verbose(env, "insn state internal bug\n");
  3767. return -EFAULT;
  3768. }
  3769. return 0;
  3770. }
  3771. /* non-recursive depth-first-search to detect loops in BPF program
  3772. * loop == back-edge in directed graph
  3773. */
  3774. static int check_cfg(struct bpf_verifier_env *env)
  3775. {
  3776. struct bpf_insn *insns = env->prog->insnsi;
  3777. int insn_cnt = env->prog->len;
  3778. int ret = 0;
  3779. int i, t;
  3780. ret = check_subprogs(env);
  3781. if (ret < 0)
  3782. return ret;
  3783. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  3784. if (!insn_state)
  3785. return -ENOMEM;
  3786. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  3787. if (!insn_stack) {
  3788. kfree(insn_state);
  3789. return -ENOMEM;
  3790. }
  3791. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  3792. insn_stack[0] = 0; /* 0 is the first instruction */
  3793. cur_stack = 1;
  3794. peek_stack:
  3795. if (cur_stack == 0)
  3796. goto check_state;
  3797. t = insn_stack[cur_stack - 1];
  3798. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  3799. u8 opcode = BPF_OP(insns[t].code);
  3800. if (opcode == BPF_EXIT) {
  3801. goto mark_explored;
  3802. } else if (opcode == BPF_CALL) {
  3803. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  3804. if (ret == 1)
  3805. goto peek_stack;
  3806. else if (ret < 0)
  3807. goto err_free;
  3808. if (t + 1 < insn_cnt)
  3809. env->explored_states[t + 1] = STATE_LIST_MARK;
  3810. if (insns[t].src_reg == BPF_PSEUDO_CALL) {
  3811. env->explored_states[t] = STATE_LIST_MARK;
  3812. ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
  3813. if (ret == 1)
  3814. goto peek_stack;
  3815. else if (ret < 0)
  3816. goto err_free;
  3817. }
  3818. } else if (opcode == BPF_JA) {
  3819. if (BPF_SRC(insns[t].code) != BPF_K) {
  3820. ret = -EINVAL;
  3821. goto err_free;
  3822. }
  3823. /* unconditional jump with single edge */
  3824. ret = push_insn(t, t + insns[t].off + 1,
  3825. FALLTHROUGH, env);
  3826. if (ret == 1)
  3827. goto peek_stack;
  3828. else if (ret < 0)
  3829. goto err_free;
  3830. /* tell verifier to check for equivalent states
  3831. * after every call and jump
  3832. */
  3833. if (t + 1 < insn_cnt)
  3834. env->explored_states[t + 1] = STATE_LIST_MARK;
  3835. } else {
  3836. /* conditional jump with two edges */
  3837. env->explored_states[t] = STATE_LIST_MARK;
  3838. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  3839. if (ret == 1)
  3840. goto peek_stack;
  3841. else if (ret < 0)
  3842. goto err_free;
  3843. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  3844. if (ret == 1)
  3845. goto peek_stack;
  3846. else if (ret < 0)
  3847. goto err_free;
  3848. }
  3849. } else {
  3850. /* all other non-branch instructions with single
  3851. * fall-through edge
  3852. */
  3853. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  3854. if (ret == 1)
  3855. goto peek_stack;
  3856. else if (ret < 0)
  3857. goto err_free;
  3858. }
  3859. mark_explored:
  3860. insn_state[t] = EXPLORED;
  3861. if (cur_stack-- <= 0) {
  3862. verbose(env, "pop stack internal bug\n");
  3863. ret = -EFAULT;
  3864. goto err_free;
  3865. }
  3866. goto peek_stack;
  3867. check_state:
  3868. for (i = 0; i < insn_cnt; i++) {
  3869. if (insn_state[i] != EXPLORED) {
  3870. verbose(env, "unreachable insn %d\n", i);
  3871. ret = -EINVAL;
  3872. goto err_free;
  3873. }
  3874. }
  3875. ret = 0; /* cfg looks good */
  3876. err_free:
  3877. kfree(insn_state);
  3878. kfree(insn_stack);
  3879. return ret;
  3880. }
  3881. /* check %cur's range satisfies %old's */
  3882. static bool range_within(struct bpf_reg_state *old,
  3883. struct bpf_reg_state *cur)
  3884. {
  3885. return old->umin_value <= cur->umin_value &&
  3886. old->umax_value >= cur->umax_value &&
  3887. old->smin_value <= cur->smin_value &&
  3888. old->smax_value >= cur->smax_value;
  3889. }
  3890. /* Maximum number of register states that can exist at once */
  3891. #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
  3892. struct idpair {
  3893. u32 old;
  3894. u32 cur;
  3895. };
  3896. /* If in the old state two registers had the same id, then they need to have
  3897. * the same id in the new state as well. But that id could be different from
  3898. * the old state, so we need to track the mapping from old to new ids.
  3899. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
  3900. * regs with old id 5 must also have new id 9 for the new state to be safe. But
  3901. * regs with a different old id could still have new id 9, we don't care about
  3902. * that.
  3903. * So we look through our idmap to see if this old id has been seen before. If
  3904. * so, we require the new id to match; otherwise, we add the id pair to the map.
  3905. */
  3906. static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
  3907. {
  3908. unsigned int i;
  3909. for (i = 0; i < ID_MAP_SIZE; i++) {
  3910. if (!idmap[i].old) {
  3911. /* Reached an empty slot; haven't seen this id before */
  3912. idmap[i].old = old_id;
  3913. idmap[i].cur = cur_id;
  3914. return true;
  3915. }
  3916. if (idmap[i].old == old_id)
  3917. return idmap[i].cur == cur_id;
  3918. }
  3919. /* We ran out of idmap slots, which should be impossible */
  3920. WARN_ON_ONCE(1);
  3921. return false;
  3922. }
  3923. /* Returns true if (rold safe implies rcur safe) */
  3924. static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
  3925. struct idpair *idmap)
  3926. {
  3927. bool equal;
  3928. if (!(rold->live & REG_LIVE_READ))
  3929. /* explored state didn't use this */
  3930. return true;
  3931. equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
  3932. if (rold->type == PTR_TO_STACK)
  3933. /* two stack pointers are equal only if they're pointing to
  3934. * the same stack frame, since fp-8 in foo != fp-8 in bar
  3935. */
  3936. return equal && rold->frameno == rcur->frameno;
  3937. if (equal)
  3938. return true;
  3939. if (rold->type == NOT_INIT)
  3940. /* explored state can't have used this */
  3941. return true;
  3942. if (rcur->type == NOT_INIT)
  3943. return false;
  3944. switch (rold->type) {
  3945. case SCALAR_VALUE:
  3946. if (rcur->type == SCALAR_VALUE) {
  3947. /* new val must satisfy old val knowledge */
  3948. return range_within(rold, rcur) &&
  3949. tnum_in(rold->var_off, rcur->var_off);
  3950. } else {
  3951. /* We're trying to use a pointer in place of a scalar.
  3952. * Even if the scalar was unbounded, this could lead to
  3953. * pointer leaks because scalars are allowed to leak
  3954. * while pointers are not. We could make this safe in
  3955. * special cases if root is calling us, but it's
  3956. * probably not worth the hassle.
  3957. */
  3958. return false;
  3959. }
  3960. case PTR_TO_MAP_VALUE:
  3961. /* If the new min/max/var_off satisfy the old ones and
  3962. * everything else matches, we are OK.
  3963. * We don't care about the 'id' value, because nothing
  3964. * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
  3965. */
  3966. return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
  3967. range_within(rold, rcur) &&
  3968. tnum_in(rold->var_off, rcur->var_off);
  3969. case PTR_TO_MAP_VALUE_OR_NULL:
  3970. /* a PTR_TO_MAP_VALUE could be safe to use as a
  3971. * PTR_TO_MAP_VALUE_OR_NULL into the same map.
  3972. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
  3973. * checked, doing so could have affected others with the same
  3974. * id, and we can't check for that because we lost the id when
  3975. * we converted to a PTR_TO_MAP_VALUE.
  3976. */
  3977. if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
  3978. return false;
  3979. if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
  3980. return false;
  3981. /* Check our ids match any regs they're supposed to */
  3982. return check_ids(rold->id, rcur->id, idmap);
  3983. case PTR_TO_PACKET_META:
  3984. case PTR_TO_PACKET:
  3985. if (rcur->type != rold->type)
  3986. return false;
  3987. /* We must have at least as much range as the old ptr
  3988. * did, so that any accesses which were safe before are
  3989. * still safe. This is true even if old range < old off,
  3990. * since someone could have accessed through (ptr - k), or
  3991. * even done ptr -= k in a register, to get a safe access.
  3992. */
  3993. if (rold->range > rcur->range)
  3994. return false;
  3995. /* If the offsets don't match, we can't trust our alignment;
  3996. * nor can we be sure that we won't fall out of range.
  3997. */
  3998. if (rold->off != rcur->off)
  3999. return false;
  4000. /* id relations must be preserved */
  4001. if (rold->id && !check_ids(rold->id, rcur->id, idmap))
  4002. return false;
  4003. /* new val must satisfy old val knowledge */
  4004. return range_within(rold, rcur) &&
  4005. tnum_in(rold->var_off, rcur->var_off);
  4006. case PTR_TO_CTX:
  4007. case CONST_PTR_TO_MAP:
  4008. case PTR_TO_PACKET_END:
  4009. /* Only valid matches are exact, which memcmp() above
  4010. * would have accepted
  4011. */
  4012. default:
  4013. /* Don't know what's going on, just say it's not safe */
  4014. return false;
  4015. }
  4016. /* Shouldn't get here; if we do, say it's not safe */
  4017. WARN_ON_ONCE(1);
  4018. return false;
  4019. }
  4020. static bool stacksafe(struct bpf_func_state *old,
  4021. struct bpf_func_state *cur,
  4022. struct idpair *idmap)
  4023. {
  4024. int i, spi;
  4025. /* if explored stack has more populated slots than current stack
  4026. * such stacks are not equivalent
  4027. */
  4028. if (old->allocated_stack > cur->allocated_stack)
  4029. return false;
  4030. /* walk slots of the explored stack and ignore any additional
  4031. * slots in the current stack, since explored(safe) state
  4032. * didn't use them
  4033. */
  4034. for (i = 0; i < old->allocated_stack; i++) {
  4035. spi = i / BPF_REG_SIZE;
  4036. if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
  4037. /* explored state didn't use this */
  4038. continue;
  4039. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
  4040. continue;
  4041. /* if old state was safe with misc data in the stack
  4042. * it will be safe with zero-initialized stack.
  4043. * The opposite is not true
  4044. */
  4045. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
  4046. cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
  4047. continue;
  4048. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
  4049. cur->stack[spi].slot_type[i % BPF_REG_SIZE])
  4050. /* Ex: old explored (safe) state has STACK_SPILL in
  4051. * this stack slot, but current has has STACK_MISC ->
  4052. * this verifier states are not equivalent,
  4053. * return false to continue verification of this path
  4054. */
  4055. return false;
  4056. if (i % BPF_REG_SIZE)
  4057. continue;
  4058. if (old->stack[spi].slot_type[0] != STACK_SPILL)
  4059. continue;
  4060. if (!regsafe(&old->stack[spi].spilled_ptr,
  4061. &cur->stack[spi].spilled_ptr,
  4062. idmap))
  4063. /* when explored and current stack slot are both storing
  4064. * spilled registers, check that stored pointers types
  4065. * are the same as well.
  4066. * Ex: explored safe path could have stored
  4067. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
  4068. * but current path has stored:
  4069. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
  4070. * such verifier states are not equivalent.
  4071. * return false to continue verification of this path
  4072. */
  4073. return false;
  4074. }
  4075. return true;
  4076. }
  4077. /* compare two verifier states
  4078. *
  4079. * all states stored in state_list are known to be valid, since
  4080. * verifier reached 'bpf_exit' instruction through them
  4081. *
  4082. * this function is called when verifier exploring different branches of
  4083. * execution popped from the state stack. If it sees an old state that has
  4084. * more strict register state and more strict stack state then this execution
  4085. * branch doesn't need to be explored further, since verifier already
  4086. * concluded that more strict state leads to valid finish.
  4087. *
  4088. * Therefore two states are equivalent if register state is more conservative
  4089. * and explored stack state is more conservative than the current one.
  4090. * Example:
  4091. * explored current
  4092. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  4093. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  4094. *
  4095. * In other words if current stack state (one being explored) has more
  4096. * valid slots than old one that already passed validation, it means
  4097. * the verifier can stop exploring and conclude that current state is valid too
  4098. *
  4099. * Similarly with registers. If explored state has register type as invalid
  4100. * whereas register type in current state is meaningful, it means that
  4101. * the current state will reach 'bpf_exit' instruction safely
  4102. */
  4103. static bool func_states_equal(struct bpf_func_state *old,
  4104. struct bpf_func_state *cur)
  4105. {
  4106. struct idpair *idmap;
  4107. bool ret = false;
  4108. int i;
  4109. idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
  4110. /* If we failed to allocate the idmap, just say it's not safe */
  4111. if (!idmap)
  4112. return false;
  4113. for (i = 0; i < MAX_BPF_REG; i++) {
  4114. if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
  4115. goto out_free;
  4116. }
  4117. if (!stacksafe(old, cur, idmap))
  4118. goto out_free;
  4119. ret = true;
  4120. out_free:
  4121. kfree(idmap);
  4122. return ret;
  4123. }
  4124. static bool states_equal(struct bpf_verifier_env *env,
  4125. struct bpf_verifier_state *old,
  4126. struct bpf_verifier_state *cur)
  4127. {
  4128. int i;
  4129. if (old->curframe != cur->curframe)
  4130. return false;
  4131. /* for states to be equal callsites have to be the same
  4132. * and all frame states need to be equivalent
  4133. */
  4134. for (i = 0; i <= old->curframe; i++) {
  4135. if (old->frame[i]->callsite != cur->frame[i]->callsite)
  4136. return false;
  4137. if (!func_states_equal(old->frame[i], cur->frame[i]))
  4138. return false;
  4139. }
  4140. return true;
  4141. }
  4142. /* A write screens off any subsequent reads; but write marks come from the
  4143. * straight-line code between a state and its parent. When we arrive at an
  4144. * equivalent state (jump target or such) we didn't arrive by the straight-line
  4145. * code, so read marks in the state must propagate to the parent regardless
  4146. * of the state's write marks. That's what 'parent == state->parent' comparison
  4147. * in mark_reg_read() and mark_stack_slot_read() is for.
  4148. */
  4149. static int propagate_liveness(struct bpf_verifier_env *env,
  4150. const struct bpf_verifier_state *vstate,
  4151. struct bpf_verifier_state *vparent)
  4152. {
  4153. int i, frame, err = 0;
  4154. struct bpf_func_state *state, *parent;
  4155. if (vparent->curframe != vstate->curframe) {
  4156. WARN(1, "propagate_live: parent frame %d current frame %d\n",
  4157. vparent->curframe, vstate->curframe);
  4158. return -EFAULT;
  4159. }
  4160. /* Propagate read liveness of registers... */
  4161. BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
  4162. /* We don't need to worry about FP liveness because it's read-only */
  4163. for (i = 0; i < BPF_REG_FP; i++) {
  4164. if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
  4165. continue;
  4166. if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
  4167. err = mark_reg_read(env, vstate, vparent, i);
  4168. if (err)
  4169. return err;
  4170. }
  4171. }
  4172. /* ... and stack slots */
  4173. for (frame = 0; frame <= vstate->curframe; frame++) {
  4174. state = vstate->frame[frame];
  4175. parent = vparent->frame[frame];
  4176. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
  4177. i < parent->allocated_stack / BPF_REG_SIZE; i++) {
  4178. if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
  4179. continue;
  4180. if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
  4181. mark_stack_slot_read(env, vstate, vparent, i, frame);
  4182. }
  4183. }
  4184. return err;
  4185. }
  4186. static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
  4187. {
  4188. struct bpf_verifier_state_list *new_sl;
  4189. struct bpf_verifier_state_list *sl;
  4190. struct bpf_verifier_state *cur = env->cur_state;
  4191. int i, j, err;
  4192. sl = env->explored_states[insn_idx];
  4193. if (!sl)
  4194. /* this 'insn_idx' instruction wasn't marked, so we will not
  4195. * be doing state search here
  4196. */
  4197. return 0;
  4198. while (sl != STATE_LIST_MARK) {
  4199. if (states_equal(env, &sl->state, cur)) {
  4200. /* reached equivalent register/stack state,
  4201. * prune the search.
  4202. * Registers read by the continuation are read by us.
  4203. * If we have any write marks in env->cur_state, they
  4204. * will prevent corresponding reads in the continuation
  4205. * from reaching our parent (an explored_state). Our
  4206. * own state will get the read marks recorded, but
  4207. * they'll be immediately forgotten as we're pruning
  4208. * this state and will pop a new one.
  4209. */
  4210. err = propagate_liveness(env, &sl->state, cur);
  4211. if (err)
  4212. return err;
  4213. return 1;
  4214. }
  4215. sl = sl->next;
  4216. }
  4217. /* there were no equivalent states, remember current one.
  4218. * technically the current state is not proven to be safe yet,
  4219. * but it will either reach outer most bpf_exit (which means it's safe)
  4220. * or it will be rejected. Since there are no loops, we won't be
  4221. * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
  4222. * again on the way to bpf_exit
  4223. */
  4224. new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
  4225. if (!new_sl)
  4226. return -ENOMEM;
  4227. /* add new state to the head of linked list */
  4228. err = copy_verifier_state(&new_sl->state, cur);
  4229. if (err) {
  4230. free_verifier_state(&new_sl->state, false);
  4231. kfree(new_sl);
  4232. return err;
  4233. }
  4234. new_sl->next = env->explored_states[insn_idx];
  4235. env->explored_states[insn_idx] = new_sl;
  4236. /* connect new state to parentage chain */
  4237. cur->parent = &new_sl->state;
  4238. /* clear write marks in current state: the writes we did are not writes
  4239. * our child did, so they don't screen off its reads from us.
  4240. * (There are no read marks in current state, because reads always mark
  4241. * their parent and current state never has children yet. Only
  4242. * explored_states can get read marks.)
  4243. */
  4244. for (i = 0; i < BPF_REG_FP; i++)
  4245. cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
  4246. /* all stack frames are accessible from callee, clear them all */
  4247. for (j = 0; j <= cur->curframe; j++) {
  4248. struct bpf_func_state *frame = cur->frame[j];
  4249. for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
  4250. frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
  4251. }
  4252. return 0;
  4253. }
  4254. static int do_check(struct bpf_verifier_env *env)
  4255. {
  4256. struct bpf_verifier_state *state;
  4257. struct bpf_insn *insns = env->prog->insnsi;
  4258. struct bpf_reg_state *regs;
  4259. int insn_cnt = env->prog->len, i;
  4260. int insn_idx, prev_insn_idx = 0;
  4261. int insn_processed = 0;
  4262. bool do_print_state = false;
  4263. state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
  4264. if (!state)
  4265. return -ENOMEM;
  4266. state->curframe = 0;
  4267. state->parent = NULL;
  4268. state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
  4269. if (!state->frame[0]) {
  4270. kfree(state);
  4271. return -ENOMEM;
  4272. }
  4273. env->cur_state = state;
  4274. init_func_state(env, state->frame[0],
  4275. BPF_MAIN_FUNC /* callsite */,
  4276. 0 /* frameno */,
  4277. 0 /* subprogno, zero == main subprog */);
  4278. insn_idx = 0;
  4279. for (;;) {
  4280. struct bpf_insn *insn;
  4281. u8 class;
  4282. int err;
  4283. if (insn_idx >= insn_cnt) {
  4284. verbose(env, "invalid insn idx %d insn_cnt %d\n",
  4285. insn_idx, insn_cnt);
  4286. return -EFAULT;
  4287. }
  4288. insn = &insns[insn_idx];
  4289. class = BPF_CLASS(insn->code);
  4290. if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
  4291. verbose(env,
  4292. "BPF program is too large. Processed %d insn\n",
  4293. insn_processed);
  4294. return -E2BIG;
  4295. }
  4296. err = is_state_visited(env, insn_idx);
  4297. if (err < 0)
  4298. return err;
  4299. if (err == 1) {
  4300. /* found equivalent state, can prune the search */
  4301. if (env->log.level) {
  4302. if (do_print_state)
  4303. verbose(env, "\nfrom %d to %d: safe\n",
  4304. prev_insn_idx, insn_idx);
  4305. else
  4306. verbose(env, "%d: safe\n", insn_idx);
  4307. }
  4308. goto process_bpf_exit;
  4309. }
  4310. if (need_resched())
  4311. cond_resched();
  4312. if (env->log.level > 1 || (env->log.level && do_print_state)) {
  4313. if (env->log.level > 1)
  4314. verbose(env, "%d:", insn_idx);
  4315. else
  4316. verbose(env, "\nfrom %d to %d:",
  4317. prev_insn_idx, insn_idx);
  4318. print_verifier_state(env, state->frame[state->curframe]);
  4319. do_print_state = false;
  4320. }
  4321. if (env->log.level) {
  4322. const struct bpf_insn_cbs cbs = {
  4323. .cb_print = verbose,
  4324. .private_data = env,
  4325. };
  4326. verbose(env, "%d: ", insn_idx);
  4327. print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
  4328. }
  4329. if (bpf_prog_is_dev_bound(env->prog->aux)) {
  4330. err = bpf_prog_offload_verify_insn(env, insn_idx,
  4331. prev_insn_idx);
  4332. if (err)
  4333. return err;
  4334. }
  4335. regs = cur_regs(env);
  4336. env->insn_aux_data[insn_idx].seen = true;
  4337. if (class == BPF_ALU || class == BPF_ALU64) {
  4338. err = check_alu_op(env, insn);
  4339. if (err)
  4340. return err;
  4341. } else if (class == BPF_LDX) {
  4342. enum bpf_reg_type *prev_src_type, src_reg_type;
  4343. /* check for reserved fields is already done */
  4344. /* check src operand */
  4345. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  4346. if (err)
  4347. return err;
  4348. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  4349. if (err)
  4350. return err;
  4351. src_reg_type = regs[insn->src_reg].type;
  4352. /* check that memory (src_reg + off) is readable,
  4353. * the state of dst_reg will be updated by this func
  4354. */
  4355. err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
  4356. BPF_SIZE(insn->code), BPF_READ,
  4357. insn->dst_reg, false);
  4358. if (err)
  4359. return err;
  4360. prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
  4361. if (*prev_src_type == NOT_INIT) {
  4362. /* saw a valid insn
  4363. * dst_reg = *(u32 *)(src_reg + off)
  4364. * save type to validate intersecting paths
  4365. */
  4366. *prev_src_type = src_reg_type;
  4367. } else if (src_reg_type != *prev_src_type &&
  4368. (src_reg_type == PTR_TO_CTX ||
  4369. *prev_src_type == PTR_TO_CTX)) {
  4370. /* ABuser program is trying to use the same insn
  4371. * dst_reg = *(u32*) (src_reg + off)
  4372. * with different pointer types:
  4373. * src_reg == ctx in one branch and
  4374. * src_reg == stack|map in some other branch.
  4375. * Reject it.
  4376. */
  4377. verbose(env, "same insn cannot be used with different pointers\n");
  4378. return -EINVAL;
  4379. }
  4380. } else if (class == BPF_STX) {
  4381. enum bpf_reg_type *prev_dst_type, dst_reg_type;
  4382. if (BPF_MODE(insn->code) == BPF_XADD) {
  4383. err = check_xadd(env, insn_idx, insn);
  4384. if (err)
  4385. return err;
  4386. insn_idx++;
  4387. continue;
  4388. }
  4389. /* check src1 operand */
  4390. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  4391. if (err)
  4392. return err;
  4393. /* check src2 operand */
  4394. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  4395. if (err)
  4396. return err;
  4397. dst_reg_type = regs[insn->dst_reg].type;
  4398. /* check that memory (dst_reg + off) is writeable */
  4399. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  4400. BPF_SIZE(insn->code), BPF_WRITE,
  4401. insn->src_reg, false);
  4402. if (err)
  4403. return err;
  4404. prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
  4405. if (*prev_dst_type == NOT_INIT) {
  4406. *prev_dst_type = dst_reg_type;
  4407. } else if (dst_reg_type != *prev_dst_type &&
  4408. (dst_reg_type == PTR_TO_CTX ||
  4409. *prev_dst_type == PTR_TO_CTX)) {
  4410. verbose(env, "same insn cannot be used with different pointers\n");
  4411. return -EINVAL;
  4412. }
  4413. } else if (class == BPF_ST) {
  4414. if (BPF_MODE(insn->code) != BPF_MEM ||
  4415. insn->src_reg != BPF_REG_0) {
  4416. verbose(env, "BPF_ST uses reserved fields\n");
  4417. return -EINVAL;
  4418. }
  4419. /* check src operand */
  4420. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  4421. if (err)
  4422. return err;
  4423. if (is_ctx_reg(env, insn->dst_reg)) {
  4424. verbose(env, "BPF_ST stores into R%d context is not allowed\n",
  4425. insn->dst_reg);
  4426. return -EACCES;
  4427. }
  4428. /* check that memory (dst_reg + off) is writeable */
  4429. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  4430. BPF_SIZE(insn->code), BPF_WRITE,
  4431. -1, false);
  4432. if (err)
  4433. return err;
  4434. } else if (class == BPF_JMP) {
  4435. u8 opcode = BPF_OP(insn->code);
  4436. if (opcode == BPF_CALL) {
  4437. if (BPF_SRC(insn->code) != BPF_K ||
  4438. insn->off != 0 ||
  4439. (insn->src_reg != BPF_REG_0 &&
  4440. insn->src_reg != BPF_PSEUDO_CALL) ||
  4441. insn->dst_reg != BPF_REG_0) {
  4442. verbose(env, "BPF_CALL uses reserved fields\n");
  4443. return -EINVAL;
  4444. }
  4445. if (insn->src_reg == BPF_PSEUDO_CALL)
  4446. err = check_func_call(env, insn, &insn_idx);
  4447. else
  4448. err = check_helper_call(env, insn->imm, insn_idx);
  4449. if (err)
  4450. return err;
  4451. } else if (opcode == BPF_JA) {
  4452. if (BPF_SRC(insn->code) != BPF_K ||
  4453. insn->imm != 0 ||
  4454. insn->src_reg != BPF_REG_0 ||
  4455. insn->dst_reg != BPF_REG_0) {
  4456. verbose(env, "BPF_JA uses reserved fields\n");
  4457. return -EINVAL;
  4458. }
  4459. insn_idx += insn->off + 1;
  4460. continue;
  4461. } else if (opcode == BPF_EXIT) {
  4462. if (BPF_SRC(insn->code) != BPF_K ||
  4463. insn->imm != 0 ||
  4464. insn->src_reg != BPF_REG_0 ||
  4465. insn->dst_reg != BPF_REG_0) {
  4466. verbose(env, "BPF_EXIT uses reserved fields\n");
  4467. return -EINVAL;
  4468. }
  4469. if (state->curframe) {
  4470. /* exit from nested function */
  4471. prev_insn_idx = insn_idx;
  4472. err = prepare_func_exit(env, &insn_idx);
  4473. if (err)
  4474. return err;
  4475. do_print_state = true;
  4476. continue;
  4477. }
  4478. /* eBPF calling convetion is such that R0 is used
  4479. * to return the value from eBPF program.
  4480. * Make sure that it's readable at this time
  4481. * of bpf_exit, which means that program wrote
  4482. * something into it earlier
  4483. */
  4484. err = check_reg_arg(env, BPF_REG_0, SRC_OP);
  4485. if (err)
  4486. return err;
  4487. if (is_pointer_value(env, BPF_REG_0)) {
  4488. verbose(env, "R0 leaks addr as return value\n");
  4489. return -EACCES;
  4490. }
  4491. err = check_return_code(env);
  4492. if (err)
  4493. return err;
  4494. process_bpf_exit:
  4495. err = pop_stack(env, &prev_insn_idx, &insn_idx);
  4496. if (err < 0) {
  4497. if (err != -ENOENT)
  4498. return err;
  4499. break;
  4500. } else {
  4501. do_print_state = true;
  4502. continue;
  4503. }
  4504. } else {
  4505. err = check_cond_jmp_op(env, insn, &insn_idx);
  4506. if (err)
  4507. return err;
  4508. }
  4509. } else if (class == BPF_LD) {
  4510. u8 mode = BPF_MODE(insn->code);
  4511. if (mode == BPF_ABS || mode == BPF_IND) {
  4512. err = check_ld_abs(env, insn);
  4513. if (err)
  4514. return err;
  4515. } else if (mode == BPF_IMM) {
  4516. err = check_ld_imm(env, insn);
  4517. if (err)
  4518. return err;
  4519. insn_idx++;
  4520. env->insn_aux_data[insn_idx].seen = true;
  4521. } else {
  4522. verbose(env, "invalid BPF_LD mode\n");
  4523. return -EINVAL;
  4524. }
  4525. } else {
  4526. verbose(env, "unknown insn class %d\n", class);
  4527. return -EINVAL;
  4528. }
  4529. insn_idx++;
  4530. }
  4531. verbose(env, "processed %d insns (limit %d), stack depth ",
  4532. insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
  4533. for (i = 0; i < env->subprog_cnt; i++) {
  4534. u32 depth = env->subprog_info[i].stack_depth;
  4535. verbose(env, "%d", depth);
  4536. if (i + 1 < env->subprog_cnt)
  4537. verbose(env, "+");
  4538. }
  4539. verbose(env, "\n");
  4540. env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
  4541. return 0;
  4542. }
  4543. static int check_map_prealloc(struct bpf_map *map)
  4544. {
  4545. return (map->map_type != BPF_MAP_TYPE_HASH &&
  4546. map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
  4547. map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
  4548. !(map->map_flags & BPF_F_NO_PREALLOC);
  4549. }
  4550. static int check_map_prog_compatibility(struct bpf_verifier_env *env,
  4551. struct bpf_map *map,
  4552. struct bpf_prog *prog)
  4553. {
  4554. /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
  4555. * preallocated hash maps, since doing memory allocation
  4556. * in overflow_handler can crash depending on where nmi got
  4557. * triggered.
  4558. */
  4559. if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
  4560. if (!check_map_prealloc(map)) {
  4561. verbose(env, "perf_event programs can only use preallocated hash map\n");
  4562. return -EINVAL;
  4563. }
  4564. if (map->inner_map_meta &&
  4565. !check_map_prealloc(map->inner_map_meta)) {
  4566. verbose(env, "perf_event programs can only use preallocated inner hash map\n");
  4567. return -EINVAL;
  4568. }
  4569. }
  4570. if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
  4571. !bpf_offload_dev_match(prog, map)) {
  4572. verbose(env, "offload device mismatch between prog and map\n");
  4573. return -EINVAL;
  4574. }
  4575. return 0;
  4576. }
  4577. /* look for pseudo eBPF instructions that access map FDs and
  4578. * replace them with actual map pointers
  4579. */
  4580. static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
  4581. {
  4582. struct bpf_insn *insn = env->prog->insnsi;
  4583. int insn_cnt = env->prog->len;
  4584. int i, j, err;
  4585. err = bpf_prog_calc_tag(env->prog);
  4586. if (err)
  4587. return err;
  4588. for (i = 0; i < insn_cnt; i++, insn++) {
  4589. if (BPF_CLASS(insn->code) == BPF_LDX &&
  4590. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  4591. verbose(env, "BPF_LDX uses reserved fields\n");
  4592. return -EINVAL;
  4593. }
  4594. if (BPF_CLASS(insn->code) == BPF_STX &&
  4595. ((BPF_MODE(insn->code) != BPF_MEM &&
  4596. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  4597. verbose(env, "BPF_STX uses reserved fields\n");
  4598. return -EINVAL;
  4599. }
  4600. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  4601. struct bpf_map *map;
  4602. struct fd f;
  4603. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  4604. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  4605. insn[1].off != 0) {
  4606. verbose(env, "invalid bpf_ld_imm64 insn\n");
  4607. return -EINVAL;
  4608. }
  4609. if (insn->src_reg == 0)
  4610. /* valid generic load 64-bit imm */
  4611. goto next_insn;
  4612. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  4613. verbose(env,
  4614. "unrecognized bpf_ld_imm64 insn\n");
  4615. return -EINVAL;
  4616. }
  4617. f = fdget(insn->imm);
  4618. map = __bpf_map_get(f);
  4619. if (IS_ERR(map)) {
  4620. verbose(env, "fd %d is not pointing to valid bpf_map\n",
  4621. insn->imm);
  4622. return PTR_ERR(map);
  4623. }
  4624. err = check_map_prog_compatibility(env, map, env->prog);
  4625. if (err) {
  4626. fdput(f);
  4627. return err;
  4628. }
  4629. /* store map pointer inside BPF_LD_IMM64 instruction */
  4630. insn[0].imm = (u32) (unsigned long) map;
  4631. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  4632. /* check whether we recorded this map already */
  4633. for (j = 0; j < env->used_map_cnt; j++)
  4634. if (env->used_maps[j] == map) {
  4635. fdput(f);
  4636. goto next_insn;
  4637. }
  4638. if (env->used_map_cnt >= MAX_USED_MAPS) {
  4639. fdput(f);
  4640. return -E2BIG;
  4641. }
  4642. /* hold the map. If the program is rejected by verifier,
  4643. * the map will be released by release_maps() or it
  4644. * will be used by the valid program until it's unloaded
  4645. * and all maps are released in free_used_maps()
  4646. */
  4647. map = bpf_map_inc(map, false);
  4648. if (IS_ERR(map)) {
  4649. fdput(f);
  4650. return PTR_ERR(map);
  4651. }
  4652. env->used_maps[env->used_map_cnt++] = map;
  4653. fdput(f);
  4654. next_insn:
  4655. insn++;
  4656. i++;
  4657. continue;
  4658. }
  4659. /* Basic sanity check before we invest more work here. */
  4660. if (!bpf_opcode_in_insntable(insn->code)) {
  4661. verbose(env, "unknown opcode %02x\n", insn->code);
  4662. return -EINVAL;
  4663. }
  4664. }
  4665. /* now all pseudo BPF_LD_IMM64 instructions load valid
  4666. * 'struct bpf_map *' into a register instead of user map_fd.
  4667. * These pointers will be used later by verifier to validate map access.
  4668. */
  4669. return 0;
  4670. }
  4671. /* drop refcnt of maps used by the rejected program */
  4672. static void release_maps(struct bpf_verifier_env *env)
  4673. {
  4674. int i;
  4675. for (i = 0; i < env->used_map_cnt; i++)
  4676. bpf_map_put(env->used_maps[i]);
  4677. }
  4678. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  4679. static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
  4680. {
  4681. struct bpf_insn *insn = env->prog->insnsi;
  4682. int insn_cnt = env->prog->len;
  4683. int i;
  4684. for (i = 0; i < insn_cnt; i++, insn++)
  4685. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  4686. insn->src_reg = 0;
  4687. }
  4688. /* single env->prog->insni[off] instruction was replaced with the range
  4689. * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
  4690. * [0, off) and [off, end) to new locations, so the patched range stays zero
  4691. */
  4692. static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
  4693. u32 off, u32 cnt)
  4694. {
  4695. struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
  4696. int i;
  4697. if (cnt == 1)
  4698. return 0;
  4699. new_data = vzalloc(array_size(prog_len,
  4700. sizeof(struct bpf_insn_aux_data)));
  4701. if (!new_data)
  4702. return -ENOMEM;
  4703. memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
  4704. memcpy(new_data + off + cnt - 1, old_data + off,
  4705. sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
  4706. for (i = off; i < off + cnt - 1; i++)
  4707. new_data[i].seen = true;
  4708. env->insn_aux_data = new_data;
  4709. vfree(old_data);
  4710. return 0;
  4711. }
  4712. static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
  4713. {
  4714. int i;
  4715. if (len == 1)
  4716. return;
  4717. /* NOTE: fake 'exit' subprog should be updated as well. */
  4718. for (i = 0; i <= env->subprog_cnt; i++) {
  4719. if (env->subprog_info[i].start < off)
  4720. continue;
  4721. env->subprog_info[i].start += len - 1;
  4722. }
  4723. }
  4724. static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
  4725. const struct bpf_insn *patch, u32 len)
  4726. {
  4727. struct bpf_prog *new_prog;
  4728. new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
  4729. if (!new_prog)
  4730. return NULL;
  4731. if (adjust_insn_aux_data(env, new_prog->len, off, len))
  4732. return NULL;
  4733. adjust_subprog_starts(env, off, len);
  4734. return new_prog;
  4735. }
  4736. /* The verifier does more data flow analysis than llvm and will not
  4737. * explore branches that are dead at run time. Malicious programs can
  4738. * have dead code too. Therefore replace all dead at-run-time code
  4739. * with 'ja -1'.
  4740. *
  4741. * Just nops are not optimal, e.g. if they would sit at the end of the
  4742. * program and through another bug we would manage to jump there, then
  4743. * we'd execute beyond program memory otherwise. Returning exception
  4744. * code also wouldn't work since we can have subprogs where the dead
  4745. * code could be located.
  4746. */
  4747. static void sanitize_dead_code(struct bpf_verifier_env *env)
  4748. {
  4749. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  4750. struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
  4751. struct bpf_insn *insn = env->prog->insnsi;
  4752. const int insn_cnt = env->prog->len;
  4753. int i;
  4754. for (i = 0; i < insn_cnt; i++) {
  4755. if (aux_data[i].seen)
  4756. continue;
  4757. memcpy(insn + i, &trap, sizeof(trap));
  4758. }
  4759. }
  4760. /* convert load instructions that access fields of 'struct __sk_buff'
  4761. * into sequence of instructions that access fields of 'struct sk_buff'
  4762. */
  4763. static int convert_ctx_accesses(struct bpf_verifier_env *env)
  4764. {
  4765. const struct bpf_verifier_ops *ops = env->ops;
  4766. int i, cnt, size, ctx_field_size, delta = 0;
  4767. const int insn_cnt = env->prog->len;
  4768. struct bpf_insn insn_buf[16], *insn;
  4769. struct bpf_prog *new_prog;
  4770. enum bpf_access_type type;
  4771. bool is_narrower_load;
  4772. u32 target_size;
  4773. if (ops->gen_prologue) {
  4774. cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
  4775. env->prog);
  4776. if (cnt >= ARRAY_SIZE(insn_buf)) {
  4777. verbose(env, "bpf verifier is misconfigured\n");
  4778. return -EINVAL;
  4779. } else if (cnt) {
  4780. new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
  4781. if (!new_prog)
  4782. return -ENOMEM;
  4783. env->prog = new_prog;
  4784. delta += cnt - 1;
  4785. }
  4786. }
  4787. if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
  4788. return 0;
  4789. insn = env->prog->insnsi + delta;
  4790. for (i = 0; i < insn_cnt; i++, insn++) {
  4791. if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
  4792. insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
  4793. insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  4794. insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
  4795. type = BPF_READ;
  4796. else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
  4797. insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
  4798. insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  4799. insn->code == (BPF_STX | BPF_MEM | BPF_DW))
  4800. type = BPF_WRITE;
  4801. else
  4802. continue;
  4803. if (type == BPF_WRITE &&
  4804. env->insn_aux_data[i + delta].sanitize_stack_off) {
  4805. struct bpf_insn patch[] = {
  4806. /* Sanitize suspicious stack slot with zero.
  4807. * There are no memory dependencies for this store,
  4808. * since it's only using frame pointer and immediate
  4809. * constant of zero
  4810. */
  4811. BPF_ST_MEM(BPF_DW, BPF_REG_FP,
  4812. env->insn_aux_data[i + delta].sanitize_stack_off,
  4813. 0),
  4814. /* the original STX instruction will immediately
  4815. * overwrite the same stack slot with appropriate value
  4816. */
  4817. *insn,
  4818. };
  4819. cnt = ARRAY_SIZE(patch);
  4820. new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
  4821. if (!new_prog)
  4822. return -ENOMEM;
  4823. delta += cnt - 1;
  4824. env->prog = new_prog;
  4825. insn = new_prog->insnsi + i + delta;
  4826. continue;
  4827. }
  4828. if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
  4829. continue;
  4830. ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
  4831. size = BPF_LDST_BYTES(insn);
  4832. /* If the read access is a narrower load of the field,
  4833. * convert to a 4/8-byte load, to minimum program type specific
  4834. * convert_ctx_access changes. If conversion is successful,
  4835. * we will apply proper mask to the result.
  4836. */
  4837. is_narrower_load = size < ctx_field_size;
  4838. if (is_narrower_load) {
  4839. u32 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
  4840. u32 off = insn->off;
  4841. u8 size_code;
  4842. if (type == BPF_WRITE) {
  4843. verbose(env, "bpf verifier narrow ctx access misconfigured\n");
  4844. return -EINVAL;
  4845. }
  4846. size_code = BPF_H;
  4847. if (ctx_field_size == 4)
  4848. size_code = BPF_W;
  4849. else if (ctx_field_size == 8)
  4850. size_code = BPF_DW;
  4851. insn->off = off & ~(size_default - 1);
  4852. insn->code = BPF_LDX | BPF_MEM | size_code;
  4853. }
  4854. target_size = 0;
  4855. cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
  4856. &target_size);
  4857. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
  4858. (ctx_field_size && !target_size)) {
  4859. verbose(env, "bpf verifier is misconfigured\n");
  4860. return -EINVAL;
  4861. }
  4862. if (is_narrower_load && size < target_size) {
  4863. if (ctx_field_size <= 4)
  4864. insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
  4865. (1 << size * 8) - 1);
  4866. else
  4867. insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
  4868. (1 << size * 8) - 1);
  4869. }
  4870. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  4871. if (!new_prog)
  4872. return -ENOMEM;
  4873. delta += cnt - 1;
  4874. /* keep walking new program and skip insns we just inserted */
  4875. env->prog = new_prog;
  4876. insn = new_prog->insnsi + i + delta;
  4877. }
  4878. return 0;
  4879. }
  4880. static int jit_subprogs(struct bpf_verifier_env *env)
  4881. {
  4882. struct bpf_prog *prog = env->prog, **func, *tmp;
  4883. int i, j, subprog_start, subprog_end = 0, len, subprog;
  4884. struct bpf_insn *insn;
  4885. void *old_bpf_func;
  4886. int err = -ENOMEM;
  4887. if (env->subprog_cnt <= 1)
  4888. return 0;
  4889. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  4890. if (insn->code != (BPF_JMP | BPF_CALL) ||
  4891. insn->src_reg != BPF_PSEUDO_CALL)
  4892. continue;
  4893. subprog = find_subprog(env, i + insn->imm + 1);
  4894. if (subprog < 0) {
  4895. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  4896. i + insn->imm + 1);
  4897. return -EFAULT;
  4898. }
  4899. /* temporarily remember subprog id inside insn instead of
  4900. * aux_data, since next loop will split up all insns into funcs
  4901. */
  4902. insn->off = subprog;
  4903. /* remember original imm in case JIT fails and fallback
  4904. * to interpreter will be needed
  4905. */
  4906. env->insn_aux_data[i].call_imm = insn->imm;
  4907. /* point imm to __bpf_call_base+1 from JITs point of view */
  4908. insn->imm = 1;
  4909. }
  4910. func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
  4911. if (!func)
  4912. return -ENOMEM;
  4913. for (i = 0; i < env->subprog_cnt; i++) {
  4914. subprog_start = subprog_end;
  4915. subprog_end = env->subprog_info[i + 1].start;
  4916. len = subprog_end - subprog_start;
  4917. func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
  4918. if (!func[i])
  4919. goto out_free;
  4920. memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
  4921. len * sizeof(struct bpf_insn));
  4922. func[i]->type = prog->type;
  4923. func[i]->len = len;
  4924. if (bpf_prog_calc_tag(func[i]))
  4925. goto out_free;
  4926. func[i]->is_func = 1;
  4927. /* Use bpf_prog_F_tag to indicate functions in stack traces.
  4928. * Long term would need debug info to populate names
  4929. */
  4930. func[i]->aux->name[0] = 'F';
  4931. func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
  4932. func[i]->jit_requested = 1;
  4933. func[i] = bpf_int_jit_compile(func[i]);
  4934. if (!func[i]->jited) {
  4935. err = -ENOTSUPP;
  4936. goto out_free;
  4937. }
  4938. cond_resched();
  4939. }
  4940. /* at this point all bpf functions were successfully JITed
  4941. * now populate all bpf_calls with correct addresses and
  4942. * run last pass of JIT
  4943. */
  4944. for (i = 0; i < env->subprog_cnt; i++) {
  4945. insn = func[i]->insnsi;
  4946. for (j = 0; j < func[i]->len; j++, insn++) {
  4947. if (insn->code != (BPF_JMP | BPF_CALL) ||
  4948. insn->src_reg != BPF_PSEUDO_CALL)
  4949. continue;
  4950. subprog = insn->off;
  4951. insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
  4952. func[subprog]->bpf_func -
  4953. __bpf_call_base;
  4954. }
  4955. /* we use the aux data to keep a list of the start addresses
  4956. * of the JITed images for each function in the program
  4957. *
  4958. * for some architectures, such as powerpc64, the imm field
  4959. * might not be large enough to hold the offset of the start
  4960. * address of the callee's JITed image from __bpf_call_base
  4961. *
  4962. * in such cases, we can lookup the start address of a callee
  4963. * by using its subprog id, available from the off field of
  4964. * the call instruction, as an index for this list
  4965. */
  4966. func[i]->aux->func = func;
  4967. func[i]->aux->func_cnt = env->subprog_cnt;
  4968. }
  4969. for (i = 0; i < env->subprog_cnt; i++) {
  4970. old_bpf_func = func[i]->bpf_func;
  4971. tmp = bpf_int_jit_compile(func[i]);
  4972. if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
  4973. verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
  4974. err = -EFAULT;
  4975. goto out_free;
  4976. }
  4977. cond_resched();
  4978. }
  4979. /* finally lock prog and jit images for all functions and
  4980. * populate kallsysm
  4981. */
  4982. for (i = 0; i < env->subprog_cnt; i++) {
  4983. bpf_prog_lock_ro(func[i]);
  4984. bpf_prog_kallsyms_add(func[i]);
  4985. }
  4986. /* Last step: make now unused interpreter insns from main
  4987. * prog consistent for later dump requests, so they can
  4988. * later look the same as if they were interpreted only.
  4989. */
  4990. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  4991. if (insn->code != (BPF_JMP | BPF_CALL) ||
  4992. insn->src_reg != BPF_PSEUDO_CALL)
  4993. continue;
  4994. insn->off = env->insn_aux_data[i].call_imm;
  4995. subprog = find_subprog(env, i + insn->off + 1);
  4996. insn->imm = subprog;
  4997. }
  4998. prog->jited = 1;
  4999. prog->bpf_func = func[0]->bpf_func;
  5000. prog->aux->func = func;
  5001. prog->aux->func_cnt = env->subprog_cnt;
  5002. return 0;
  5003. out_free:
  5004. for (i = 0; i < env->subprog_cnt; i++)
  5005. if (func[i])
  5006. bpf_jit_free(func[i]);
  5007. kfree(func);
  5008. /* cleanup main prog to be interpreted */
  5009. prog->jit_requested = 0;
  5010. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  5011. if (insn->code != (BPF_JMP | BPF_CALL) ||
  5012. insn->src_reg != BPF_PSEUDO_CALL)
  5013. continue;
  5014. insn->off = 0;
  5015. insn->imm = env->insn_aux_data[i].call_imm;
  5016. }
  5017. return err;
  5018. }
  5019. static int fixup_call_args(struct bpf_verifier_env *env)
  5020. {
  5021. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  5022. struct bpf_prog *prog = env->prog;
  5023. struct bpf_insn *insn = prog->insnsi;
  5024. int i, depth;
  5025. #endif
  5026. int err;
  5027. err = 0;
  5028. if (env->prog->jit_requested) {
  5029. err = jit_subprogs(env);
  5030. if (err == 0)
  5031. return 0;
  5032. }
  5033. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  5034. for (i = 0; i < prog->len; i++, insn++) {
  5035. if (insn->code != (BPF_JMP | BPF_CALL) ||
  5036. insn->src_reg != BPF_PSEUDO_CALL)
  5037. continue;
  5038. depth = get_callee_stack_depth(env, insn, i);
  5039. if (depth < 0)
  5040. return depth;
  5041. bpf_patch_call_args(insn, depth);
  5042. }
  5043. err = 0;
  5044. #endif
  5045. return err;
  5046. }
  5047. /* fixup insn->imm field of bpf_call instructions
  5048. * and inline eligible helpers as explicit sequence of BPF instructions
  5049. *
  5050. * this function is called after eBPF program passed verification
  5051. */
  5052. static int fixup_bpf_calls(struct bpf_verifier_env *env)
  5053. {
  5054. struct bpf_prog *prog = env->prog;
  5055. struct bpf_insn *insn = prog->insnsi;
  5056. const struct bpf_func_proto *fn;
  5057. const int insn_cnt = prog->len;
  5058. const struct bpf_map_ops *ops;
  5059. struct bpf_insn_aux_data *aux;
  5060. struct bpf_insn insn_buf[16];
  5061. struct bpf_prog *new_prog;
  5062. struct bpf_map *map_ptr;
  5063. int i, cnt, delta = 0;
  5064. for (i = 0; i < insn_cnt; i++, insn++) {
  5065. if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
  5066. insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
  5067. insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
  5068. insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
  5069. bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
  5070. struct bpf_insn mask_and_div[] = {
  5071. BPF_MOV32_REG(insn->src_reg, insn->src_reg),
  5072. /* Rx div 0 -> 0 */
  5073. BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
  5074. BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
  5075. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  5076. *insn,
  5077. };
  5078. struct bpf_insn mask_and_mod[] = {
  5079. BPF_MOV32_REG(insn->src_reg, insn->src_reg),
  5080. /* Rx mod 0 -> Rx */
  5081. BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
  5082. *insn,
  5083. };
  5084. struct bpf_insn *patchlet;
  5085. if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
  5086. insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
  5087. patchlet = mask_and_div + (is64 ? 1 : 0);
  5088. cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
  5089. } else {
  5090. patchlet = mask_and_mod + (is64 ? 1 : 0);
  5091. cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
  5092. }
  5093. new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
  5094. if (!new_prog)
  5095. return -ENOMEM;
  5096. delta += cnt - 1;
  5097. env->prog = prog = new_prog;
  5098. insn = new_prog->insnsi + i + delta;
  5099. continue;
  5100. }
  5101. if (BPF_CLASS(insn->code) == BPF_LD &&
  5102. (BPF_MODE(insn->code) == BPF_ABS ||
  5103. BPF_MODE(insn->code) == BPF_IND)) {
  5104. cnt = env->ops->gen_ld_abs(insn, insn_buf);
  5105. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  5106. verbose(env, "bpf verifier is misconfigured\n");
  5107. return -EINVAL;
  5108. }
  5109. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  5110. if (!new_prog)
  5111. return -ENOMEM;
  5112. delta += cnt - 1;
  5113. env->prog = prog = new_prog;
  5114. insn = new_prog->insnsi + i + delta;
  5115. continue;
  5116. }
  5117. if (insn->code != (BPF_JMP | BPF_CALL))
  5118. continue;
  5119. if (insn->src_reg == BPF_PSEUDO_CALL)
  5120. continue;
  5121. if (insn->imm == BPF_FUNC_get_route_realm)
  5122. prog->dst_needed = 1;
  5123. if (insn->imm == BPF_FUNC_get_prandom_u32)
  5124. bpf_user_rnd_init_once();
  5125. if (insn->imm == BPF_FUNC_override_return)
  5126. prog->kprobe_override = 1;
  5127. if (insn->imm == BPF_FUNC_tail_call) {
  5128. /* If we tail call into other programs, we
  5129. * cannot make any assumptions since they can
  5130. * be replaced dynamically during runtime in
  5131. * the program array.
  5132. */
  5133. prog->cb_access = 1;
  5134. env->prog->aux->stack_depth = MAX_BPF_STACK;
  5135. /* mark bpf_tail_call as different opcode to avoid
  5136. * conditional branch in the interpeter for every normal
  5137. * call and to prevent accidental JITing by JIT compiler
  5138. * that doesn't support bpf_tail_call yet
  5139. */
  5140. insn->imm = 0;
  5141. insn->code = BPF_JMP | BPF_TAIL_CALL;
  5142. aux = &env->insn_aux_data[i + delta];
  5143. if (!bpf_map_ptr_unpriv(aux))
  5144. continue;
  5145. /* instead of changing every JIT dealing with tail_call
  5146. * emit two extra insns:
  5147. * if (index >= max_entries) goto out;
  5148. * index &= array->index_mask;
  5149. * to avoid out-of-bounds cpu speculation
  5150. */
  5151. if (bpf_map_ptr_poisoned(aux)) {
  5152. verbose(env, "tail_call abusing map_ptr\n");
  5153. return -EINVAL;
  5154. }
  5155. map_ptr = BPF_MAP_PTR(aux->map_state);
  5156. insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
  5157. map_ptr->max_entries, 2);
  5158. insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
  5159. container_of(map_ptr,
  5160. struct bpf_array,
  5161. map)->index_mask);
  5162. insn_buf[2] = *insn;
  5163. cnt = 3;
  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. /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
  5173. * and other inlining handlers are currently limited to 64 bit
  5174. * only.
  5175. */
  5176. if (prog->jit_requested && BITS_PER_LONG == 64 &&
  5177. (insn->imm == BPF_FUNC_map_lookup_elem ||
  5178. insn->imm == BPF_FUNC_map_update_elem ||
  5179. insn->imm == BPF_FUNC_map_delete_elem)) {
  5180. aux = &env->insn_aux_data[i + delta];
  5181. if (bpf_map_ptr_poisoned(aux))
  5182. goto patch_call_imm;
  5183. map_ptr = BPF_MAP_PTR(aux->map_state);
  5184. ops = map_ptr->ops;
  5185. if (insn->imm == BPF_FUNC_map_lookup_elem &&
  5186. ops->map_gen_lookup) {
  5187. cnt = ops->map_gen_lookup(map_ptr, insn_buf);
  5188. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  5189. verbose(env, "bpf verifier is misconfigured\n");
  5190. return -EINVAL;
  5191. }
  5192. new_prog = bpf_patch_insn_data(env, i + delta,
  5193. insn_buf, cnt);
  5194. if (!new_prog)
  5195. return -ENOMEM;
  5196. delta += cnt - 1;
  5197. env->prog = prog = new_prog;
  5198. insn = new_prog->insnsi + i + delta;
  5199. continue;
  5200. }
  5201. BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
  5202. (void *(*)(struct bpf_map *map, void *key))NULL));
  5203. BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
  5204. (int (*)(struct bpf_map *map, void *key))NULL));
  5205. BUILD_BUG_ON(!__same_type(ops->map_update_elem,
  5206. (int (*)(struct bpf_map *map, void *key, void *value,
  5207. u64 flags))NULL));
  5208. switch (insn->imm) {
  5209. case BPF_FUNC_map_lookup_elem:
  5210. insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
  5211. __bpf_call_base;
  5212. continue;
  5213. case BPF_FUNC_map_update_elem:
  5214. insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
  5215. __bpf_call_base;
  5216. continue;
  5217. case BPF_FUNC_map_delete_elem:
  5218. insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
  5219. __bpf_call_base;
  5220. continue;
  5221. }
  5222. goto patch_call_imm;
  5223. }
  5224. if (insn->imm == BPF_FUNC_redirect_map) {
  5225. /* Note, we cannot use prog directly as imm as subsequent
  5226. * rewrites would still change the prog pointer. The only
  5227. * stable address we can use is aux, which also works with
  5228. * prog clones during blinding.
  5229. */
  5230. u64 addr = (unsigned long)prog->aux;
  5231. struct bpf_insn r4_ld[] = {
  5232. BPF_LD_IMM64(BPF_REG_4, addr),
  5233. *insn,
  5234. };
  5235. cnt = ARRAY_SIZE(r4_ld);
  5236. new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
  5237. if (!new_prog)
  5238. return -ENOMEM;
  5239. delta += cnt - 1;
  5240. env->prog = prog = new_prog;
  5241. insn = new_prog->insnsi + i + delta;
  5242. }
  5243. patch_call_imm:
  5244. fn = env->ops->get_func_proto(insn->imm, env->prog);
  5245. /* all functions that have prototype and verifier allowed
  5246. * programs to call them, must be real in-kernel functions
  5247. */
  5248. if (!fn->func) {
  5249. verbose(env,
  5250. "kernel subsystem misconfigured func %s#%d\n",
  5251. func_id_name(insn->imm), insn->imm);
  5252. return -EFAULT;
  5253. }
  5254. insn->imm = fn->func - __bpf_call_base;
  5255. }
  5256. return 0;
  5257. }
  5258. static void free_states(struct bpf_verifier_env *env)
  5259. {
  5260. struct bpf_verifier_state_list *sl, *sln;
  5261. int i;
  5262. if (!env->explored_states)
  5263. return;
  5264. for (i = 0; i < env->prog->len; i++) {
  5265. sl = env->explored_states[i];
  5266. if (sl)
  5267. while (sl != STATE_LIST_MARK) {
  5268. sln = sl->next;
  5269. free_verifier_state(&sl->state, false);
  5270. kfree(sl);
  5271. sl = sln;
  5272. }
  5273. }
  5274. kfree(env->explored_states);
  5275. }
  5276. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  5277. {
  5278. struct bpf_verifier_env *env;
  5279. struct bpf_verifier_log *log;
  5280. int ret = -EINVAL;
  5281. /* no program is valid */
  5282. if (ARRAY_SIZE(bpf_verifier_ops) == 0)
  5283. return -EINVAL;
  5284. /* 'struct bpf_verifier_env' can be global, but since it's not small,
  5285. * allocate/free it every time bpf_check() is called
  5286. */
  5287. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  5288. if (!env)
  5289. return -ENOMEM;
  5290. log = &env->log;
  5291. env->insn_aux_data =
  5292. vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
  5293. (*prog)->len));
  5294. ret = -ENOMEM;
  5295. if (!env->insn_aux_data)
  5296. goto err_free_env;
  5297. env->prog = *prog;
  5298. env->ops = bpf_verifier_ops[env->prog->type];
  5299. /* grab the mutex to protect few globals used by verifier */
  5300. mutex_lock(&bpf_verifier_lock);
  5301. if (attr->log_level || attr->log_buf || attr->log_size) {
  5302. /* user requested verbose verifier output
  5303. * and supplied buffer to store the verification trace
  5304. */
  5305. log->level = attr->log_level;
  5306. log->ubuf = (char __user *) (unsigned long) attr->log_buf;
  5307. log->len_total = attr->log_size;
  5308. ret = -EINVAL;
  5309. /* log attributes have to be sane */
  5310. if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
  5311. !log->level || !log->ubuf)
  5312. goto err_unlock;
  5313. }
  5314. env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
  5315. if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
  5316. env->strict_alignment = true;
  5317. ret = replace_map_fd_with_map_ptr(env);
  5318. if (ret < 0)
  5319. goto skip_full_check;
  5320. if (bpf_prog_is_dev_bound(env->prog->aux)) {
  5321. ret = bpf_prog_offload_verifier_prep(env);
  5322. if (ret)
  5323. goto skip_full_check;
  5324. }
  5325. env->explored_states = kcalloc(env->prog->len,
  5326. sizeof(struct bpf_verifier_state_list *),
  5327. GFP_USER);
  5328. ret = -ENOMEM;
  5329. if (!env->explored_states)
  5330. goto skip_full_check;
  5331. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  5332. ret = check_cfg(env);
  5333. if (ret < 0)
  5334. goto skip_full_check;
  5335. ret = do_check(env);
  5336. if (env->cur_state) {
  5337. free_verifier_state(env->cur_state, true);
  5338. env->cur_state = NULL;
  5339. }
  5340. skip_full_check:
  5341. while (!pop_stack(env, NULL, NULL));
  5342. free_states(env);
  5343. if (ret == 0)
  5344. sanitize_dead_code(env);
  5345. if (ret == 0)
  5346. ret = check_max_stack_depth(env);
  5347. if (ret == 0)
  5348. /* program is valid, convert *(u32*)(ctx + off) accesses */
  5349. ret = convert_ctx_accesses(env);
  5350. if (ret == 0)
  5351. ret = fixup_bpf_calls(env);
  5352. if (ret == 0)
  5353. ret = fixup_call_args(env);
  5354. if (log->level && bpf_verifier_log_full(log))
  5355. ret = -ENOSPC;
  5356. if (log->level && !log->ubuf) {
  5357. ret = -EFAULT;
  5358. goto err_release_maps;
  5359. }
  5360. if (ret == 0 && env->used_map_cnt) {
  5361. /* if program passed verifier, update used_maps in bpf_prog_info */
  5362. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  5363. sizeof(env->used_maps[0]),
  5364. GFP_KERNEL);
  5365. if (!env->prog->aux->used_maps) {
  5366. ret = -ENOMEM;
  5367. goto err_release_maps;
  5368. }
  5369. memcpy(env->prog->aux->used_maps, env->used_maps,
  5370. sizeof(env->used_maps[0]) * env->used_map_cnt);
  5371. env->prog->aux->used_map_cnt = env->used_map_cnt;
  5372. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  5373. * bpf_ld_imm64 instructions
  5374. */
  5375. convert_pseudo_ld_imm64(env);
  5376. }
  5377. err_release_maps:
  5378. if (!env->prog->aux->used_maps)
  5379. /* if we didn't copy map pointers into bpf_prog_info, release
  5380. * them now. Otherwise free_used_maps() will release them.
  5381. */
  5382. release_maps(env);
  5383. *prog = env->prog;
  5384. err_unlock:
  5385. mutex_unlock(&bpf_verifier_lock);
  5386. vfree(env->insn_aux_data);
  5387. err_free_env:
  5388. kfree(env);
  5389. return ret;
  5390. }