verifier.c 135 KB

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