verifier.c 152 KB

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