verifier.c 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628
  1. /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  2. * Copyright (c) 2016 Facebook
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of version 2 of the GNU General Public
  6. * License as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful, but
  9. * WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * General Public License for more details.
  12. */
  13. #include <linux/kernel.h>
  14. #include <linux/types.h>
  15. #include <linux/slab.h>
  16. #include <linux/bpf.h>
  17. #include <linux/bpf_verifier.h>
  18. #include <linux/filter.h>
  19. #include <net/netlink.h>
  20. #include <linux/file.h>
  21. #include <linux/vmalloc.h>
  22. #include <linux/stringify.h>
  23. /* bpf_check() is a static code analyzer that walks eBPF program
  24. * instruction by instruction and updates register/stack state.
  25. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  26. *
  27. * The first pass is depth-first-search to check that the program is a DAG.
  28. * It rejects the following programs:
  29. * - larger than BPF_MAXINSNS insns
  30. * - if loop is present (detected via back-edge)
  31. * - unreachable insns exist (shouldn't be a forest. program = one function)
  32. * - out of bounds or malformed jumps
  33. * The second pass is all possible path descent from the 1st insn.
  34. * Since it's analyzing all pathes through the program, the length of the
  35. * analysis is limited to 64k insn, which may be hit even if total number of
  36. * insn is less then 4K, but there are too many branches that change stack/regs.
  37. * Number of 'branches to be analyzed' is limited to 1k
  38. *
  39. * On entry to each instruction, each register has a type, and the instruction
  40. * changes the types of the registers depending on instruction semantics.
  41. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  42. * copied to R1.
  43. *
  44. * All registers are 64-bit.
  45. * R0 - return register
  46. * R1-R5 argument passing registers
  47. * R6-R9 callee saved registers
  48. * R10 - frame pointer read-only
  49. *
  50. * At the start of BPF program the register R1 contains a pointer to bpf_context
  51. * and has type PTR_TO_CTX.
  52. *
  53. * Verifier tracks arithmetic operations on pointers in case:
  54. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  55. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  56. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  57. * and 2nd arithmetic instruction is pattern matched to recognize
  58. * that it wants to construct a pointer to some element within stack.
  59. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  60. * (and -20 constant is saved for further stack bounds checking).
  61. * Meaning that this reg is a pointer to stack plus known immediate constant.
  62. *
  63. * Most of the time the registers have UNKNOWN_VALUE type, which
  64. * means the register has some value, but it's not a valid pointer.
  65. * (like pointer plus pointer becomes UNKNOWN_VALUE type)
  66. *
  67. * When verifier sees load or store instructions the type of base register
  68. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
  69. * types recognized by check_mem_access() function.
  70. *
  71. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  72. * and the range of [ptr, ptr + map's value_size) is accessible.
  73. *
  74. * registers used to pass values to function calls are checked against
  75. * function argument constraints.
  76. *
  77. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  78. * It means that the register type passed to this function must be
  79. * PTR_TO_STACK and it will be used inside the function as
  80. * 'pointer to map element key'
  81. *
  82. * For example the argument constraints for bpf_map_lookup_elem():
  83. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  84. * .arg1_type = ARG_CONST_MAP_PTR,
  85. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  86. *
  87. * ret_type says that this function returns 'pointer to map elem value or null'
  88. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  89. * 2nd argument should be a pointer to stack, which will be used inside
  90. * the helper function as a pointer to map element key.
  91. *
  92. * On the kernel side the helper function looks like:
  93. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  94. * {
  95. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  96. * void *key = (void *) (unsigned long) r2;
  97. * void *value;
  98. *
  99. * here kernel can access 'key' and 'map' pointers safely, knowing that
  100. * [key, key + map->key_size) bytes are valid and were initialized on
  101. * the stack of eBPF program.
  102. * }
  103. *
  104. * Corresponding eBPF program may look like:
  105. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  106. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  107. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  108. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  109. * here verifier looks at prototype of map_lookup_elem() and sees:
  110. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  111. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  112. *
  113. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  114. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  115. * and were initialized prior to this call.
  116. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  117. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  118. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  119. * returns ether pointer to map value or NULL.
  120. *
  121. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  122. * insn, the register holding that pointer in the true branch changes state to
  123. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  124. * branch. See check_cond_jmp_op().
  125. *
  126. * After the call R0 is set to return type of the function and registers R1-R5
  127. * are set to NOT_INIT to indicate that they are no longer readable.
  128. */
  129. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  130. struct bpf_verifier_stack_elem {
  131. /* verifer state is 'st'
  132. * before processing instruction 'insn_idx'
  133. * and after processing instruction 'prev_insn_idx'
  134. */
  135. struct bpf_verifier_state st;
  136. int insn_idx;
  137. int prev_insn_idx;
  138. struct bpf_verifier_stack_elem *next;
  139. };
  140. #define BPF_COMPLEXITY_LIMIT_INSNS 65536
  141. #define BPF_COMPLEXITY_LIMIT_STACK 1024
  142. #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
  143. struct bpf_call_arg_meta {
  144. struct bpf_map *map_ptr;
  145. bool raw_mode;
  146. bool pkt_access;
  147. int regno;
  148. int access_size;
  149. };
  150. /* verbose verifier prints what it's seeing
  151. * bpf_check() is called under lock, so no race to access these global vars
  152. */
  153. static u32 log_level, log_size, log_len;
  154. static char *log_buf;
  155. static DEFINE_MUTEX(bpf_verifier_lock);
  156. /* log_level controls verbosity level of eBPF verifier.
  157. * verbose() is used to dump the verification trace to the log, so the user
  158. * can figure out what's wrong with the program
  159. */
  160. static __printf(1, 2) void verbose(const char *fmt, ...)
  161. {
  162. va_list args;
  163. if (log_level == 0 || log_len >= log_size - 1)
  164. return;
  165. va_start(args, fmt);
  166. log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
  167. va_end(args);
  168. }
  169. /* string representation of 'enum bpf_reg_type' */
  170. static const char * const reg_type_str[] = {
  171. [NOT_INIT] = "?",
  172. [UNKNOWN_VALUE] = "inv",
  173. [PTR_TO_CTX] = "ctx",
  174. [CONST_PTR_TO_MAP] = "map_ptr",
  175. [PTR_TO_MAP_VALUE] = "map_value",
  176. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  177. [PTR_TO_MAP_VALUE_ADJ] = "map_value_adj",
  178. [FRAME_PTR] = "fp",
  179. [PTR_TO_STACK] = "fp",
  180. [CONST_IMM] = "imm",
  181. [PTR_TO_PACKET] = "pkt",
  182. [PTR_TO_PACKET_END] = "pkt_end",
  183. };
  184. #define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
  185. static const char * const func_id_str[] = {
  186. __BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
  187. };
  188. #undef __BPF_FUNC_STR_FN
  189. static const char *func_id_name(int id)
  190. {
  191. BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID);
  192. if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id])
  193. return func_id_str[id];
  194. else
  195. return "unknown";
  196. }
  197. static void print_verifier_state(struct bpf_verifier_state *state)
  198. {
  199. struct bpf_reg_state *reg;
  200. enum bpf_reg_type t;
  201. int i;
  202. for (i = 0; i < MAX_BPF_REG; i++) {
  203. reg = &state->regs[i];
  204. t = reg->type;
  205. if (t == NOT_INIT)
  206. continue;
  207. verbose(" R%d=%s", i, reg_type_str[t]);
  208. if (t == CONST_IMM || t == PTR_TO_STACK)
  209. verbose("%lld", reg->imm);
  210. else if (t == PTR_TO_PACKET)
  211. verbose("(id=%d,off=%d,r=%d)",
  212. reg->id, reg->off, reg->range);
  213. else if (t == UNKNOWN_VALUE && reg->imm)
  214. verbose("%lld", reg->imm);
  215. else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
  216. t == PTR_TO_MAP_VALUE_OR_NULL ||
  217. t == PTR_TO_MAP_VALUE_ADJ)
  218. verbose("(ks=%d,vs=%d,id=%u)",
  219. reg->map_ptr->key_size,
  220. reg->map_ptr->value_size,
  221. reg->id);
  222. if (reg->min_value != BPF_REGISTER_MIN_RANGE)
  223. verbose(",min_value=%lld",
  224. (long long)reg->min_value);
  225. if (reg->max_value != BPF_REGISTER_MAX_RANGE)
  226. verbose(",max_value=%llu",
  227. (unsigned long long)reg->max_value);
  228. }
  229. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  230. if (state->stack_slot_type[i] == STACK_SPILL)
  231. verbose(" fp%d=%s", -MAX_BPF_STACK + i,
  232. reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
  233. }
  234. verbose("\n");
  235. }
  236. static const char *const bpf_class_string[] = {
  237. [BPF_LD] = "ld",
  238. [BPF_LDX] = "ldx",
  239. [BPF_ST] = "st",
  240. [BPF_STX] = "stx",
  241. [BPF_ALU] = "alu",
  242. [BPF_JMP] = "jmp",
  243. [BPF_RET] = "BUG",
  244. [BPF_ALU64] = "alu64",
  245. };
  246. static const char *const bpf_alu_string[16] = {
  247. [BPF_ADD >> 4] = "+=",
  248. [BPF_SUB >> 4] = "-=",
  249. [BPF_MUL >> 4] = "*=",
  250. [BPF_DIV >> 4] = "/=",
  251. [BPF_OR >> 4] = "|=",
  252. [BPF_AND >> 4] = "&=",
  253. [BPF_LSH >> 4] = "<<=",
  254. [BPF_RSH >> 4] = ">>=",
  255. [BPF_NEG >> 4] = "neg",
  256. [BPF_MOD >> 4] = "%=",
  257. [BPF_XOR >> 4] = "^=",
  258. [BPF_MOV >> 4] = "=",
  259. [BPF_ARSH >> 4] = "s>>=",
  260. [BPF_END >> 4] = "endian",
  261. };
  262. static const char *const bpf_ldst_string[] = {
  263. [BPF_W >> 3] = "u32",
  264. [BPF_H >> 3] = "u16",
  265. [BPF_B >> 3] = "u8",
  266. [BPF_DW >> 3] = "u64",
  267. };
  268. static const char *const bpf_jmp_string[16] = {
  269. [BPF_JA >> 4] = "jmp",
  270. [BPF_JEQ >> 4] = "==",
  271. [BPF_JGT >> 4] = ">",
  272. [BPF_JGE >> 4] = ">=",
  273. [BPF_JSET >> 4] = "&",
  274. [BPF_JNE >> 4] = "!=",
  275. [BPF_JSGT >> 4] = "s>",
  276. [BPF_JSGE >> 4] = "s>=",
  277. [BPF_CALL >> 4] = "call",
  278. [BPF_EXIT >> 4] = "exit",
  279. };
  280. static void print_bpf_insn(const struct bpf_verifier_env *env,
  281. const struct bpf_insn *insn)
  282. {
  283. u8 class = BPF_CLASS(insn->code);
  284. if (class == BPF_ALU || class == BPF_ALU64) {
  285. if (BPF_SRC(insn->code) == BPF_X)
  286. verbose("(%02x) %sr%d %s %sr%d\n",
  287. insn->code, class == BPF_ALU ? "(u32) " : "",
  288. insn->dst_reg,
  289. bpf_alu_string[BPF_OP(insn->code) >> 4],
  290. class == BPF_ALU ? "(u32) " : "",
  291. insn->src_reg);
  292. else
  293. verbose("(%02x) %sr%d %s %s%d\n",
  294. insn->code, class == BPF_ALU ? "(u32) " : "",
  295. insn->dst_reg,
  296. bpf_alu_string[BPF_OP(insn->code) >> 4],
  297. class == BPF_ALU ? "(u32) " : "",
  298. insn->imm);
  299. } else if (class == BPF_STX) {
  300. if (BPF_MODE(insn->code) == BPF_MEM)
  301. verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
  302. insn->code,
  303. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  304. insn->dst_reg,
  305. insn->off, insn->src_reg);
  306. else if (BPF_MODE(insn->code) == BPF_XADD)
  307. verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
  308. insn->code,
  309. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  310. insn->dst_reg, insn->off,
  311. insn->src_reg);
  312. else
  313. verbose("BUG_%02x\n", insn->code);
  314. } else if (class == BPF_ST) {
  315. if (BPF_MODE(insn->code) != BPF_MEM) {
  316. verbose("BUG_st_%02x\n", insn->code);
  317. return;
  318. }
  319. verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
  320. insn->code,
  321. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  322. insn->dst_reg,
  323. insn->off, insn->imm);
  324. } else if (class == BPF_LDX) {
  325. if (BPF_MODE(insn->code) != BPF_MEM) {
  326. verbose("BUG_ldx_%02x\n", insn->code);
  327. return;
  328. }
  329. verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
  330. insn->code, insn->dst_reg,
  331. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  332. insn->src_reg, insn->off);
  333. } else if (class == BPF_LD) {
  334. if (BPF_MODE(insn->code) == BPF_ABS) {
  335. verbose("(%02x) r0 = *(%s *)skb[%d]\n",
  336. insn->code,
  337. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  338. insn->imm);
  339. } else if (BPF_MODE(insn->code) == BPF_IND) {
  340. verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
  341. insn->code,
  342. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  343. insn->src_reg, insn->imm);
  344. } else if (BPF_MODE(insn->code) == BPF_IMM &&
  345. BPF_SIZE(insn->code) == BPF_DW) {
  346. /* At this point, we already made sure that the second
  347. * part of the ldimm64 insn is accessible.
  348. */
  349. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  350. bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
  351. if (map_ptr && !env->allow_ptr_leaks)
  352. imm = 0;
  353. verbose("(%02x) r%d = 0x%llx\n", insn->code,
  354. insn->dst_reg, (unsigned long long)imm);
  355. } else {
  356. verbose("BUG_ld_%02x\n", insn->code);
  357. return;
  358. }
  359. } else if (class == BPF_JMP) {
  360. u8 opcode = BPF_OP(insn->code);
  361. if (opcode == BPF_CALL) {
  362. verbose("(%02x) call %s#%d\n", insn->code,
  363. func_id_name(insn->imm), insn->imm);
  364. } else if (insn->code == (BPF_JMP | BPF_JA)) {
  365. verbose("(%02x) goto pc%+d\n",
  366. insn->code, insn->off);
  367. } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
  368. verbose("(%02x) exit\n", insn->code);
  369. } else if (BPF_SRC(insn->code) == BPF_X) {
  370. verbose("(%02x) if r%d %s r%d goto pc%+d\n",
  371. insn->code, insn->dst_reg,
  372. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  373. insn->src_reg, insn->off);
  374. } else {
  375. verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
  376. insn->code, insn->dst_reg,
  377. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  378. insn->imm, insn->off);
  379. }
  380. } else {
  381. verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
  382. }
  383. }
  384. static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
  385. {
  386. struct bpf_verifier_stack_elem *elem;
  387. int insn_idx;
  388. if (env->head == NULL)
  389. return -1;
  390. memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
  391. insn_idx = env->head->insn_idx;
  392. if (prev_insn_idx)
  393. *prev_insn_idx = env->head->prev_insn_idx;
  394. elem = env->head->next;
  395. kfree(env->head);
  396. env->head = elem;
  397. env->stack_size--;
  398. return insn_idx;
  399. }
  400. static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
  401. int insn_idx, int prev_insn_idx)
  402. {
  403. struct bpf_verifier_stack_elem *elem;
  404. elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
  405. if (!elem)
  406. goto err;
  407. memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
  408. elem->insn_idx = insn_idx;
  409. elem->prev_insn_idx = prev_insn_idx;
  410. elem->next = env->head;
  411. env->head = elem;
  412. env->stack_size++;
  413. if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
  414. verbose("BPF program is too complex\n");
  415. goto err;
  416. }
  417. return &elem->st;
  418. err:
  419. /* pop all elements and return */
  420. while (pop_stack(env, NULL) >= 0);
  421. return NULL;
  422. }
  423. #define CALLER_SAVED_REGS 6
  424. static const int caller_saved[CALLER_SAVED_REGS] = {
  425. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  426. };
  427. static void init_reg_state(struct bpf_reg_state *regs)
  428. {
  429. int i;
  430. for (i = 0; i < MAX_BPF_REG; i++) {
  431. regs[i].type = NOT_INIT;
  432. regs[i].imm = 0;
  433. regs[i].min_value = BPF_REGISTER_MIN_RANGE;
  434. regs[i].max_value = BPF_REGISTER_MAX_RANGE;
  435. }
  436. /* frame pointer */
  437. regs[BPF_REG_FP].type = FRAME_PTR;
  438. /* 1st arg to a function */
  439. regs[BPF_REG_1].type = PTR_TO_CTX;
  440. }
  441. static void __mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
  442. {
  443. regs[regno].type = UNKNOWN_VALUE;
  444. regs[regno].id = 0;
  445. regs[regno].imm = 0;
  446. }
  447. static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
  448. {
  449. BUG_ON(regno >= MAX_BPF_REG);
  450. __mark_reg_unknown_value(regs, regno);
  451. }
  452. static void reset_reg_range_values(struct bpf_reg_state *regs, u32 regno)
  453. {
  454. regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
  455. regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
  456. }
  457. static void mark_reg_unknown_value_and_range(struct bpf_reg_state *regs,
  458. u32 regno)
  459. {
  460. mark_reg_unknown_value(regs, regno);
  461. reset_reg_range_values(regs, regno);
  462. }
  463. enum reg_arg_type {
  464. SRC_OP, /* register is used as source operand */
  465. DST_OP, /* register is used as destination operand */
  466. DST_OP_NO_MARK /* same as above, check only, don't mark */
  467. };
  468. static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
  469. enum reg_arg_type t)
  470. {
  471. if (regno >= MAX_BPF_REG) {
  472. verbose("R%d is invalid\n", regno);
  473. return -EINVAL;
  474. }
  475. if (t == SRC_OP) {
  476. /* check whether register used as source operand can be read */
  477. if (regs[regno].type == NOT_INIT) {
  478. verbose("R%d !read_ok\n", regno);
  479. return -EACCES;
  480. }
  481. } else {
  482. /* check whether register used as dest operand can be written to */
  483. if (regno == BPF_REG_FP) {
  484. verbose("frame pointer is read only\n");
  485. return -EACCES;
  486. }
  487. if (t == DST_OP)
  488. mark_reg_unknown_value(regs, regno);
  489. }
  490. return 0;
  491. }
  492. static int bpf_size_to_bytes(int bpf_size)
  493. {
  494. if (bpf_size == BPF_W)
  495. return 4;
  496. else if (bpf_size == BPF_H)
  497. return 2;
  498. else if (bpf_size == BPF_B)
  499. return 1;
  500. else if (bpf_size == BPF_DW)
  501. return 8;
  502. else
  503. return -EINVAL;
  504. }
  505. static bool is_spillable_regtype(enum bpf_reg_type type)
  506. {
  507. switch (type) {
  508. case PTR_TO_MAP_VALUE:
  509. case PTR_TO_MAP_VALUE_OR_NULL:
  510. case PTR_TO_MAP_VALUE_ADJ:
  511. case PTR_TO_STACK:
  512. case PTR_TO_CTX:
  513. case PTR_TO_PACKET:
  514. case PTR_TO_PACKET_END:
  515. case FRAME_PTR:
  516. case CONST_PTR_TO_MAP:
  517. return true;
  518. default:
  519. return false;
  520. }
  521. }
  522. /* check_stack_read/write functions track spill/fill of registers,
  523. * stack boundary and alignment are checked in check_mem_access()
  524. */
  525. static int check_stack_write(struct bpf_verifier_state *state, int off,
  526. int size, int value_regno)
  527. {
  528. int i;
  529. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  530. * so it's aligned access and [off, off + size) are within stack limits
  531. */
  532. if (value_regno >= 0 &&
  533. is_spillable_regtype(state->regs[value_regno].type)) {
  534. /* register containing pointer is being spilled into stack */
  535. if (size != BPF_REG_SIZE) {
  536. verbose("invalid size of register spill\n");
  537. return -EACCES;
  538. }
  539. /* save register state */
  540. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
  541. state->regs[value_regno];
  542. for (i = 0; i < BPF_REG_SIZE; i++)
  543. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
  544. } else {
  545. /* regular write of data into stack */
  546. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
  547. (struct bpf_reg_state) {};
  548. for (i = 0; i < size; i++)
  549. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
  550. }
  551. return 0;
  552. }
  553. static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
  554. int value_regno)
  555. {
  556. u8 *slot_type;
  557. int i;
  558. slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
  559. if (slot_type[0] == STACK_SPILL) {
  560. if (size != BPF_REG_SIZE) {
  561. verbose("invalid size of register spill\n");
  562. return -EACCES;
  563. }
  564. for (i = 1; i < BPF_REG_SIZE; i++) {
  565. if (slot_type[i] != STACK_SPILL) {
  566. verbose("corrupted spill memory\n");
  567. return -EACCES;
  568. }
  569. }
  570. if (value_regno >= 0)
  571. /* restore register state from stack */
  572. state->regs[value_regno] =
  573. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
  574. return 0;
  575. } else {
  576. for (i = 0; i < size; i++) {
  577. if (slot_type[i] != STACK_MISC) {
  578. verbose("invalid read from stack off %d+%d size %d\n",
  579. off, i, size);
  580. return -EACCES;
  581. }
  582. }
  583. if (value_regno >= 0)
  584. /* have read misc data from the stack */
  585. mark_reg_unknown_value_and_range(state->regs,
  586. value_regno);
  587. return 0;
  588. }
  589. }
  590. /* check read/write into map element returned by bpf_map_lookup_elem() */
  591. static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
  592. int size)
  593. {
  594. struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
  595. if (off < 0 || size <= 0 || off + size > map->value_size) {
  596. verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
  597. map->value_size, off, size);
  598. return -EACCES;
  599. }
  600. return 0;
  601. }
  602. /* check read/write into an adjusted map element */
  603. static int check_map_access_adj(struct bpf_verifier_env *env, u32 regno,
  604. int off, int size)
  605. {
  606. struct bpf_verifier_state *state = &env->cur_state;
  607. struct bpf_reg_state *reg = &state->regs[regno];
  608. int err;
  609. /* We adjusted the register to this map value, so we
  610. * need to change off and size to min_value and max_value
  611. * respectively to make sure our theoretical access will be
  612. * safe.
  613. */
  614. if (log_level)
  615. print_verifier_state(state);
  616. env->varlen_map_value_access = true;
  617. /* The minimum value is only important with signed
  618. * comparisons where we can't assume the floor of a
  619. * value is 0. If we are using signed variables for our
  620. * index'es we need to make sure that whatever we use
  621. * will have a set floor within our range.
  622. */
  623. if (reg->min_value < 0) {
  624. verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  625. regno);
  626. return -EACCES;
  627. }
  628. err = check_map_access(env, regno, reg->min_value + off, size);
  629. if (err) {
  630. verbose("R%d min value is outside of the array range\n",
  631. regno);
  632. return err;
  633. }
  634. /* If we haven't set a max value then we need to bail
  635. * since we can't be sure we won't do bad things.
  636. */
  637. if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
  638. verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
  639. regno);
  640. return -EACCES;
  641. }
  642. return check_map_access(env, regno, reg->max_value + off, size);
  643. }
  644. #define MAX_PACKET_OFF 0xffff
  645. static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
  646. const struct bpf_call_arg_meta *meta,
  647. enum bpf_access_type t)
  648. {
  649. switch (env->prog->type) {
  650. case BPF_PROG_TYPE_LWT_IN:
  651. case BPF_PROG_TYPE_LWT_OUT:
  652. /* dst_input() and dst_output() can't write for now */
  653. if (t == BPF_WRITE)
  654. return false;
  655. /* fallthrough */
  656. case BPF_PROG_TYPE_SCHED_CLS:
  657. case BPF_PROG_TYPE_SCHED_ACT:
  658. case BPF_PROG_TYPE_XDP:
  659. case BPF_PROG_TYPE_LWT_XMIT:
  660. if (meta)
  661. return meta->pkt_access;
  662. env->seen_direct_write = true;
  663. return true;
  664. default:
  665. return false;
  666. }
  667. }
  668. static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
  669. int size)
  670. {
  671. struct bpf_reg_state *regs = env->cur_state.regs;
  672. struct bpf_reg_state *reg = &regs[regno];
  673. off += reg->off;
  674. if (off < 0 || size <= 0 || off + size > reg->range) {
  675. verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
  676. off, size, regno, reg->id, reg->off, reg->range);
  677. return -EACCES;
  678. }
  679. return 0;
  680. }
  681. /* check access to 'struct bpf_context' fields */
  682. static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
  683. enum bpf_access_type t, enum bpf_reg_type *reg_type)
  684. {
  685. /* for analyzer ctx accesses are already validated and converted */
  686. if (env->analyzer_ops)
  687. return 0;
  688. if (env->prog->aux->ops->is_valid_access &&
  689. env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
  690. /* remember the offset of last byte accessed in ctx */
  691. if (env->prog->aux->max_ctx_offset < off + size)
  692. env->prog->aux->max_ctx_offset = off + size;
  693. return 0;
  694. }
  695. verbose("invalid bpf_context access off=%d size=%d\n", off, size);
  696. return -EACCES;
  697. }
  698. static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
  699. {
  700. if (env->allow_ptr_leaks)
  701. return false;
  702. switch (env->cur_state.regs[regno].type) {
  703. case UNKNOWN_VALUE:
  704. case CONST_IMM:
  705. return false;
  706. default:
  707. return true;
  708. }
  709. }
  710. static int check_pkt_ptr_alignment(const struct bpf_reg_state *reg,
  711. int off, int size)
  712. {
  713. if (reg->id && size != 1) {
  714. verbose("Unknown alignment. Only byte-sized access allowed in packet access.\n");
  715. return -EACCES;
  716. }
  717. /* skb->data is NET_IP_ALIGN-ed */
  718. if ((NET_IP_ALIGN + reg->off + off) % size != 0) {
  719. verbose("misaligned packet access off %d+%d+%d size %d\n",
  720. NET_IP_ALIGN, reg->off, off, size);
  721. return -EACCES;
  722. }
  723. return 0;
  724. }
  725. static int check_val_ptr_alignment(const struct bpf_reg_state *reg,
  726. int size)
  727. {
  728. if (size != 1) {
  729. verbose("Unknown alignment. Only byte-sized access allowed in value access.\n");
  730. return -EACCES;
  731. }
  732. return 0;
  733. }
  734. static int check_ptr_alignment(const struct bpf_reg_state *reg,
  735. int off, int size)
  736. {
  737. switch (reg->type) {
  738. case PTR_TO_PACKET:
  739. return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ? 0 :
  740. check_pkt_ptr_alignment(reg, off, size);
  741. case PTR_TO_MAP_VALUE_ADJ:
  742. return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ? 0 :
  743. check_val_ptr_alignment(reg, size);
  744. default:
  745. if (off % size != 0) {
  746. verbose("misaligned access off %d size %d\n",
  747. off, size);
  748. return -EACCES;
  749. }
  750. return 0;
  751. }
  752. }
  753. /* check whether memory at (regno + off) is accessible for t = (read | write)
  754. * if t==write, value_regno is a register which value is stored into memory
  755. * if t==read, value_regno is a register which will receive the value from memory
  756. * if t==write && value_regno==-1, some unknown value is stored into memory
  757. * if t==read && value_regno==-1, don't care what we read from memory
  758. */
  759. static int check_mem_access(struct bpf_verifier_env *env, u32 regno, int off,
  760. int bpf_size, enum bpf_access_type t,
  761. int value_regno)
  762. {
  763. struct bpf_verifier_state *state = &env->cur_state;
  764. struct bpf_reg_state *reg = &state->regs[regno];
  765. int size, err = 0;
  766. if (reg->type == PTR_TO_STACK)
  767. off += reg->imm;
  768. size = bpf_size_to_bytes(bpf_size);
  769. if (size < 0)
  770. return size;
  771. err = check_ptr_alignment(reg, off, size);
  772. if (err)
  773. return err;
  774. if (reg->type == PTR_TO_MAP_VALUE ||
  775. reg->type == PTR_TO_MAP_VALUE_ADJ) {
  776. if (t == BPF_WRITE && value_regno >= 0 &&
  777. is_pointer_value(env, value_regno)) {
  778. verbose("R%d leaks addr into map\n", value_regno);
  779. return -EACCES;
  780. }
  781. if (reg->type == PTR_TO_MAP_VALUE_ADJ)
  782. err = check_map_access_adj(env, regno, off, size);
  783. else
  784. err = check_map_access(env, regno, off, size);
  785. if (!err && t == BPF_READ && value_regno >= 0)
  786. mark_reg_unknown_value_and_range(state->regs,
  787. value_regno);
  788. } else if (reg->type == PTR_TO_CTX) {
  789. enum bpf_reg_type reg_type = UNKNOWN_VALUE;
  790. if (t == BPF_WRITE && value_regno >= 0 &&
  791. is_pointer_value(env, value_regno)) {
  792. verbose("R%d leaks addr into ctx\n", value_regno);
  793. return -EACCES;
  794. }
  795. err = check_ctx_access(env, off, size, t, &reg_type);
  796. if (!err && t == BPF_READ && value_regno >= 0) {
  797. mark_reg_unknown_value_and_range(state->regs,
  798. value_regno);
  799. /* note that reg.[id|off|range] == 0 */
  800. state->regs[value_regno].type = reg_type;
  801. }
  802. } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
  803. if (off >= 0 || off < -MAX_BPF_STACK) {
  804. verbose("invalid stack off=%d size=%d\n", off, size);
  805. return -EACCES;
  806. }
  807. if (t == BPF_WRITE) {
  808. if (!env->allow_ptr_leaks &&
  809. state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
  810. size != BPF_REG_SIZE) {
  811. verbose("attempt to corrupt spilled pointer on stack\n");
  812. return -EACCES;
  813. }
  814. err = check_stack_write(state, off, size, value_regno);
  815. } else {
  816. err = check_stack_read(state, off, size, value_regno);
  817. }
  818. } else if (state->regs[regno].type == PTR_TO_PACKET) {
  819. if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
  820. verbose("cannot write into packet\n");
  821. return -EACCES;
  822. }
  823. if (t == BPF_WRITE && value_regno >= 0 &&
  824. is_pointer_value(env, value_regno)) {
  825. verbose("R%d leaks addr into packet\n", value_regno);
  826. return -EACCES;
  827. }
  828. err = check_packet_access(env, regno, off, size);
  829. if (!err && t == BPF_READ && value_regno >= 0)
  830. mark_reg_unknown_value_and_range(state->regs,
  831. value_regno);
  832. } else {
  833. verbose("R%d invalid mem access '%s'\n",
  834. regno, reg_type_str[reg->type]);
  835. return -EACCES;
  836. }
  837. if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
  838. state->regs[value_regno].type == UNKNOWN_VALUE) {
  839. /* 1 or 2 byte load zero-extends, determine the number of
  840. * zero upper bits. Not doing it fo 4 byte load, since
  841. * such values cannot be added to ptr_to_packet anyway.
  842. */
  843. state->regs[value_regno].imm = 64 - size * 8;
  844. }
  845. return err;
  846. }
  847. static int check_xadd(struct bpf_verifier_env *env, struct bpf_insn *insn)
  848. {
  849. struct bpf_reg_state *regs = env->cur_state.regs;
  850. int err;
  851. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  852. insn->imm != 0) {
  853. verbose("BPF_XADD uses reserved fields\n");
  854. return -EINVAL;
  855. }
  856. /* check src1 operand */
  857. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  858. if (err)
  859. return err;
  860. /* check src2 operand */
  861. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  862. if (err)
  863. return err;
  864. /* check whether atomic_add can read the memory */
  865. err = check_mem_access(env, insn->dst_reg, insn->off,
  866. BPF_SIZE(insn->code), BPF_READ, -1);
  867. if (err)
  868. return err;
  869. /* check whether atomic_add can write into the same memory */
  870. return check_mem_access(env, insn->dst_reg, insn->off,
  871. BPF_SIZE(insn->code), BPF_WRITE, -1);
  872. }
  873. /* when register 'regno' is passed into function that will read 'access_size'
  874. * bytes from that pointer, make sure that it's within stack boundary
  875. * and all elements of stack are initialized
  876. */
  877. static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
  878. int access_size, bool zero_size_allowed,
  879. struct bpf_call_arg_meta *meta)
  880. {
  881. struct bpf_verifier_state *state = &env->cur_state;
  882. struct bpf_reg_state *regs = state->regs;
  883. int off, i;
  884. if (regs[regno].type != PTR_TO_STACK) {
  885. if (zero_size_allowed && access_size == 0 &&
  886. regs[regno].type == CONST_IMM &&
  887. regs[regno].imm == 0)
  888. return 0;
  889. verbose("R%d type=%s expected=%s\n", regno,
  890. reg_type_str[regs[regno].type],
  891. reg_type_str[PTR_TO_STACK]);
  892. return -EACCES;
  893. }
  894. off = regs[regno].imm;
  895. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  896. access_size <= 0) {
  897. verbose("invalid stack type R%d off=%d access_size=%d\n",
  898. regno, off, access_size);
  899. return -EACCES;
  900. }
  901. if (meta && meta->raw_mode) {
  902. meta->access_size = access_size;
  903. meta->regno = regno;
  904. return 0;
  905. }
  906. for (i = 0; i < access_size; i++) {
  907. if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
  908. verbose("invalid indirect read from stack off %d+%d size %d\n",
  909. off, i, access_size);
  910. return -EACCES;
  911. }
  912. }
  913. return 0;
  914. }
  915. static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
  916. int access_size, bool zero_size_allowed,
  917. struct bpf_call_arg_meta *meta)
  918. {
  919. struct bpf_reg_state *regs = env->cur_state.regs;
  920. switch (regs[regno].type) {
  921. case PTR_TO_PACKET:
  922. return check_packet_access(env, regno, 0, access_size);
  923. case PTR_TO_MAP_VALUE:
  924. return check_map_access(env, regno, 0, access_size);
  925. case PTR_TO_MAP_VALUE_ADJ:
  926. return check_map_access_adj(env, regno, 0, access_size);
  927. default: /* const_imm|ptr_to_stack or invalid ptr */
  928. return check_stack_boundary(env, regno, access_size,
  929. zero_size_allowed, meta);
  930. }
  931. }
  932. static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
  933. enum bpf_arg_type arg_type,
  934. struct bpf_call_arg_meta *meta)
  935. {
  936. struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
  937. enum bpf_reg_type expected_type, type = reg->type;
  938. int err = 0;
  939. if (arg_type == ARG_DONTCARE)
  940. return 0;
  941. if (type == NOT_INIT) {
  942. verbose("R%d !read_ok\n", regno);
  943. return -EACCES;
  944. }
  945. if (arg_type == ARG_ANYTHING) {
  946. if (is_pointer_value(env, regno)) {
  947. verbose("R%d leaks addr into helper function\n", regno);
  948. return -EACCES;
  949. }
  950. return 0;
  951. }
  952. if (type == PTR_TO_PACKET &&
  953. !may_access_direct_pkt_data(env, meta, BPF_READ)) {
  954. verbose("helper access to the packet is not allowed\n");
  955. return -EACCES;
  956. }
  957. if (arg_type == ARG_PTR_TO_MAP_KEY ||
  958. arg_type == ARG_PTR_TO_MAP_VALUE) {
  959. expected_type = PTR_TO_STACK;
  960. if (type != PTR_TO_PACKET && type != expected_type)
  961. goto err_type;
  962. } else if (arg_type == ARG_CONST_SIZE ||
  963. arg_type == ARG_CONST_SIZE_OR_ZERO) {
  964. expected_type = CONST_IMM;
  965. /* One exception. Allow UNKNOWN_VALUE registers when the
  966. * boundaries are known and don't cause unsafe memory accesses
  967. */
  968. if (type != UNKNOWN_VALUE && type != expected_type)
  969. goto err_type;
  970. } else if (arg_type == ARG_CONST_MAP_PTR) {
  971. expected_type = CONST_PTR_TO_MAP;
  972. if (type != expected_type)
  973. goto err_type;
  974. } else if (arg_type == ARG_PTR_TO_CTX) {
  975. expected_type = PTR_TO_CTX;
  976. if (type != expected_type)
  977. goto err_type;
  978. } else if (arg_type == ARG_PTR_TO_MEM ||
  979. arg_type == ARG_PTR_TO_UNINIT_MEM) {
  980. expected_type = PTR_TO_STACK;
  981. /* One exception here. In case function allows for NULL to be
  982. * passed in as argument, it's a CONST_IMM type. Final test
  983. * happens during stack boundary checking.
  984. */
  985. if (type == CONST_IMM && reg->imm == 0)
  986. /* final test in check_stack_boundary() */;
  987. else if (type != PTR_TO_PACKET && type != PTR_TO_MAP_VALUE &&
  988. type != PTR_TO_MAP_VALUE_ADJ && type != expected_type)
  989. goto err_type;
  990. meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
  991. } else {
  992. verbose("unsupported arg_type %d\n", arg_type);
  993. return -EFAULT;
  994. }
  995. if (arg_type == ARG_CONST_MAP_PTR) {
  996. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  997. meta->map_ptr = reg->map_ptr;
  998. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  999. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  1000. * check that [key, key + map->key_size) are within
  1001. * stack limits and initialized
  1002. */
  1003. if (!meta->map_ptr) {
  1004. /* in function declaration map_ptr must come before
  1005. * map_key, so that it's verified and known before
  1006. * we have to check map_key here. Otherwise it means
  1007. * that kernel subsystem misconfigured verifier
  1008. */
  1009. verbose("invalid map_ptr to access map->key\n");
  1010. return -EACCES;
  1011. }
  1012. if (type == PTR_TO_PACKET)
  1013. err = check_packet_access(env, regno, 0,
  1014. meta->map_ptr->key_size);
  1015. else
  1016. err = check_stack_boundary(env, regno,
  1017. meta->map_ptr->key_size,
  1018. false, NULL);
  1019. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  1020. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  1021. * check [value, value + map->value_size) validity
  1022. */
  1023. if (!meta->map_ptr) {
  1024. /* kernel subsystem misconfigured verifier */
  1025. verbose("invalid map_ptr to access map->value\n");
  1026. return -EACCES;
  1027. }
  1028. if (type == PTR_TO_PACKET)
  1029. err = check_packet_access(env, regno, 0,
  1030. meta->map_ptr->value_size);
  1031. else
  1032. err = check_stack_boundary(env, regno,
  1033. meta->map_ptr->value_size,
  1034. false, NULL);
  1035. } else if (arg_type == ARG_CONST_SIZE ||
  1036. arg_type == ARG_CONST_SIZE_OR_ZERO) {
  1037. bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
  1038. /* bpf_xxx(..., buf, len) call will access 'len' bytes
  1039. * from stack pointer 'buf'. Check it
  1040. * note: regno == len, regno - 1 == buf
  1041. */
  1042. if (regno == 0) {
  1043. /* kernel subsystem misconfigured verifier */
  1044. verbose("ARG_CONST_SIZE cannot be first argument\n");
  1045. return -EACCES;
  1046. }
  1047. /* If the register is UNKNOWN_VALUE, the access check happens
  1048. * using its boundaries. Otherwise, just use its imm
  1049. */
  1050. if (type == UNKNOWN_VALUE) {
  1051. /* For unprivileged variable accesses, disable raw
  1052. * mode so that the program is required to
  1053. * initialize all the memory that the helper could
  1054. * just partially fill up.
  1055. */
  1056. meta = NULL;
  1057. if (reg->min_value < 0) {
  1058. verbose("R%d min value is negative, either use unsigned or 'var &= const'\n",
  1059. regno);
  1060. return -EACCES;
  1061. }
  1062. if (reg->min_value == 0) {
  1063. err = check_helper_mem_access(env, regno - 1, 0,
  1064. zero_size_allowed,
  1065. meta);
  1066. if (err)
  1067. return err;
  1068. }
  1069. if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
  1070. verbose("R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
  1071. regno);
  1072. return -EACCES;
  1073. }
  1074. err = check_helper_mem_access(env, regno - 1,
  1075. reg->max_value,
  1076. zero_size_allowed, meta);
  1077. if (err)
  1078. return err;
  1079. } else {
  1080. /* register is CONST_IMM */
  1081. err = check_helper_mem_access(env, regno - 1, reg->imm,
  1082. zero_size_allowed, meta);
  1083. }
  1084. }
  1085. return err;
  1086. err_type:
  1087. verbose("R%d type=%s expected=%s\n", regno,
  1088. reg_type_str[type], reg_type_str[expected_type]);
  1089. return -EACCES;
  1090. }
  1091. static int check_map_func_compatibility(struct bpf_map *map, int func_id)
  1092. {
  1093. if (!map)
  1094. return 0;
  1095. /* We need a two way check, first is from map perspective ... */
  1096. switch (map->map_type) {
  1097. case BPF_MAP_TYPE_PROG_ARRAY:
  1098. if (func_id != BPF_FUNC_tail_call)
  1099. goto error;
  1100. break;
  1101. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  1102. if (func_id != BPF_FUNC_perf_event_read &&
  1103. func_id != BPF_FUNC_perf_event_output)
  1104. goto error;
  1105. break;
  1106. case BPF_MAP_TYPE_STACK_TRACE:
  1107. if (func_id != BPF_FUNC_get_stackid)
  1108. goto error;
  1109. break;
  1110. case BPF_MAP_TYPE_CGROUP_ARRAY:
  1111. if (func_id != BPF_FUNC_skb_under_cgroup &&
  1112. func_id != BPF_FUNC_current_task_under_cgroup)
  1113. goto error;
  1114. break;
  1115. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  1116. case BPF_MAP_TYPE_HASH_OF_MAPS:
  1117. if (func_id != BPF_FUNC_map_lookup_elem)
  1118. goto error;
  1119. default:
  1120. break;
  1121. }
  1122. /* ... and second from the function itself. */
  1123. switch (func_id) {
  1124. case BPF_FUNC_tail_call:
  1125. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  1126. goto error;
  1127. break;
  1128. case BPF_FUNC_perf_event_read:
  1129. case BPF_FUNC_perf_event_output:
  1130. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  1131. goto error;
  1132. break;
  1133. case BPF_FUNC_get_stackid:
  1134. if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
  1135. goto error;
  1136. break;
  1137. case BPF_FUNC_current_task_under_cgroup:
  1138. case BPF_FUNC_skb_under_cgroup:
  1139. if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
  1140. goto error;
  1141. break;
  1142. default:
  1143. break;
  1144. }
  1145. return 0;
  1146. error:
  1147. verbose("cannot pass map_type %d into func %s#%d\n",
  1148. map->map_type, func_id_name(func_id), func_id);
  1149. return -EINVAL;
  1150. }
  1151. static int check_raw_mode(const struct bpf_func_proto *fn)
  1152. {
  1153. int count = 0;
  1154. if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
  1155. count++;
  1156. if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
  1157. count++;
  1158. if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
  1159. count++;
  1160. if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
  1161. count++;
  1162. if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
  1163. count++;
  1164. return count > 1 ? -EINVAL : 0;
  1165. }
  1166. static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
  1167. {
  1168. struct bpf_verifier_state *state = &env->cur_state;
  1169. struct bpf_reg_state *regs = state->regs, *reg;
  1170. int i;
  1171. for (i = 0; i < MAX_BPF_REG; i++)
  1172. if (regs[i].type == PTR_TO_PACKET ||
  1173. regs[i].type == PTR_TO_PACKET_END)
  1174. mark_reg_unknown_value(regs, i);
  1175. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  1176. if (state->stack_slot_type[i] != STACK_SPILL)
  1177. continue;
  1178. reg = &state->spilled_regs[i / BPF_REG_SIZE];
  1179. if (reg->type != PTR_TO_PACKET &&
  1180. reg->type != PTR_TO_PACKET_END)
  1181. continue;
  1182. reg->type = UNKNOWN_VALUE;
  1183. reg->imm = 0;
  1184. }
  1185. }
  1186. static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
  1187. {
  1188. struct bpf_verifier_state *state = &env->cur_state;
  1189. const struct bpf_func_proto *fn = NULL;
  1190. struct bpf_reg_state *regs = state->regs;
  1191. struct bpf_reg_state *reg;
  1192. struct bpf_call_arg_meta meta;
  1193. bool changes_data;
  1194. int i, err;
  1195. /* find function prototype */
  1196. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  1197. verbose("invalid func %s#%d\n", func_id_name(func_id), func_id);
  1198. return -EINVAL;
  1199. }
  1200. if (env->prog->aux->ops->get_func_proto)
  1201. fn = env->prog->aux->ops->get_func_proto(func_id);
  1202. if (!fn) {
  1203. verbose("unknown func %s#%d\n", func_id_name(func_id), func_id);
  1204. return -EINVAL;
  1205. }
  1206. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  1207. if (!env->prog->gpl_compatible && fn->gpl_only) {
  1208. verbose("cannot call GPL only function from proprietary program\n");
  1209. return -EINVAL;
  1210. }
  1211. changes_data = bpf_helper_changes_pkt_data(fn->func);
  1212. memset(&meta, 0, sizeof(meta));
  1213. meta.pkt_access = fn->pkt_access;
  1214. /* We only support one arg being in raw mode at the moment, which
  1215. * is sufficient for the helper functions we have right now.
  1216. */
  1217. err = check_raw_mode(fn);
  1218. if (err) {
  1219. verbose("kernel subsystem misconfigured func %s#%d\n",
  1220. func_id_name(func_id), func_id);
  1221. return err;
  1222. }
  1223. /* check args */
  1224. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
  1225. if (err)
  1226. return err;
  1227. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
  1228. if (err)
  1229. return err;
  1230. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
  1231. if (err)
  1232. return err;
  1233. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
  1234. if (err)
  1235. return err;
  1236. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
  1237. if (err)
  1238. return err;
  1239. /* Mark slots with STACK_MISC in case of raw mode, stack offset
  1240. * is inferred from register state.
  1241. */
  1242. for (i = 0; i < meta.access_size; i++) {
  1243. err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
  1244. if (err)
  1245. return err;
  1246. }
  1247. /* reset caller saved regs */
  1248. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  1249. reg = regs + caller_saved[i];
  1250. reg->type = NOT_INIT;
  1251. reg->imm = 0;
  1252. }
  1253. /* update return register */
  1254. if (fn->ret_type == RET_INTEGER) {
  1255. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  1256. } else if (fn->ret_type == RET_VOID) {
  1257. regs[BPF_REG_0].type = NOT_INIT;
  1258. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  1259. struct bpf_insn_aux_data *insn_aux;
  1260. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  1261. regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0;
  1262. /* remember map_ptr, so that check_map_access()
  1263. * can check 'value_size' boundary of memory access
  1264. * to map element returned from bpf_map_lookup_elem()
  1265. */
  1266. if (meta.map_ptr == NULL) {
  1267. verbose("kernel subsystem misconfigured verifier\n");
  1268. return -EINVAL;
  1269. }
  1270. regs[BPF_REG_0].map_ptr = meta.map_ptr;
  1271. regs[BPF_REG_0].id = ++env->id_gen;
  1272. insn_aux = &env->insn_aux_data[insn_idx];
  1273. if (!insn_aux->map_ptr)
  1274. insn_aux->map_ptr = meta.map_ptr;
  1275. else if (insn_aux->map_ptr != meta.map_ptr)
  1276. insn_aux->map_ptr = BPF_MAP_PTR_POISON;
  1277. } else {
  1278. verbose("unknown return type %d of func %s#%d\n",
  1279. fn->ret_type, func_id_name(func_id), func_id);
  1280. return -EINVAL;
  1281. }
  1282. err = check_map_func_compatibility(meta.map_ptr, func_id);
  1283. if (err)
  1284. return err;
  1285. if (changes_data)
  1286. clear_all_pkt_pointers(env);
  1287. return 0;
  1288. }
  1289. static int check_packet_ptr_add(struct bpf_verifier_env *env,
  1290. struct bpf_insn *insn)
  1291. {
  1292. struct bpf_reg_state *regs = env->cur_state.regs;
  1293. struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
  1294. struct bpf_reg_state *src_reg = &regs[insn->src_reg];
  1295. struct bpf_reg_state tmp_reg;
  1296. s32 imm;
  1297. if (BPF_SRC(insn->code) == BPF_K) {
  1298. /* pkt_ptr += imm */
  1299. imm = insn->imm;
  1300. add_imm:
  1301. if (imm < 0) {
  1302. verbose("addition of negative constant to packet pointer is not allowed\n");
  1303. return -EACCES;
  1304. }
  1305. if (imm >= MAX_PACKET_OFF ||
  1306. imm + dst_reg->off >= MAX_PACKET_OFF) {
  1307. verbose("constant %d is too large to add to packet pointer\n",
  1308. imm);
  1309. return -EACCES;
  1310. }
  1311. /* a constant was added to pkt_ptr.
  1312. * Remember it while keeping the same 'id'
  1313. */
  1314. dst_reg->off += imm;
  1315. } else {
  1316. if (src_reg->type == PTR_TO_PACKET) {
  1317. /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
  1318. tmp_reg = *dst_reg; /* save r7 state */
  1319. *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
  1320. src_reg = &tmp_reg; /* pretend it's src_reg state */
  1321. /* if the checks below reject it, the copy won't matter,
  1322. * since we're rejecting the whole program. If all ok,
  1323. * then imm22 state will be added to r7
  1324. * and r7 will be pkt(id=0,off=22,r=62) while
  1325. * r6 will stay as pkt(id=0,off=0,r=62)
  1326. */
  1327. }
  1328. if (src_reg->type == CONST_IMM) {
  1329. /* pkt_ptr += reg where reg is known constant */
  1330. imm = src_reg->imm;
  1331. goto add_imm;
  1332. }
  1333. /* disallow pkt_ptr += reg
  1334. * if reg is not uknown_value with guaranteed zero upper bits
  1335. * otherwise pkt_ptr may overflow and addition will become
  1336. * subtraction which is not allowed
  1337. */
  1338. if (src_reg->type != UNKNOWN_VALUE) {
  1339. verbose("cannot add '%s' to ptr_to_packet\n",
  1340. reg_type_str[src_reg->type]);
  1341. return -EACCES;
  1342. }
  1343. if (src_reg->imm < 48) {
  1344. verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
  1345. src_reg->imm);
  1346. return -EACCES;
  1347. }
  1348. /* dst_reg stays as pkt_ptr type and since some positive
  1349. * integer value was added to the pointer, increment its 'id'
  1350. */
  1351. dst_reg->id = ++env->id_gen;
  1352. /* something was added to pkt_ptr, set range and off to zero */
  1353. dst_reg->off = 0;
  1354. dst_reg->range = 0;
  1355. }
  1356. return 0;
  1357. }
  1358. static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
  1359. {
  1360. struct bpf_reg_state *regs = env->cur_state.regs;
  1361. struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
  1362. u8 opcode = BPF_OP(insn->code);
  1363. s64 imm_log2;
  1364. /* for type == UNKNOWN_VALUE:
  1365. * imm > 0 -> number of zero upper bits
  1366. * imm == 0 -> don't track which is the same as all bits can be non-zero
  1367. */
  1368. if (BPF_SRC(insn->code) == BPF_X) {
  1369. struct bpf_reg_state *src_reg = &regs[insn->src_reg];
  1370. if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
  1371. dst_reg->imm && opcode == BPF_ADD) {
  1372. /* dreg += sreg
  1373. * where both have zero upper bits. Adding them
  1374. * can only result making one more bit non-zero
  1375. * in the larger value.
  1376. * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
  1377. * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
  1378. */
  1379. dst_reg->imm = min(dst_reg->imm, src_reg->imm);
  1380. dst_reg->imm--;
  1381. return 0;
  1382. }
  1383. if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
  1384. dst_reg->imm && opcode == BPF_ADD) {
  1385. /* dreg += sreg
  1386. * where dreg has zero upper bits and sreg is const.
  1387. * Adding them can only result making one more bit
  1388. * non-zero in the larger value.
  1389. */
  1390. imm_log2 = __ilog2_u64((long long)src_reg->imm);
  1391. dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
  1392. dst_reg->imm--;
  1393. return 0;
  1394. }
  1395. /* all other cases non supported yet, just mark dst_reg */
  1396. dst_reg->imm = 0;
  1397. return 0;
  1398. }
  1399. /* sign extend 32-bit imm into 64-bit to make sure that
  1400. * negative values occupy bit 63. Note ilog2() would have
  1401. * been incorrect, since sizeof(insn->imm) == 4
  1402. */
  1403. imm_log2 = __ilog2_u64((long long)insn->imm);
  1404. if (dst_reg->imm && opcode == BPF_LSH) {
  1405. /* reg <<= imm
  1406. * if reg was a result of 2 byte load, then its imm == 48
  1407. * which means that upper 48 bits are zero and shifting this reg
  1408. * left by 4 would mean that upper 44 bits are still zero
  1409. */
  1410. dst_reg->imm -= insn->imm;
  1411. } else if (dst_reg->imm && opcode == BPF_MUL) {
  1412. /* reg *= imm
  1413. * if multiplying by 14 subtract 4
  1414. * This is conservative calculation of upper zero bits.
  1415. * It's not trying to special case insn->imm == 1 or 0 cases
  1416. */
  1417. dst_reg->imm -= imm_log2 + 1;
  1418. } else if (opcode == BPF_AND) {
  1419. /* reg &= imm */
  1420. dst_reg->imm = 63 - imm_log2;
  1421. } else if (dst_reg->imm && opcode == BPF_ADD) {
  1422. /* reg += imm */
  1423. dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
  1424. dst_reg->imm--;
  1425. } else if (opcode == BPF_RSH) {
  1426. /* reg >>= imm
  1427. * which means that after right shift, upper bits will be zero
  1428. * note that verifier already checked that
  1429. * 0 <= imm < 64 for shift insn
  1430. */
  1431. dst_reg->imm += insn->imm;
  1432. if (unlikely(dst_reg->imm > 64))
  1433. /* some dumb code did:
  1434. * r2 = *(u32 *)mem;
  1435. * r2 >>= 32;
  1436. * and all bits are zero now */
  1437. dst_reg->imm = 64;
  1438. } else {
  1439. /* all other alu ops, means that we don't know what will
  1440. * happen to the value, mark it with unknown number of zero bits
  1441. */
  1442. dst_reg->imm = 0;
  1443. }
  1444. if (dst_reg->imm < 0) {
  1445. /* all 64 bits of the register can contain non-zero bits
  1446. * and such value cannot be added to ptr_to_packet, since it
  1447. * may overflow, mark it as unknown to avoid further eval
  1448. */
  1449. dst_reg->imm = 0;
  1450. }
  1451. return 0;
  1452. }
  1453. static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
  1454. struct bpf_insn *insn)
  1455. {
  1456. struct bpf_reg_state *regs = env->cur_state.regs;
  1457. struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
  1458. struct bpf_reg_state *src_reg = &regs[insn->src_reg];
  1459. u8 opcode = BPF_OP(insn->code);
  1460. u64 dst_imm = dst_reg->imm;
  1461. /* dst_reg->type == CONST_IMM here. Simulate execution of insns
  1462. * containing ALU ops. Don't care about overflow or negative
  1463. * values, just add/sub/... them; registers are in u64.
  1464. */
  1465. if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K) {
  1466. dst_imm += insn->imm;
  1467. } else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
  1468. src_reg->type == CONST_IMM) {
  1469. dst_imm += src_reg->imm;
  1470. } else if (opcode == BPF_SUB && BPF_SRC(insn->code) == BPF_K) {
  1471. dst_imm -= insn->imm;
  1472. } else if (opcode == BPF_SUB && BPF_SRC(insn->code) == BPF_X &&
  1473. src_reg->type == CONST_IMM) {
  1474. dst_imm -= src_reg->imm;
  1475. } else if (opcode == BPF_MUL && BPF_SRC(insn->code) == BPF_K) {
  1476. dst_imm *= insn->imm;
  1477. } else if (opcode == BPF_MUL && BPF_SRC(insn->code) == BPF_X &&
  1478. src_reg->type == CONST_IMM) {
  1479. dst_imm *= src_reg->imm;
  1480. } else if (opcode == BPF_OR && BPF_SRC(insn->code) == BPF_K) {
  1481. dst_imm |= insn->imm;
  1482. } else if (opcode == BPF_OR && BPF_SRC(insn->code) == BPF_X &&
  1483. src_reg->type == CONST_IMM) {
  1484. dst_imm |= src_reg->imm;
  1485. } else if (opcode == BPF_AND && BPF_SRC(insn->code) == BPF_K) {
  1486. dst_imm &= insn->imm;
  1487. } else if (opcode == BPF_AND && BPF_SRC(insn->code) == BPF_X &&
  1488. src_reg->type == CONST_IMM) {
  1489. dst_imm &= src_reg->imm;
  1490. } else if (opcode == BPF_RSH && BPF_SRC(insn->code) == BPF_K) {
  1491. dst_imm >>= insn->imm;
  1492. } else if (opcode == BPF_RSH && BPF_SRC(insn->code) == BPF_X &&
  1493. src_reg->type == CONST_IMM) {
  1494. dst_imm >>= src_reg->imm;
  1495. } else if (opcode == BPF_LSH && BPF_SRC(insn->code) == BPF_K) {
  1496. dst_imm <<= insn->imm;
  1497. } else if (opcode == BPF_LSH && BPF_SRC(insn->code) == BPF_X &&
  1498. src_reg->type == CONST_IMM) {
  1499. dst_imm <<= src_reg->imm;
  1500. } else {
  1501. mark_reg_unknown_value(regs, insn->dst_reg);
  1502. goto out;
  1503. }
  1504. dst_reg->imm = dst_imm;
  1505. out:
  1506. return 0;
  1507. }
  1508. static void check_reg_overflow(struct bpf_reg_state *reg)
  1509. {
  1510. if (reg->max_value > BPF_REGISTER_MAX_RANGE)
  1511. reg->max_value = BPF_REGISTER_MAX_RANGE;
  1512. if (reg->min_value < BPF_REGISTER_MIN_RANGE ||
  1513. reg->min_value > BPF_REGISTER_MAX_RANGE)
  1514. reg->min_value = BPF_REGISTER_MIN_RANGE;
  1515. }
  1516. static void adjust_reg_min_max_vals(struct bpf_verifier_env *env,
  1517. struct bpf_insn *insn)
  1518. {
  1519. struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
  1520. s64 min_val = BPF_REGISTER_MIN_RANGE;
  1521. u64 max_val = BPF_REGISTER_MAX_RANGE;
  1522. u8 opcode = BPF_OP(insn->code);
  1523. dst_reg = &regs[insn->dst_reg];
  1524. if (BPF_SRC(insn->code) == BPF_X) {
  1525. check_reg_overflow(&regs[insn->src_reg]);
  1526. min_val = regs[insn->src_reg].min_value;
  1527. max_val = regs[insn->src_reg].max_value;
  1528. /* If the source register is a random pointer then the
  1529. * min_value/max_value values represent the range of the known
  1530. * accesses into that value, not the actual min/max value of the
  1531. * register itself. In this case we have to reset the reg range
  1532. * values so we know it is not safe to look at.
  1533. */
  1534. if (regs[insn->src_reg].type != CONST_IMM &&
  1535. regs[insn->src_reg].type != UNKNOWN_VALUE) {
  1536. min_val = BPF_REGISTER_MIN_RANGE;
  1537. max_val = BPF_REGISTER_MAX_RANGE;
  1538. }
  1539. } else if (insn->imm < BPF_REGISTER_MAX_RANGE &&
  1540. (s64)insn->imm > BPF_REGISTER_MIN_RANGE) {
  1541. min_val = max_val = insn->imm;
  1542. }
  1543. /* We don't know anything about what was done to this register, mark it
  1544. * as unknown.
  1545. */
  1546. if (min_val == BPF_REGISTER_MIN_RANGE &&
  1547. max_val == BPF_REGISTER_MAX_RANGE) {
  1548. reset_reg_range_values(regs, insn->dst_reg);
  1549. return;
  1550. }
  1551. /* If one of our values was at the end of our ranges then we can't just
  1552. * do our normal operations to the register, we need to set the values
  1553. * to the min/max since they are undefined.
  1554. */
  1555. if (min_val == BPF_REGISTER_MIN_RANGE)
  1556. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1557. if (max_val == BPF_REGISTER_MAX_RANGE)
  1558. dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
  1559. switch (opcode) {
  1560. case BPF_ADD:
  1561. if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
  1562. dst_reg->min_value += min_val;
  1563. if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1564. dst_reg->max_value += max_val;
  1565. break;
  1566. case BPF_SUB:
  1567. if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
  1568. dst_reg->min_value -= min_val;
  1569. if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1570. dst_reg->max_value -= max_val;
  1571. break;
  1572. case BPF_MUL:
  1573. if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
  1574. dst_reg->min_value *= min_val;
  1575. if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1576. dst_reg->max_value *= max_val;
  1577. break;
  1578. case BPF_AND:
  1579. /* Disallow AND'ing of negative numbers, ain't nobody got time
  1580. * for that. Otherwise the minimum is 0 and the max is the max
  1581. * value we could AND against.
  1582. */
  1583. if (min_val < 0)
  1584. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1585. else
  1586. dst_reg->min_value = 0;
  1587. dst_reg->max_value = max_val;
  1588. break;
  1589. case BPF_LSH:
  1590. /* Gotta have special overflow logic here, if we're shifting
  1591. * more than MAX_RANGE then just assume we have an invalid
  1592. * range.
  1593. */
  1594. if (min_val > ilog2(BPF_REGISTER_MAX_RANGE))
  1595. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1596. else if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
  1597. dst_reg->min_value <<= min_val;
  1598. if (max_val > ilog2(BPF_REGISTER_MAX_RANGE))
  1599. dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
  1600. else if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1601. dst_reg->max_value <<= max_val;
  1602. break;
  1603. case BPF_RSH:
  1604. /* RSH by a negative number is undefined, and the BPF_RSH is an
  1605. * unsigned shift, so make the appropriate casts.
  1606. */
  1607. if (min_val < 0 || dst_reg->min_value < 0)
  1608. dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
  1609. else
  1610. dst_reg->min_value =
  1611. (u64)(dst_reg->min_value) >> min_val;
  1612. if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
  1613. dst_reg->max_value >>= max_val;
  1614. break;
  1615. default:
  1616. reset_reg_range_values(regs, insn->dst_reg);
  1617. break;
  1618. }
  1619. check_reg_overflow(dst_reg);
  1620. }
  1621. /* check validity of 32-bit and 64-bit arithmetic operations */
  1622. static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
  1623. {
  1624. struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
  1625. u8 opcode = BPF_OP(insn->code);
  1626. int err;
  1627. if (opcode == BPF_END || opcode == BPF_NEG) {
  1628. if (opcode == BPF_NEG) {
  1629. if (BPF_SRC(insn->code) != 0 ||
  1630. insn->src_reg != BPF_REG_0 ||
  1631. insn->off != 0 || insn->imm != 0) {
  1632. verbose("BPF_NEG uses reserved fields\n");
  1633. return -EINVAL;
  1634. }
  1635. } else {
  1636. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  1637. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
  1638. verbose("BPF_END uses reserved fields\n");
  1639. return -EINVAL;
  1640. }
  1641. }
  1642. /* check src operand */
  1643. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1644. if (err)
  1645. return err;
  1646. if (is_pointer_value(env, insn->dst_reg)) {
  1647. verbose("R%d pointer arithmetic prohibited\n",
  1648. insn->dst_reg);
  1649. return -EACCES;
  1650. }
  1651. /* check dest operand */
  1652. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1653. if (err)
  1654. return err;
  1655. } else if (opcode == BPF_MOV) {
  1656. if (BPF_SRC(insn->code) == BPF_X) {
  1657. if (insn->imm != 0 || insn->off != 0) {
  1658. verbose("BPF_MOV uses reserved fields\n");
  1659. return -EINVAL;
  1660. }
  1661. /* check src operand */
  1662. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1663. if (err)
  1664. return err;
  1665. } else {
  1666. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  1667. verbose("BPF_MOV uses reserved fields\n");
  1668. return -EINVAL;
  1669. }
  1670. }
  1671. /* check dest operand */
  1672. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1673. if (err)
  1674. return err;
  1675. /* we are setting our register to something new, we need to
  1676. * reset its range values.
  1677. */
  1678. reset_reg_range_values(regs, insn->dst_reg);
  1679. if (BPF_SRC(insn->code) == BPF_X) {
  1680. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  1681. /* case: R1 = R2
  1682. * copy register state to dest reg
  1683. */
  1684. regs[insn->dst_reg] = regs[insn->src_reg];
  1685. } else {
  1686. if (is_pointer_value(env, insn->src_reg)) {
  1687. verbose("R%d partial copy of pointer\n",
  1688. insn->src_reg);
  1689. return -EACCES;
  1690. }
  1691. mark_reg_unknown_value(regs, insn->dst_reg);
  1692. }
  1693. } else {
  1694. /* case: R = imm
  1695. * remember the value we stored into this reg
  1696. */
  1697. regs[insn->dst_reg].type = CONST_IMM;
  1698. regs[insn->dst_reg].imm = insn->imm;
  1699. regs[insn->dst_reg].max_value = insn->imm;
  1700. regs[insn->dst_reg].min_value = insn->imm;
  1701. }
  1702. } else if (opcode > BPF_END) {
  1703. verbose("invalid BPF_ALU opcode %x\n", opcode);
  1704. return -EINVAL;
  1705. } else { /* all other ALU ops: and, sub, xor, add, ... */
  1706. if (BPF_SRC(insn->code) == BPF_X) {
  1707. if (insn->imm != 0 || insn->off != 0) {
  1708. verbose("BPF_ALU uses reserved fields\n");
  1709. return -EINVAL;
  1710. }
  1711. /* check src1 operand */
  1712. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1713. if (err)
  1714. return err;
  1715. } else {
  1716. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  1717. verbose("BPF_ALU uses reserved fields\n");
  1718. return -EINVAL;
  1719. }
  1720. }
  1721. /* check src2 operand */
  1722. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1723. if (err)
  1724. return err;
  1725. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  1726. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  1727. verbose("div by zero\n");
  1728. return -EINVAL;
  1729. }
  1730. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  1731. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  1732. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  1733. if (insn->imm < 0 || insn->imm >= size) {
  1734. verbose("invalid shift %d\n", insn->imm);
  1735. return -EINVAL;
  1736. }
  1737. }
  1738. /* check dest operand */
  1739. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  1740. if (err)
  1741. return err;
  1742. dst_reg = &regs[insn->dst_reg];
  1743. /* first we want to adjust our ranges. */
  1744. adjust_reg_min_max_vals(env, insn);
  1745. /* pattern match 'bpf_add Rx, imm' instruction */
  1746. if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
  1747. dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
  1748. dst_reg->type = PTR_TO_STACK;
  1749. dst_reg->imm = insn->imm;
  1750. return 0;
  1751. } else if (opcode == BPF_ADD &&
  1752. BPF_CLASS(insn->code) == BPF_ALU64 &&
  1753. dst_reg->type == PTR_TO_STACK &&
  1754. ((BPF_SRC(insn->code) == BPF_X &&
  1755. regs[insn->src_reg].type == CONST_IMM) ||
  1756. BPF_SRC(insn->code) == BPF_K)) {
  1757. if (BPF_SRC(insn->code) == BPF_X)
  1758. dst_reg->imm += regs[insn->src_reg].imm;
  1759. else
  1760. dst_reg->imm += insn->imm;
  1761. return 0;
  1762. } else if (opcode == BPF_ADD &&
  1763. BPF_CLASS(insn->code) == BPF_ALU64 &&
  1764. (dst_reg->type == PTR_TO_PACKET ||
  1765. (BPF_SRC(insn->code) == BPF_X &&
  1766. regs[insn->src_reg].type == PTR_TO_PACKET))) {
  1767. /* ptr_to_packet += K|X */
  1768. return check_packet_ptr_add(env, insn);
  1769. } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
  1770. dst_reg->type == UNKNOWN_VALUE &&
  1771. env->allow_ptr_leaks) {
  1772. /* unknown += K|X */
  1773. return evaluate_reg_alu(env, insn);
  1774. } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
  1775. dst_reg->type == CONST_IMM &&
  1776. env->allow_ptr_leaks) {
  1777. /* reg_imm += K|X */
  1778. return evaluate_reg_imm_alu(env, insn);
  1779. } else if (is_pointer_value(env, insn->dst_reg)) {
  1780. verbose("R%d pointer arithmetic prohibited\n",
  1781. insn->dst_reg);
  1782. return -EACCES;
  1783. } else if (BPF_SRC(insn->code) == BPF_X &&
  1784. is_pointer_value(env, insn->src_reg)) {
  1785. verbose("R%d pointer arithmetic prohibited\n",
  1786. insn->src_reg);
  1787. return -EACCES;
  1788. }
  1789. /* If we did pointer math on a map value then just set it to our
  1790. * PTR_TO_MAP_VALUE_ADJ type so we can deal with any stores or
  1791. * loads to this register appropriately, otherwise just mark the
  1792. * register as unknown.
  1793. */
  1794. if (env->allow_ptr_leaks &&
  1795. BPF_CLASS(insn->code) == BPF_ALU64 && opcode == BPF_ADD &&
  1796. (dst_reg->type == PTR_TO_MAP_VALUE ||
  1797. dst_reg->type == PTR_TO_MAP_VALUE_ADJ))
  1798. dst_reg->type = PTR_TO_MAP_VALUE_ADJ;
  1799. else
  1800. mark_reg_unknown_value(regs, insn->dst_reg);
  1801. }
  1802. return 0;
  1803. }
  1804. static void find_good_pkt_pointers(struct bpf_verifier_state *state,
  1805. struct bpf_reg_state *dst_reg)
  1806. {
  1807. struct bpf_reg_state *regs = state->regs, *reg;
  1808. int i;
  1809. /* LLVM can generate two kind of checks:
  1810. *
  1811. * Type 1:
  1812. *
  1813. * r2 = r3;
  1814. * r2 += 8;
  1815. * if (r2 > pkt_end) goto <handle exception>
  1816. * <access okay>
  1817. *
  1818. * Where:
  1819. * r2 == dst_reg, pkt_end == src_reg
  1820. * r2=pkt(id=n,off=8,r=0)
  1821. * r3=pkt(id=n,off=0,r=0)
  1822. *
  1823. * Type 2:
  1824. *
  1825. * r2 = r3;
  1826. * r2 += 8;
  1827. * if (pkt_end >= r2) goto <access okay>
  1828. * <handle exception>
  1829. *
  1830. * Where:
  1831. * pkt_end == dst_reg, r2 == src_reg
  1832. * r2=pkt(id=n,off=8,r=0)
  1833. * r3=pkt(id=n,off=0,r=0)
  1834. *
  1835. * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
  1836. * so that range of bytes [r3, r3 + 8) is safe to access.
  1837. */
  1838. for (i = 0; i < MAX_BPF_REG; i++)
  1839. if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
  1840. /* keep the maximum range already checked */
  1841. regs[i].range = max(regs[i].range, dst_reg->off);
  1842. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  1843. if (state->stack_slot_type[i] != STACK_SPILL)
  1844. continue;
  1845. reg = &state->spilled_regs[i / BPF_REG_SIZE];
  1846. if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
  1847. reg->range = max(reg->range, dst_reg->off);
  1848. }
  1849. }
  1850. /* Adjusts the register min/max values in the case that the dst_reg is the
  1851. * variable register that we are working on, and src_reg is a constant or we're
  1852. * simply doing a BPF_K check.
  1853. */
  1854. static void reg_set_min_max(struct bpf_reg_state *true_reg,
  1855. struct bpf_reg_state *false_reg, u64 val,
  1856. u8 opcode)
  1857. {
  1858. switch (opcode) {
  1859. case BPF_JEQ:
  1860. /* If this is false then we know nothing Jon Snow, but if it is
  1861. * true then we know for sure.
  1862. */
  1863. true_reg->max_value = true_reg->min_value = val;
  1864. break;
  1865. case BPF_JNE:
  1866. /* If this is true we know nothing Jon Snow, but if it is false
  1867. * we know the value for sure;
  1868. */
  1869. false_reg->max_value = false_reg->min_value = val;
  1870. break;
  1871. case BPF_JGT:
  1872. /* Unsigned comparison, the minimum value is 0. */
  1873. false_reg->min_value = 0;
  1874. /* fallthrough */
  1875. case BPF_JSGT:
  1876. /* If this is false then we know the maximum val is val,
  1877. * otherwise we know the min val is val+1.
  1878. */
  1879. false_reg->max_value = val;
  1880. true_reg->min_value = val + 1;
  1881. break;
  1882. case BPF_JGE:
  1883. /* Unsigned comparison, the minimum value is 0. */
  1884. false_reg->min_value = 0;
  1885. /* fallthrough */
  1886. case BPF_JSGE:
  1887. /* If this is false then we know the maximum value is val - 1,
  1888. * otherwise we know the mimimum value is val.
  1889. */
  1890. false_reg->max_value = val - 1;
  1891. true_reg->min_value = val;
  1892. break;
  1893. default:
  1894. break;
  1895. }
  1896. check_reg_overflow(false_reg);
  1897. check_reg_overflow(true_reg);
  1898. }
  1899. /* Same as above, but for the case that dst_reg is a CONST_IMM reg and src_reg
  1900. * is the variable reg.
  1901. */
  1902. static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
  1903. struct bpf_reg_state *false_reg, u64 val,
  1904. u8 opcode)
  1905. {
  1906. switch (opcode) {
  1907. case BPF_JEQ:
  1908. /* If this is false then we know nothing Jon Snow, but if it is
  1909. * true then we know for sure.
  1910. */
  1911. true_reg->max_value = true_reg->min_value = val;
  1912. break;
  1913. case BPF_JNE:
  1914. /* If this is true we know nothing Jon Snow, but if it is false
  1915. * we know the value for sure;
  1916. */
  1917. false_reg->max_value = false_reg->min_value = val;
  1918. break;
  1919. case BPF_JGT:
  1920. /* Unsigned comparison, the minimum value is 0. */
  1921. true_reg->min_value = 0;
  1922. /* fallthrough */
  1923. case BPF_JSGT:
  1924. /*
  1925. * If this is false, then the val is <= the register, if it is
  1926. * true the register <= to the val.
  1927. */
  1928. false_reg->min_value = val;
  1929. true_reg->max_value = val - 1;
  1930. break;
  1931. case BPF_JGE:
  1932. /* Unsigned comparison, the minimum value is 0. */
  1933. true_reg->min_value = 0;
  1934. /* fallthrough */
  1935. case BPF_JSGE:
  1936. /* If this is false then constant < register, if it is true then
  1937. * the register < constant.
  1938. */
  1939. false_reg->min_value = val + 1;
  1940. true_reg->max_value = val;
  1941. break;
  1942. default:
  1943. break;
  1944. }
  1945. check_reg_overflow(false_reg);
  1946. check_reg_overflow(true_reg);
  1947. }
  1948. static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
  1949. enum bpf_reg_type type)
  1950. {
  1951. struct bpf_reg_state *reg = &regs[regno];
  1952. if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
  1953. if (type == UNKNOWN_VALUE) {
  1954. __mark_reg_unknown_value(regs, regno);
  1955. } else if (reg->map_ptr->inner_map_meta) {
  1956. reg->type = CONST_PTR_TO_MAP;
  1957. reg->map_ptr = reg->map_ptr->inner_map_meta;
  1958. } else {
  1959. reg->type = type;
  1960. }
  1961. /* We don't need id from this point onwards anymore, thus we
  1962. * should better reset it, so that state pruning has chances
  1963. * to take effect.
  1964. */
  1965. reg->id = 0;
  1966. }
  1967. }
  1968. /* The logic is similar to find_good_pkt_pointers(), both could eventually
  1969. * be folded together at some point.
  1970. */
  1971. static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
  1972. enum bpf_reg_type type)
  1973. {
  1974. struct bpf_reg_state *regs = state->regs;
  1975. u32 id = regs[regno].id;
  1976. int i;
  1977. for (i = 0; i < MAX_BPF_REG; i++)
  1978. mark_map_reg(regs, i, id, type);
  1979. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  1980. if (state->stack_slot_type[i] != STACK_SPILL)
  1981. continue;
  1982. mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, type);
  1983. }
  1984. }
  1985. static int check_cond_jmp_op(struct bpf_verifier_env *env,
  1986. struct bpf_insn *insn, int *insn_idx)
  1987. {
  1988. struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
  1989. struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
  1990. u8 opcode = BPF_OP(insn->code);
  1991. int err;
  1992. if (opcode > BPF_EXIT) {
  1993. verbose("invalid BPF_JMP opcode %x\n", opcode);
  1994. return -EINVAL;
  1995. }
  1996. if (BPF_SRC(insn->code) == BPF_X) {
  1997. if (insn->imm != 0) {
  1998. verbose("BPF_JMP uses reserved fields\n");
  1999. return -EINVAL;
  2000. }
  2001. /* check src1 operand */
  2002. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2003. if (err)
  2004. return err;
  2005. if (is_pointer_value(env, insn->src_reg)) {
  2006. verbose("R%d pointer comparison prohibited\n",
  2007. insn->src_reg);
  2008. return -EACCES;
  2009. }
  2010. } else {
  2011. if (insn->src_reg != BPF_REG_0) {
  2012. verbose("BPF_JMP uses reserved fields\n");
  2013. return -EINVAL;
  2014. }
  2015. }
  2016. /* check src2 operand */
  2017. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  2018. if (err)
  2019. return err;
  2020. dst_reg = &regs[insn->dst_reg];
  2021. /* detect if R == 0 where R was initialized to zero earlier */
  2022. if (BPF_SRC(insn->code) == BPF_K &&
  2023. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  2024. dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
  2025. if (opcode == BPF_JEQ) {
  2026. /* if (imm == imm) goto pc+off;
  2027. * only follow the goto, ignore fall-through
  2028. */
  2029. *insn_idx += insn->off;
  2030. return 0;
  2031. } else {
  2032. /* if (imm != imm) goto pc+off;
  2033. * only follow fall-through branch, since
  2034. * that's where the program will go
  2035. */
  2036. return 0;
  2037. }
  2038. }
  2039. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  2040. if (!other_branch)
  2041. return -EFAULT;
  2042. /* detect if we are comparing against a constant value so we can adjust
  2043. * our min/max values for our dst register.
  2044. */
  2045. if (BPF_SRC(insn->code) == BPF_X) {
  2046. if (regs[insn->src_reg].type == CONST_IMM)
  2047. reg_set_min_max(&other_branch->regs[insn->dst_reg],
  2048. dst_reg, regs[insn->src_reg].imm,
  2049. opcode);
  2050. else if (dst_reg->type == CONST_IMM)
  2051. reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
  2052. &regs[insn->src_reg], dst_reg->imm,
  2053. opcode);
  2054. } else {
  2055. reg_set_min_max(&other_branch->regs[insn->dst_reg],
  2056. dst_reg, insn->imm, opcode);
  2057. }
  2058. /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
  2059. if (BPF_SRC(insn->code) == BPF_K &&
  2060. insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  2061. dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
  2062. /* Mark all identical map registers in each branch as either
  2063. * safe or unknown depending R == 0 or R != 0 conditional.
  2064. */
  2065. mark_map_regs(this_branch, insn->dst_reg,
  2066. opcode == BPF_JEQ ? PTR_TO_MAP_VALUE : UNKNOWN_VALUE);
  2067. mark_map_regs(other_branch, insn->dst_reg,
  2068. opcode == BPF_JEQ ? UNKNOWN_VALUE : PTR_TO_MAP_VALUE);
  2069. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
  2070. dst_reg->type == PTR_TO_PACKET &&
  2071. regs[insn->src_reg].type == PTR_TO_PACKET_END) {
  2072. find_good_pkt_pointers(this_branch, dst_reg);
  2073. } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
  2074. dst_reg->type == PTR_TO_PACKET_END &&
  2075. regs[insn->src_reg].type == PTR_TO_PACKET) {
  2076. find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
  2077. } else if (is_pointer_value(env, insn->dst_reg)) {
  2078. verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
  2079. return -EACCES;
  2080. }
  2081. if (log_level)
  2082. print_verifier_state(this_branch);
  2083. return 0;
  2084. }
  2085. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  2086. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  2087. {
  2088. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  2089. return (struct bpf_map *) (unsigned long) imm64;
  2090. }
  2091. /* verify BPF_LD_IMM64 instruction */
  2092. static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2093. {
  2094. struct bpf_reg_state *regs = env->cur_state.regs;
  2095. int err;
  2096. if (BPF_SIZE(insn->code) != BPF_DW) {
  2097. verbose("invalid BPF_LD_IMM insn\n");
  2098. return -EINVAL;
  2099. }
  2100. if (insn->off != 0) {
  2101. verbose("BPF_LD_IMM64 uses reserved fields\n");
  2102. return -EINVAL;
  2103. }
  2104. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  2105. if (err)
  2106. return err;
  2107. if (insn->src_reg == 0) {
  2108. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  2109. regs[insn->dst_reg].type = CONST_IMM;
  2110. regs[insn->dst_reg].imm = imm;
  2111. return 0;
  2112. }
  2113. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  2114. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  2115. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  2116. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  2117. return 0;
  2118. }
  2119. static bool may_access_skb(enum bpf_prog_type type)
  2120. {
  2121. switch (type) {
  2122. case BPF_PROG_TYPE_SOCKET_FILTER:
  2123. case BPF_PROG_TYPE_SCHED_CLS:
  2124. case BPF_PROG_TYPE_SCHED_ACT:
  2125. return true;
  2126. default:
  2127. return false;
  2128. }
  2129. }
  2130. /* verify safety of LD_ABS|LD_IND instructions:
  2131. * - they can only appear in the programs where ctx == skb
  2132. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  2133. * preserve R6-R9, and store return value into R0
  2134. *
  2135. * Implicit input:
  2136. * ctx == skb == R6 == CTX
  2137. *
  2138. * Explicit input:
  2139. * SRC == any register
  2140. * IMM == 32-bit immediate
  2141. *
  2142. * Output:
  2143. * R0 - 8/16/32-bit skb data converted to cpu endianness
  2144. */
  2145. static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2146. {
  2147. struct bpf_reg_state *regs = env->cur_state.regs;
  2148. u8 mode = BPF_MODE(insn->code);
  2149. struct bpf_reg_state *reg;
  2150. int i, err;
  2151. if (!may_access_skb(env->prog->type)) {
  2152. verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
  2153. return -EINVAL;
  2154. }
  2155. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  2156. BPF_SIZE(insn->code) == BPF_DW ||
  2157. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  2158. verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
  2159. return -EINVAL;
  2160. }
  2161. /* check whether implicit source operand (register R6) is readable */
  2162. err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
  2163. if (err)
  2164. return err;
  2165. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  2166. verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  2167. return -EINVAL;
  2168. }
  2169. if (mode == BPF_IND) {
  2170. /* check explicit source operand */
  2171. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2172. if (err)
  2173. return err;
  2174. }
  2175. /* reset caller saved regs to unreadable */
  2176. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  2177. reg = regs + caller_saved[i];
  2178. reg->type = NOT_INIT;
  2179. reg->imm = 0;
  2180. }
  2181. /* mark destination R0 register as readable, since it contains
  2182. * the value fetched from the packet
  2183. */
  2184. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  2185. return 0;
  2186. }
  2187. /* non-recursive DFS pseudo code
  2188. * 1 procedure DFS-iterative(G,v):
  2189. * 2 label v as discovered
  2190. * 3 let S be a stack
  2191. * 4 S.push(v)
  2192. * 5 while S is not empty
  2193. * 6 t <- S.pop()
  2194. * 7 if t is what we're looking for:
  2195. * 8 return t
  2196. * 9 for all edges e in G.adjacentEdges(t) do
  2197. * 10 if edge e is already labelled
  2198. * 11 continue with the next edge
  2199. * 12 w <- G.adjacentVertex(t,e)
  2200. * 13 if vertex w is not discovered and not explored
  2201. * 14 label e as tree-edge
  2202. * 15 label w as discovered
  2203. * 16 S.push(w)
  2204. * 17 continue at 5
  2205. * 18 else if vertex w is discovered
  2206. * 19 label e as back-edge
  2207. * 20 else
  2208. * 21 // vertex w is explored
  2209. * 22 label e as forward- or cross-edge
  2210. * 23 label t as explored
  2211. * 24 S.pop()
  2212. *
  2213. * convention:
  2214. * 0x10 - discovered
  2215. * 0x11 - discovered and fall-through edge labelled
  2216. * 0x12 - discovered and fall-through and branch edges labelled
  2217. * 0x20 - explored
  2218. */
  2219. enum {
  2220. DISCOVERED = 0x10,
  2221. EXPLORED = 0x20,
  2222. FALLTHROUGH = 1,
  2223. BRANCH = 2,
  2224. };
  2225. #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
  2226. static int *insn_stack; /* stack of insns to process */
  2227. static int cur_stack; /* current stack index */
  2228. static int *insn_state;
  2229. /* t, w, e - match pseudo-code above:
  2230. * t - index of current instruction
  2231. * w - next instruction
  2232. * e - edge
  2233. */
  2234. static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
  2235. {
  2236. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  2237. return 0;
  2238. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  2239. return 0;
  2240. if (w < 0 || w >= env->prog->len) {
  2241. verbose("jump out of range from insn %d to %d\n", t, w);
  2242. return -EINVAL;
  2243. }
  2244. if (e == BRANCH)
  2245. /* mark branch target for state pruning */
  2246. env->explored_states[w] = STATE_LIST_MARK;
  2247. if (insn_state[w] == 0) {
  2248. /* tree-edge */
  2249. insn_state[t] = DISCOVERED | e;
  2250. insn_state[w] = DISCOVERED;
  2251. if (cur_stack >= env->prog->len)
  2252. return -E2BIG;
  2253. insn_stack[cur_stack++] = w;
  2254. return 1;
  2255. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  2256. verbose("back-edge from insn %d to %d\n", t, w);
  2257. return -EINVAL;
  2258. } else if (insn_state[w] == EXPLORED) {
  2259. /* forward- or cross-edge */
  2260. insn_state[t] = DISCOVERED | e;
  2261. } else {
  2262. verbose("insn state internal bug\n");
  2263. return -EFAULT;
  2264. }
  2265. return 0;
  2266. }
  2267. /* non-recursive depth-first-search to detect loops in BPF program
  2268. * loop == back-edge in directed graph
  2269. */
  2270. static int check_cfg(struct bpf_verifier_env *env)
  2271. {
  2272. struct bpf_insn *insns = env->prog->insnsi;
  2273. int insn_cnt = env->prog->len;
  2274. int ret = 0;
  2275. int i, t;
  2276. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  2277. if (!insn_state)
  2278. return -ENOMEM;
  2279. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  2280. if (!insn_stack) {
  2281. kfree(insn_state);
  2282. return -ENOMEM;
  2283. }
  2284. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  2285. insn_stack[0] = 0; /* 0 is the first instruction */
  2286. cur_stack = 1;
  2287. peek_stack:
  2288. if (cur_stack == 0)
  2289. goto check_state;
  2290. t = insn_stack[cur_stack - 1];
  2291. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  2292. u8 opcode = BPF_OP(insns[t].code);
  2293. if (opcode == BPF_EXIT) {
  2294. goto mark_explored;
  2295. } else if (opcode == BPF_CALL) {
  2296. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2297. if (ret == 1)
  2298. goto peek_stack;
  2299. else if (ret < 0)
  2300. goto err_free;
  2301. if (t + 1 < insn_cnt)
  2302. env->explored_states[t + 1] = STATE_LIST_MARK;
  2303. } else if (opcode == BPF_JA) {
  2304. if (BPF_SRC(insns[t].code) != BPF_K) {
  2305. ret = -EINVAL;
  2306. goto err_free;
  2307. }
  2308. /* unconditional jump with single edge */
  2309. ret = push_insn(t, t + insns[t].off + 1,
  2310. FALLTHROUGH, env);
  2311. if (ret == 1)
  2312. goto peek_stack;
  2313. else if (ret < 0)
  2314. goto err_free;
  2315. /* tell verifier to check for equivalent states
  2316. * after every call and jump
  2317. */
  2318. if (t + 1 < insn_cnt)
  2319. env->explored_states[t + 1] = STATE_LIST_MARK;
  2320. } else {
  2321. /* conditional jump with two edges */
  2322. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2323. if (ret == 1)
  2324. goto peek_stack;
  2325. else if (ret < 0)
  2326. goto err_free;
  2327. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  2328. if (ret == 1)
  2329. goto peek_stack;
  2330. else if (ret < 0)
  2331. goto err_free;
  2332. }
  2333. } else {
  2334. /* all other non-branch instructions with single
  2335. * fall-through edge
  2336. */
  2337. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  2338. if (ret == 1)
  2339. goto peek_stack;
  2340. else if (ret < 0)
  2341. goto err_free;
  2342. }
  2343. mark_explored:
  2344. insn_state[t] = EXPLORED;
  2345. if (cur_stack-- <= 0) {
  2346. verbose("pop stack internal bug\n");
  2347. ret = -EFAULT;
  2348. goto err_free;
  2349. }
  2350. goto peek_stack;
  2351. check_state:
  2352. for (i = 0; i < insn_cnt; i++) {
  2353. if (insn_state[i] != EXPLORED) {
  2354. verbose("unreachable insn %d\n", i);
  2355. ret = -EINVAL;
  2356. goto err_free;
  2357. }
  2358. }
  2359. ret = 0; /* cfg looks good */
  2360. err_free:
  2361. kfree(insn_state);
  2362. kfree(insn_stack);
  2363. return ret;
  2364. }
  2365. /* the following conditions reduce the number of explored insns
  2366. * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
  2367. */
  2368. static bool compare_ptrs_to_packet(struct bpf_reg_state *old,
  2369. struct bpf_reg_state *cur)
  2370. {
  2371. if (old->id != cur->id)
  2372. return false;
  2373. /* old ptr_to_packet is more conservative, since it allows smaller
  2374. * range. Ex:
  2375. * old(off=0,r=10) is equal to cur(off=0,r=20), because
  2376. * old(off=0,r=10) means that with range=10 the verifier proceeded
  2377. * further and found no issues with the program. Now we're in the same
  2378. * spot with cur(off=0,r=20), so we're safe too, since anything further
  2379. * will only be looking at most 10 bytes after this pointer.
  2380. */
  2381. if (old->off == cur->off && old->range < cur->range)
  2382. return true;
  2383. /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
  2384. * since both cannot be used for packet access and safe(old)
  2385. * pointer has smaller off that could be used for further
  2386. * 'if (ptr > data_end)' check
  2387. * Ex:
  2388. * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
  2389. * that we cannot access the packet.
  2390. * The safe range is:
  2391. * [ptr, ptr + range - off)
  2392. * so whenever off >=range, it means no safe bytes from this pointer.
  2393. * When comparing old->off <= cur->off, it means that older code
  2394. * went with smaller offset and that offset was later
  2395. * used to figure out the safe range after 'if (ptr > data_end)' check
  2396. * Say, 'old' state was explored like:
  2397. * ... R3(off=0, r=0)
  2398. * R4 = R3 + 20
  2399. * ... now R4(off=20,r=0) <-- here
  2400. * if (R4 > data_end)
  2401. * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
  2402. * ... the code further went all the way to bpf_exit.
  2403. * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
  2404. * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
  2405. * goes further, such cur_R4 will give larger safe packet range after
  2406. * 'if (R4 > data_end)' and all further insn were already good with r=20,
  2407. * so they will be good with r=30 and we can prune the search.
  2408. */
  2409. if (old->off <= cur->off &&
  2410. old->off >= old->range && cur->off >= cur->range)
  2411. return true;
  2412. return false;
  2413. }
  2414. /* compare two verifier states
  2415. *
  2416. * all states stored in state_list are known to be valid, since
  2417. * verifier reached 'bpf_exit' instruction through them
  2418. *
  2419. * this function is called when verifier exploring different branches of
  2420. * execution popped from the state stack. If it sees an old state that has
  2421. * more strict register state and more strict stack state then this execution
  2422. * branch doesn't need to be explored further, since verifier already
  2423. * concluded that more strict state leads to valid finish.
  2424. *
  2425. * Therefore two states are equivalent if register state is more conservative
  2426. * and explored stack state is more conservative than the current one.
  2427. * Example:
  2428. * explored current
  2429. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  2430. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  2431. *
  2432. * In other words if current stack state (one being explored) has more
  2433. * valid slots than old one that already passed validation, it means
  2434. * the verifier can stop exploring and conclude that current state is valid too
  2435. *
  2436. * Similarly with registers. If explored state has register type as invalid
  2437. * whereas register type in current state is meaningful, it means that
  2438. * the current state will reach 'bpf_exit' instruction safely
  2439. */
  2440. static bool states_equal(struct bpf_verifier_env *env,
  2441. struct bpf_verifier_state *old,
  2442. struct bpf_verifier_state *cur)
  2443. {
  2444. bool varlen_map_access = env->varlen_map_value_access;
  2445. struct bpf_reg_state *rold, *rcur;
  2446. int i;
  2447. for (i = 0; i < MAX_BPF_REG; i++) {
  2448. rold = &old->regs[i];
  2449. rcur = &cur->regs[i];
  2450. if (memcmp(rold, rcur, sizeof(*rold)) == 0)
  2451. continue;
  2452. /* If the ranges were not the same, but everything else was and
  2453. * we didn't do a variable access into a map then we are a-ok.
  2454. */
  2455. if (!varlen_map_access &&
  2456. memcmp(rold, rcur, offsetofend(struct bpf_reg_state, id)) == 0)
  2457. continue;
  2458. /* If we didn't map access then again we don't care about the
  2459. * mismatched range values and it's ok if our old type was
  2460. * UNKNOWN and we didn't go to a NOT_INIT'ed reg.
  2461. */
  2462. if (rold->type == NOT_INIT ||
  2463. (!varlen_map_access && rold->type == UNKNOWN_VALUE &&
  2464. rcur->type != NOT_INIT))
  2465. continue;
  2466. if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
  2467. compare_ptrs_to_packet(rold, rcur))
  2468. continue;
  2469. return false;
  2470. }
  2471. for (i = 0; i < MAX_BPF_STACK; i++) {
  2472. if (old->stack_slot_type[i] == STACK_INVALID)
  2473. continue;
  2474. if (old->stack_slot_type[i] != cur->stack_slot_type[i])
  2475. /* Ex: old explored (safe) state has STACK_SPILL in
  2476. * this stack slot, but current has has STACK_MISC ->
  2477. * this verifier states are not equivalent,
  2478. * return false to continue verification of this path
  2479. */
  2480. return false;
  2481. if (i % BPF_REG_SIZE)
  2482. continue;
  2483. if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
  2484. &cur->spilled_regs[i / BPF_REG_SIZE],
  2485. sizeof(old->spilled_regs[0])))
  2486. /* when explored and current stack slot types are
  2487. * the same, check that stored pointers types
  2488. * are the same as well.
  2489. * Ex: explored safe path could have stored
  2490. * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
  2491. * but current path has stored:
  2492. * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
  2493. * such verifier states are not equivalent.
  2494. * return false to continue verification of this path
  2495. */
  2496. return false;
  2497. else
  2498. continue;
  2499. }
  2500. return true;
  2501. }
  2502. static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
  2503. {
  2504. struct bpf_verifier_state_list *new_sl;
  2505. struct bpf_verifier_state_list *sl;
  2506. sl = env->explored_states[insn_idx];
  2507. if (!sl)
  2508. /* this 'insn_idx' instruction wasn't marked, so we will not
  2509. * be doing state search here
  2510. */
  2511. return 0;
  2512. while (sl != STATE_LIST_MARK) {
  2513. if (states_equal(env, &sl->state, &env->cur_state))
  2514. /* reached equivalent register/stack state,
  2515. * prune the search
  2516. */
  2517. return 1;
  2518. sl = sl->next;
  2519. }
  2520. /* there were no equivalent states, remember current one.
  2521. * technically the current state is not proven to be safe yet,
  2522. * but it will either reach bpf_exit (which means it's safe) or
  2523. * it will be rejected. Since there are no loops, we won't be
  2524. * seeing this 'insn_idx' instruction again on the way to bpf_exit
  2525. */
  2526. new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
  2527. if (!new_sl)
  2528. return -ENOMEM;
  2529. /* add new state to the head of linked list */
  2530. memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
  2531. new_sl->next = env->explored_states[insn_idx];
  2532. env->explored_states[insn_idx] = new_sl;
  2533. return 0;
  2534. }
  2535. static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
  2536. int insn_idx, int prev_insn_idx)
  2537. {
  2538. if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
  2539. return 0;
  2540. return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
  2541. }
  2542. static int do_check(struct bpf_verifier_env *env)
  2543. {
  2544. struct bpf_verifier_state *state = &env->cur_state;
  2545. struct bpf_insn *insns = env->prog->insnsi;
  2546. struct bpf_reg_state *regs = state->regs;
  2547. int insn_cnt = env->prog->len;
  2548. int insn_idx, prev_insn_idx = 0;
  2549. int insn_processed = 0;
  2550. bool do_print_state = false;
  2551. init_reg_state(regs);
  2552. insn_idx = 0;
  2553. env->varlen_map_value_access = false;
  2554. for (;;) {
  2555. struct bpf_insn *insn;
  2556. u8 class;
  2557. int err;
  2558. if (insn_idx >= insn_cnt) {
  2559. verbose("invalid insn idx %d insn_cnt %d\n",
  2560. insn_idx, insn_cnt);
  2561. return -EFAULT;
  2562. }
  2563. insn = &insns[insn_idx];
  2564. class = BPF_CLASS(insn->code);
  2565. if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
  2566. verbose("BPF program is too large. Processed %d insn\n",
  2567. insn_processed);
  2568. return -E2BIG;
  2569. }
  2570. err = is_state_visited(env, insn_idx);
  2571. if (err < 0)
  2572. return err;
  2573. if (err == 1) {
  2574. /* found equivalent state, can prune the search */
  2575. if (log_level) {
  2576. if (do_print_state)
  2577. verbose("\nfrom %d to %d: safe\n",
  2578. prev_insn_idx, insn_idx);
  2579. else
  2580. verbose("%d: safe\n", insn_idx);
  2581. }
  2582. goto process_bpf_exit;
  2583. }
  2584. if (log_level && do_print_state) {
  2585. verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
  2586. print_verifier_state(&env->cur_state);
  2587. do_print_state = false;
  2588. }
  2589. if (log_level) {
  2590. verbose("%d: ", insn_idx);
  2591. print_bpf_insn(env, insn);
  2592. }
  2593. err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
  2594. if (err)
  2595. return err;
  2596. if (class == BPF_ALU || class == BPF_ALU64) {
  2597. err = check_alu_op(env, insn);
  2598. if (err)
  2599. return err;
  2600. } else if (class == BPF_LDX) {
  2601. enum bpf_reg_type *prev_src_type, src_reg_type;
  2602. /* check for reserved fields is already done */
  2603. /* check src operand */
  2604. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2605. if (err)
  2606. return err;
  2607. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  2608. if (err)
  2609. return err;
  2610. src_reg_type = regs[insn->src_reg].type;
  2611. /* check that memory (src_reg + off) is readable,
  2612. * the state of dst_reg will be updated by this func
  2613. */
  2614. err = check_mem_access(env, insn->src_reg, insn->off,
  2615. BPF_SIZE(insn->code), BPF_READ,
  2616. insn->dst_reg);
  2617. if (err)
  2618. return err;
  2619. if (BPF_SIZE(insn->code) != BPF_W &&
  2620. BPF_SIZE(insn->code) != BPF_DW) {
  2621. insn_idx++;
  2622. continue;
  2623. }
  2624. prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
  2625. if (*prev_src_type == NOT_INIT) {
  2626. /* saw a valid insn
  2627. * dst_reg = *(u32 *)(src_reg + off)
  2628. * save type to validate intersecting paths
  2629. */
  2630. *prev_src_type = src_reg_type;
  2631. } else if (src_reg_type != *prev_src_type &&
  2632. (src_reg_type == PTR_TO_CTX ||
  2633. *prev_src_type == PTR_TO_CTX)) {
  2634. /* ABuser program is trying to use the same insn
  2635. * dst_reg = *(u32*) (src_reg + off)
  2636. * with different pointer types:
  2637. * src_reg == ctx in one branch and
  2638. * src_reg == stack|map in some other branch.
  2639. * Reject it.
  2640. */
  2641. verbose("same insn cannot be used with different pointers\n");
  2642. return -EINVAL;
  2643. }
  2644. } else if (class == BPF_STX) {
  2645. enum bpf_reg_type *prev_dst_type, dst_reg_type;
  2646. if (BPF_MODE(insn->code) == BPF_XADD) {
  2647. err = check_xadd(env, insn);
  2648. if (err)
  2649. return err;
  2650. insn_idx++;
  2651. continue;
  2652. }
  2653. /* check src1 operand */
  2654. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  2655. if (err)
  2656. return err;
  2657. /* check src2 operand */
  2658. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  2659. if (err)
  2660. return err;
  2661. dst_reg_type = regs[insn->dst_reg].type;
  2662. /* check that memory (dst_reg + off) is writeable */
  2663. err = check_mem_access(env, insn->dst_reg, insn->off,
  2664. BPF_SIZE(insn->code), BPF_WRITE,
  2665. insn->src_reg);
  2666. if (err)
  2667. return err;
  2668. prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
  2669. if (*prev_dst_type == NOT_INIT) {
  2670. *prev_dst_type = dst_reg_type;
  2671. } else if (dst_reg_type != *prev_dst_type &&
  2672. (dst_reg_type == PTR_TO_CTX ||
  2673. *prev_dst_type == PTR_TO_CTX)) {
  2674. verbose("same insn cannot be used with different pointers\n");
  2675. return -EINVAL;
  2676. }
  2677. } else if (class == BPF_ST) {
  2678. if (BPF_MODE(insn->code) != BPF_MEM ||
  2679. insn->src_reg != BPF_REG_0) {
  2680. verbose("BPF_ST uses reserved fields\n");
  2681. return -EINVAL;
  2682. }
  2683. /* check src operand */
  2684. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  2685. if (err)
  2686. return err;
  2687. /* check that memory (dst_reg + off) is writeable */
  2688. err = check_mem_access(env, insn->dst_reg, insn->off,
  2689. BPF_SIZE(insn->code), BPF_WRITE,
  2690. -1);
  2691. if (err)
  2692. return err;
  2693. } else if (class == BPF_JMP) {
  2694. u8 opcode = BPF_OP(insn->code);
  2695. if (opcode == BPF_CALL) {
  2696. if (BPF_SRC(insn->code) != BPF_K ||
  2697. insn->off != 0 ||
  2698. insn->src_reg != BPF_REG_0 ||
  2699. insn->dst_reg != BPF_REG_0) {
  2700. verbose("BPF_CALL uses reserved fields\n");
  2701. return -EINVAL;
  2702. }
  2703. err = check_call(env, insn->imm, insn_idx);
  2704. if (err)
  2705. return err;
  2706. } else if (opcode == BPF_JA) {
  2707. if (BPF_SRC(insn->code) != BPF_K ||
  2708. insn->imm != 0 ||
  2709. insn->src_reg != BPF_REG_0 ||
  2710. insn->dst_reg != BPF_REG_0) {
  2711. verbose("BPF_JA uses reserved fields\n");
  2712. return -EINVAL;
  2713. }
  2714. insn_idx += insn->off + 1;
  2715. continue;
  2716. } else if (opcode == BPF_EXIT) {
  2717. if (BPF_SRC(insn->code) != BPF_K ||
  2718. insn->imm != 0 ||
  2719. insn->src_reg != BPF_REG_0 ||
  2720. insn->dst_reg != BPF_REG_0) {
  2721. verbose("BPF_EXIT uses reserved fields\n");
  2722. return -EINVAL;
  2723. }
  2724. /* eBPF calling convetion is such that R0 is used
  2725. * to return the value from eBPF program.
  2726. * Make sure that it's readable at this time
  2727. * of bpf_exit, which means that program wrote
  2728. * something into it earlier
  2729. */
  2730. err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
  2731. if (err)
  2732. return err;
  2733. if (is_pointer_value(env, BPF_REG_0)) {
  2734. verbose("R0 leaks addr as return value\n");
  2735. return -EACCES;
  2736. }
  2737. process_bpf_exit:
  2738. insn_idx = pop_stack(env, &prev_insn_idx);
  2739. if (insn_idx < 0) {
  2740. break;
  2741. } else {
  2742. do_print_state = true;
  2743. continue;
  2744. }
  2745. } else {
  2746. err = check_cond_jmp_op(env, insn, &insn_idx);
  2747. if (err)
  2748. return err;
  2749. }
  2750. } else if (class == BPF_LD) {
  2751. u8 mode = BPF_MODE(insn->code);
  2752. if (mode == BPF_ABS || mode == BPF_IND) {
  2753. err = check_ld_abs(env, insn);
  2754. if (err)
  2755. return err;
  2756. } else if (mode == BPF_IMM) {
  2757. err = check_ld_imm(env, insn);
  2758. if (err)
  2759. return err;
  2760. insn_idx++;
  2761. } else {
  2762. verbose("invalid BPF_LD mode\n");
  2763. return -EINVAL;
  2764. }
  2765. reset_reg_range_values(regs, insn->dst_reg);
  2766. } else {
  2767. verbose("unknown insn class %d\n", class);
  2768. return -EINVAL;
  2769. }
  2770. insn_idx++;
  2771. }
  2772. verbose("processed %d insns\n", insn_processed);
  2773. return 0;
  2774. }
  2775. static int check_map_prealloc(struct bpf_map *map)
  2776. {
  2777. return (map->map_type != BPF_MAP_TYPE_HASH &&
  2778. map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
  2779. map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
  2780. !(map->map_flags & BPF_F_NO_PREALLOC);
  2781. }
  2782. static int check_map_prog_compatibility(struct bpf_map *map,
  2783. struct bpf_prog *prog)
  2784. {
  2785. /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
  2786. * preallocated hash maps, since doing memory allocation
  2787. * in overflow_handler can crash depending on where nmi got
  2788. * triggered.
  2789. */
  2790. if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
  2791. if (!check_map_prealloc(map)) {
  2792. verbose("perf_event programs can only use preallocated hash map\n");
  2793. return -EINVAL;
  2794. }
  2795. if (map->inner_map_meta &&
  2796. !check_map_prealloc(map->inner_map_meta)) {
  2797. verbose("perf_event programs can only use preallocated inner hash map\n");
  2798. return -EINVAL;
  2799. }
  2800. }
  2801. return 0;
  2802. }
  2803. /* look for pseudo eBPF instructions that access map FDs and
  2804. * replace them with actual map pointers
  2805. */
  2806. static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
  2807. {
  2808. struct bpf_insn *insn = env->prog->insnsi;
  2809. int insn_cnt = env->prog->len;
  2810. int i, j, err;
  2811. err = bpf_prog_calc_tag(env->prog);
  2812. if (err)
  2813. return err;
  2814. for (i = 0; i < insn_cnt; i++, insn++) {
  2815. if (BPF_CLASS(insn->code) == BPF_LDX &&
  2816. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  2817. verbose("BPF_LDX uses reserved fields\n");
  2818. return -EINVAL;
  2819. }
  2820. if (BPF_CLASS(insn->code) == BPF_STX &&
  2821. ((BPF_MODE(insn->code) != BPF_MEM &&
  2822. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  2823. verbose("BPF_STX uses reserved fields\n");
  2824. return -EINVAL;
  2825. }
  2826. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  2827. struct bpf_map *map;
  2828. struct fd f;
  2829. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  2830. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  2831. insn[1].off != 0) {
  2832. verbose("invalid bpf_ld_imm64 insn\n");
  2833. return -EINVAL;
  2834. }
  2835. if (insn->src_reg == 0)
  2836. /* valid generic load 64-bit imm */
  2837. goto next_insn;
  2838. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  2839. verbose("unrecognized bpf_ld_imm64 insn\n");
  2840. return -EINVAL;
  2841. }
  2842. f = fdget(insn->imm);
  2843. map = __bpf_map_get(f);
  2844. if (IS_ERR(map)) {
  2845. verbose("fd %d is not pointing to valid bpf_map\n",
  2846. insn->imm);
  2847. return PTR_ERR(map);
  2848. }
  2849. err = check_map_prog_compatibility(map, env->prog);
  2850. if (err) {
  2851. fdput(f);
  2852. return err;
  2853. }
  2854. /* store map pointer inside BPF_LD_IMM64 instruction */
  2855. insn[0].imm = (u32) (unsigned long) map;
  2856. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  2857. /* check whether we recorded this map already */
  2858. for (j = 0; j < env->used_map_cnt; j++)
  2859. if (env->used_maps[j] == map) {
  2860. fdput(f);
  2861. goto next_insn;
  2862. }
  2863. if (env->used_map_cnt >= MAX_USED_MAPS) {
  2864. fdput(f);
  2865. return -E2BIG;
  2866. }
  2867. /* hold the map. If the program is rejected by verifier,
  2868. * the map will be released by release_maps() or it
  2869. * will be used by the valid program until it's unloaded
  2870. * and all maps are released in free_bpf_prog_info()
  2871. */
  2872. map = bpf_map_inc(map, false);
  2873. if (IS_ERR(map)) {
  2874. fdput(f);
  2875. return PTR_ERR(map);
  2876. }
  2877. env->used_maps[env->used_map_cnt++] = map;
  2878. fdput(f);
  2879. next_insn:
  2880. insn++;
  2881. i++;
  2882. }
  2883. }
  2884. /* now all pseudo BPF_LD_IMM64 instructions load valid
  2885. * 'struct bpf_map *' into a register instead of user map_fd.
  2886. * These pointers will be used later by verifier to validate map access.
  2887. */
  2888. return 0;
  2889. }
  2890. /* drop refcnt of maps used by the rejected program */
  2891. static void release_maps(struct bpf_verifier_env *env)
  2892. {
  2893. int i;
  2894. for (i = 0; i < env->used_map_cnt; i++)
  2895. bpf_map_put(env->used_maps[i]);
  2896. }
  2897. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  2898. static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
  2899. {
  2900. struct bpf_insn *insn = env->prog->insnsi;
  2901. int insn_cnt = env->prog->len;
  2902. int i;
  2903. for (i = 0; i < insn_cnt; i++, insn++)
  2904. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  2905. insn->src_reg = 0;
  2906. }
  2907. /* single env->prog->insni[off] instruction was replaced with the range
  2908. * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
  2909. * [0, off) and [off, end) to new locations, so the patched range stays zero
  2910. */
  2911. static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
  2912. u32 off, u32 cnt)
  2913. {
  2914. struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
  2915. if (cnt == 1)
  2916. return 0;
  2917. new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
  2918. if (!new_data)
  2919. return -ENOMEM;
  2920. memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
  2921. memcpy(new_data + off + cnt - 1, old_data + off,
  2922. sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
  2923. env->insn_aux_data = new_data;
  2924. vfree(old_data);
  2925. return 0;
  2926. }
  2927. static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
  2928. const struct bpf_insn *patch, u32 len)
  2929. {
  2930. struct bpf_prog *new_prog;
  2931. new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
  2932. if (!new_prog)
  2933. return NULL;
  2934. if (adjust_insn_aux_data(env, new_prog->len, off, len))
  2935. return NULL;
  2936. return new_prog;
  2937. }
  2938. /* convert load instructions that access fields of 'struct __sk_buff'
  2939. * into sequence of instructions that access fields of 'struct sk_buff'
  2940. */
  2941. static int convert_ctx_accesses(struct bpf_verifier_env *env)
  2942. {
  2943. const struct bpf_verifier_ops *ops = env->prog->aux->ops;
  2944. const int insn_cnt = env->prog->len;
  2945. struct bpf_insn insn_buf[16], *insn;
  2946. struct bpf_prog *new_prog;
  2947. enum bpf_access_type type;
  2948. int i, cnt, delta = 0;
  2949. if (ops->gen_prologue) {
  2950. cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
  2951. env->prog);
  2952. if (cnt >= ARRAY_SIZE(insn_buf)) {
  2953. verbose("bpf verifier is misconfigured\n");
  2954. return -EINVAL;
  2955. } else if (cnt) {
  2956. new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
  2957. if (!new_prog)
  2958. return -ENOMEM;
  2959. env->prog = new_prog;
  2960. delta += cnt - 1;
  2961. }
  2962. }
  2963. if (!ops->convert_ctx_access)
  2964. return 0;
  2965. insn = env->prog->insnsi + delta;
  2966. for (i = 0; i < insn_cnt; i++, insn++) {
  2967. if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
  2968. insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
  2969. insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  2970. insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
  2971. type = BPF_READ;
  2972. else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
  2973. insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
  2974. insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  2975. insn->code == (BPF_STX | BPF_MEM | BPF_DW))
  2976. type = BPF_WRITE;
  2977. else
  2978. continue;
  2979. if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
  2980. continue;
  2981. cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog);
  2982. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  2983. verbose("bpf verifier is misconfigured\n");
  2984. return -EINVAL;
  2985. }
  2986. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  2987. if (!new_prog)
  2988. return -ENOMEM;
  2989. delta += cnt - 1;
  2990. /* keep walking new program and skip insns we just inserted */
  2991. env->prog = new_prog;
  2992. insn = new_prog->insnsi + i + delta;
  2993. }
  2994. return 0;
  2995. }
  2996. /* fixup insn->imm field of bpf_call instructions
  2997. * and inline eligible helpers as explicit sequence of BPF instructions
  2998. *
  2999. * this function is called after eBPF program passed verification
  3000. */
  3001. static int fixup_bpf_calls(struct bpf_verifier_env *env)
  3002. {
  3003. struct bpf_prog *prog = env->prog;
  3004. struct bpf_insn *insn = prog->insnsi;
  3005. const struct bpf_func_proto *fn;
  3006. const int insn_cnt = prog->len;
  3007. struct bpf_insn insn_buf[16];
  3008. struct bpf_prog *new_prog;
  3009. struct bpf_map *map_ptr;
  3010. int i, cnt, delta = 0;
  3011. for (i = 0; i < insn_cnt; i++, insn++) {
  3012. if (insn->code != (BPF_JMP | BPF_CALL))
  3013. continue;
  3014. if (insn->imm == BPF_FUNC_get_route_realm)
  3015. prog->dst_needed = 1;
  3016. if (insn->imm == BPF_FUNC_get_prandom_u32)
  3017. bpf_user_rnd_init_once();
  3018. if (insn->imm == BPF_FUNC_tail_call) {
  3019. /* If we tail call into other programs, we
  3020. * cannot make any assumptions since they can
  3021. * be replaced dynamically during runtime in
  3022. * the program array.
  3023. */
  3024. prog->cb_access = 1;
  3025. /* mark bpf_tail_call as different opcode to avoid
  3026. * conditional branch in the interpeter for every normal
  3027. * call and to prevent accidental JITing by JIT compiler
  3028. * that doesn't support bpf_tail_call yet
  3029. */
  3030. insn->imm = 0;
  3031. insn->code |= BPF_X;
  3032. continue;
  3033. }
  3034. if (ebpf_jit_enabled() && insn->imm == BPF_FUNC_map_lookup_elem) {
  3035. map_ptr = env->insn_aux_data[i + delta].map_ptr;
  3036. if (map_ptr == BPF_MAP_PTR_POISON ||
  3037. !map_ptr->ops->map_gen_lookup)
  3038. goto patch_call_imm;
  3039. cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
  3040. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  3041. verbose("bpf verifier is misconfigured\n");
  3042. return -EINVAL;
  3043. }
  3044. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
  3045. cnt);
  3046. if (!new_prog)
  3047. return -ENOMEM;
  3048. delta += cnt - 1;
  3049. /* keep walking new program and skip insns we just inserted */
  3050. env->prog = prog = new_prog;
  3051. insn = new_prog->insnsi + i + delta;
  3052. continue;
  3053. }
  3054. patch_call_imm:
  3055. fn = prog->aux->ops->get_func_proto(insn->imm);
  3056. /* all functions that have prototype and verifier allowed
  3057. * programs to call them, must be real in-kernel functions
  3058. */
  3059. if (!fn->func) {
  3060. verbose("kernel subsystem misconfigured func %s#%d\n",
  3061. func_id_name(insn->imm), insn->imm);
  3062. return -EFAULT;
  3063. }
  3064. insn->imm = fn->func - __bpf_call_base;
  3065. }
  3066. return 0;
  3067. }
  3068. static void free_states(struct bpf_verifier_env *env)
  3069. {
  3070. struct bpf_verifier_state_list *sl, *sln;
  3071. int i;
  3072. if (!env->explored_states)
  3073. return;
  3074. for (i = 0; i < env->prog->len; i++) {
  3075. sl = env->explored_states[i];
  3076. if (sl)
  3077. while (sl != STATE_LIST_MARK) {
  3078. sln = sl->next;
  3079. kfree(sl);
  3080. sl = sln;
  3081. }
  3082. }
  3083. kfree(env->explored_states);
  3084. }
  3085. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  3086. {
  3087. char __user *log_ubuf = NULL;
  3088. struct bpf_verifier_env *env;
  3089. int ret = -EINVAL;
  3090. /* 'struct bpf_verifier_env' can be global, but since it's not small,
  3091. * allocate/free it every time bpf_check() is called
  3092. */
  3093. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  3094. if (!env)
  3095. return -ENOMEM;
  3096. env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
  3097. (*prog)->len);
  3098. ret = -ENOMEM;
  3099. if (!env->insn_aux_data)
  3100. goto err_free_env;
  3101. env->prog = *prog;
  3102. /* grab the mutex to protect few globals used by verifier */
  3103. mutex_lock(&bpf_verifier_lock);
  3104. if (attr->log_level || attr->log_buf || attr->log_size) {
  3105. /* user requested verbose verifier output
  3106. * and supplied buffer to store the verification trace
  3107. */
  3108. log_level = attr->log_level;
  3109. log_ubuf = (char __user *) (unsigned long) attr->log_buf;
  3110. log_size = attr->log_size;
  3111. log_len = 0;
  3112. ret = -EINVAL;
  3113. /* log_* values have to be sane */
  3114. if (log_size < 128 || log_size > UINT_MAX >> 8 ||
  3115. log_level == 0 || log_ubuf == NULL)
  3116. goto err_unlock;
  3117. ret = -ENOMEM;
  3118. log_buf = vmalloc(log_size);
  3119. if (!log_buf)
  3120. goto err_unlock;
  3121. } else {
  3122. log_level = 0;
  3123. }
  3124. ret = replace_map_fd_with_map_ptr(env);
  3125. if (ret < 0)
  3126. goto skip_full_check;
  3127. env->explored_states = kcalloc(env->prog->len,
  3128. sizeof(struct bpf_verifier_state_list *),
  3129. GFP_USER);
  3130. ret = -ENOMEM;
  3131. if (!env->explored_states)
  3132. goto skip_full_check;
  3133. ret = check_cfg(env);
  3134. if (ret < 0)
  3135. goto skip_full_check;
  3136. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  3137. ret = do_check(env);
  3138. skip_full_check:
  3139. while (pop_stack(env, NULL) >= 0);
  3140. free_states(env);
  3141. if (ret == 0)
  3142. /* program is valid, convert *(u32*)(ctx + off) accesses */
  3143. ret = convert_ctx_accesses(env);
  3144. if (ret == 0)
  3145. ret = fixup_bpf_calls(env);
  3146. if (log_level && log_len >= log_size - 1) {
  3147. BUG_ON(log_len >= log_size);
  3148. /* verifier log exceeded user supplied buffer */
  3149. ret = -ENOSPC;
  3150. /* fall through to return what was recorded */
  3151. }
  3152. /* copy verifier log back to user space including trailing zero */
  3153. if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
  3154. ret = -EFAULT;
  3155. goto free_log_buf;
  3156. }
  3157. if (ret == 0 && env->used_map_cnt) {
  3158. /* if program passed verifier, update used_maps in bpf_prog_info */
  3159. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  3160. sizeof(env->used_maps[0]),
  3161. GFP_KERNEL);
  3162. if (!env->prog->aux->used_maps) {
  3163. ret = -ENOMEM;
  3164. goto free_log_buf;
  3165. }
  3166. memcpy(env->prog->aux->used_maps, env->used_maps,
  3167. sizeof(env->used_maps[0]) * env->used_map_cnt);
  3168. env->prog->aux->used_map_cnt = env->used_map_cnt;
  3169. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  3170. * bpf_ld_imm64 instructions
  3171. */
  3172. convert_pseudo_ld_imm64(env);
  3173. }
  3174. free_log_buf:
  3175. if (log_level)
  3176. vfree(log_buf);
  3177. if (!env->prog->aux->used_maps)
  3178. /* if we didn't copy map pointers into bpf_prog_info, release
  3179. * them now. Otherwise free_bpf_prog_info() will release them.
  3180. */
  3181. release_maps(env);
  3182. *prog = env->prog;
  3183. err_unlock:
  3184. mutex_unlock(&bpf_verifier_lock);
  3185. vfree(env->insn_aux_data);
  3186. err_free_env:
  3187. kfree(env);
  3188. return ret;
  3189. }
  3190. int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
  3191. void *priv)
  3192. {
  3193. struct bpf_verifier_env *env;
  3194. int ret;
  3195. env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  3196. if (!env)
  3197. return -ENOMEM;
  3198. env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
  3199. prog->len);
  3200. ret = -ENOMEM;
  3201. if (!env->insn_aux_data)
  3202. goto err_free_env;
  3203. env->prog = prog;
  3204. env->analyzer_ops = ops;
  3205. env->analyzer_priv = priv;
  3206. /* grab the mutex to protect few globals used by verifier */
  3207. mutex_lock(&bpf_verifier_lock);
  3208. log_level = 0;
  3209. env->explored_states = kcalloc(env->prog->len,
  3210. sizeof(struct bpf_verifier_state_list *),
  3211. GFP_KERNEL);
  3212. ret = -ENOMEM;
  3213. if (!env->explored_states)
  3214. goto skip_full_check;
  3215. ret = check_cfg(env);
  3216. if (ret < 0)
  3217. goto skip_full_check;
  3218. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  3219. ret = do_check(env);
  3220. skip_full_check:
  3221. while (pop_stack(env, NULL) >= 0);
  3222. free_states(env);
  3223. mutex_unlock(&bpf_verifier_lock);
  3224. vfree(env->insn_aux_data);
  3225. err_free_env:
  3226. kfree(env);
  3227. return ret;
  3228. }
  3229. EXPORT_SYMBOL_GPL(bpf_analyzer);