verifier.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556
  1. /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of version 2 of the GNU General Public
  5. * License as published by the Free Software Foundation.
  6. *
  7. * This program is distributed in the hope that it will be useful, but
  8. * WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. * General Public License for more details.
  11. */
  12. #include <linux/kernel.h>
  13. #include <linux/types.h>
  14. #include <linux/slab.h>
  15. #include <linux/bpf.h>
  16. #include <linux/filter.h>
  17. #include <net/netlink.h>
  18. #include <linux/file.h>
  19. #include <linux/vmalloc.h>
  20. /* bpf_check() is a static code analyzer that walks eBPF program
  21. * instruction by instruction and updates register/stack state.
  22. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  23. *
  24. * The first pass is depth-first-search to check that the program is a DAG.
  25. * It rejects the following programs:
  26. * - larger than BPF_MAXINSNS insns
  27. * - if loop is present (detected via back-edge)
  28. * - unreachable insns exist (shouldn't be a forest. program = one function)
  29. * - out of bounds or malformed jumps
  30. * The second pass is all possible path descent from the 1st insn.
  31. * Since it's analyzing all pathes through the program, the length of the
  32. * analysis is limited to 32k insn, which may be hit even if total number of
  33. * insn is less then 4K, but there are too many branches that change stack/regs.
  34. * Number of 'branches to be analyzed' is limited to 1k
  35. *
  36. * On entry to each instruction, each register has a type, and the instruction
  37. * changes the types of the registers depending on instruction semantics.
  38. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  39. * copied to R1.
  40. *
  41. * All registers are 64-bit.
  42. * R0 - return register
  43. * R1-R5 argument passing registers
  44. * R6-R9 callee saved registers
  45. * R10 - frame pointer read-only
  46. *
  47. * At the start of BPF program the register R1 contains a pointer to bpf_context
  48. * and has type PTR_TO_CTX.
  49. *
  50. * Verifier tracks arithmetic operations on pointers in case:
  51. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  52. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  53. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  54. * and 2nd arithmetic instruction is pattern matched to recognize
  55. * that it wants to construct a pointer to some element within stack.
  56. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  57. * (and -20 constant is saved for further stack bounds checking).
  58. * Meaning that this reg is a pointer to stack plus known immediate constant.
  59. *
  60. * Most of the time the registers have UNKNOWN_VALUE type, which
  61. * means the register has some value, but it's not a valid pointer.
  62. * (like pointer plus pointer becomes UNKNOWN_VALUE type)
  63. *
  64. * When verifier sees load or store instructions the type of base register
  65. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
  66. * types recognized by check_mem_access() function.
  67. *
  68. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  69. * and the range of [ptr, ptr + map's value_size) is accessible.
  70. *
  71. * registers used to pass values to function calls are checked against
  72. * function argument constraints.
  73. *
  74. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  75. * It means that the register type passed to this function must be
  76. * PTR_TO_STACK and it will be used inside the function as
  77. * 'pointer to map element key'
  78. *
  79. * For example the argument constraints for bpf_map_lookup_elem():
  80. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  81. * .arg1_type = ARG_CONST_MAP_PTR,
  82. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  83. *
  84. * ret_type says that this function returns 'pointer to map elem value or null'
  85. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  86. * 2nd argument should be a pointer to stack, which will be used inside
  87. * the helper function as a pointer to map element key.
  88. *
  89. * On the kernel side the helper function looks like:
  90. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  91. * {
  92. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  93. * void *key = (void *) (unsigned long) r2;
  94. * void *value;
  95. *
  96. * here kernel can access 'key' and 'map' pointers safely, knowing that
  97. * [key, key + map->key_size) bytes are valid and were initialized on
  98. * the stack of eBPF program.
  99. * }
  100. *
  101. * Corresponding eBPF program may look like:
  102. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  103. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  104. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  105. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  106. * here verifier looks at prototype of map_lookup_elem() and sees:
  107. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  108. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  109. *
  110. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  111. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  112. * and were initialized prior to this call.
  113. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  114. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  115. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  116. * returns ether pointer to map value or NULL.
  117. *
  118. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  119. * insn, the register holding that pointer in the true branch changes state to
  120. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  121. * branch. See check_cond_jmp_op().
  122. *
  123. * After the call R0 is set to return type of the function and registers R1-R5
  124. * are set to NOT_INIT to indicate that they are no longer readable.
  125. */
  126. /* types of values stored in eBPF registers */
  127. enum bpf_reg_type {
  128. NOT_INIT = 0, /* nothing was written into register */
  129. UNKNOWN_VALUE, /* reg doesn't contain a valid pointer */
  130. PTR_TO_CTX, /* reg points to bpf_context */
  131. CONST_PTR_TO_MAP, /* reg points to struct bpf_map */
  132. PTR_TO_MAP_VALUE, /* reg points to map element value */
  133. PTR_TO_MAP_VALUE_OR_NULL,/* points to map elem value or NULL */
  134. FRAME_PTR, /* reg == frame_pointer */
  135. PTR_TO_STACK, /* reg == frame_pointer + imm */
  136. CONST_IMM, /* constant integer value */
  137. };
  138. struct reg_state {
  139. enum bpf_reg_type type;
  140. union {
  141. /* valid when type == CONST_IMM | PTR_TO_STACK */
  142. int imm;
  143. /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
  144. * PTR_TO_MAP_VALUE_OR_NULL
  145. */
  146. struct bpf_map *map_ptr;
  147. };
  148. };
  149. enum bpf_stack_slot_type {
  150. STACK_INVALID, /* nothing was stored in this stack slot */
  151. STACK_SPILL, /* register spilled into stack */
  152. STACK_MISC /* BPF program wrote some data into this slot */
  153. };
  154. #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */
  155. /* state of the program:
  156. * type of all registers and stack info
  157. */
  158. struct verifier_state {
  159. struct reg_state regs[MAX_BPF_REG];
  160. u8 stack_slot_type[MAX_BPF_STACK];
  161. struct reg_state spilled_regs[MAX_BPF_STACK / BPF_REG_SIZE];
  162. };
  163. /* linked list of verifier states used to prune search */
  164. struct verifier_state_list {
  165. struct verifier_state state;
  166. struct verifier_state_list *next;
  167. };
  168. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  169. struct verifier_stack_elem {
  170. /* verifer state is 'st'
  171. * before processing instruction 'insn_idx'
  172. * and after processing instruction 'prev_insn_idx'
  173. */
  174. struct verifier_state st;
  175. int insn_idx;
  176. int prev_insn_idx;
  177. struct verifier_stack_elem *next;
  178. };
  179. struct bpf_insn_aux_data {
  180. union {
  181. enum bpf_reg_type ptr_type; /* pointer type for load/store insns */
  182. struct bpf_map *map_ptr; /* pointer for call insn into lookup_elem */
  183. };
  184. int sanitize_stack_off; /* stack slot to be cleared */
  185. bool seen; /* this insn was processed by the verifier */
  186. };
  187. #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
  188. /* single container for all structs
  189. * one verifier_env per bpf_check() call
  190. */
  191. struct verifier_env {
  192. struct bpf_prog *prog; /* eBPF program being verified */
  193. struct verifier_stack_elem *head; /* stack of verifier states to be processed */
  194. int stack_size; /* number of states to be processed */
  195. struct verifier_state cur_state; /* current verifier state */
  196. struct verifier_state_list **explored_states; /* search pruning optimization */
  197. struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
  198. u32 used_map_cnt; /* number of used maps */
  199. bool allow_ptr_leaks;
  200. struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
  201. };
  202. /* verbose verifier prints what it's seeing
  203. * bpf_check() is called under lock, so no race to access these global vars
  204. */
  205. static u32 log_level, log_size, log_len;
  206. static char *log_buf;
  207. static DEFINE_MUTEX(bpf_verifier_lock);
  208. /* log_level controls verbosity level of eBPF verifier.
  209. * verbose() is used to dump the verification trace to the log, so the user
  210. * can figure out what's wrong with the program
  211. */
  212. static __printf(1, 2) void verbose(const char *fmt, ...)
  213. {
  214. va_list args;
  215. if (log_level == 0 || log_len >= log_size - 1)
  216. return;
  217. va_start(args, fmt);
  218. log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
  219. va_end(args);
  220. }
  221. /* string representation of 'enum bpf_reg_type' */
  222. static const char * const reg_type_str[] = {
  223. [NOT_INIT] = "?",
  224. [UNKNOWN_VALUE] = "inv",
  225. [PTR_TO_CTX] = "ctx",
  226. [CONST_PTR_TO_MAP] = "map_ptr",
  227. [PTR_TO_MAP_VALUE] = "map_value",
  228. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  229. [FRAME_PTR] = "fp",
  230. [PTR_TO_STACK] = "fp",
  231. [CONST_IMM] = "imm",
  232. };
  233. static void print_verifier_state(struct verifier_env *env)
  234. {
  235. enum bpf_reg_type t;
  236. int i;
  237. for (i = 0; i < MAX_BPF_REG; i++) {
  238. t = env->cur_state.regs[i].type;
  239. if (t == NOT_INIT)
  240. continue;
  241. verbose(" R%d=%s", i, reg_type_str[t]);
  242. if (t == CONST_IMM || t == PTR_TO_STACK)
  243. verbose("%d", env->cur_state.regs[i].imm);
  244. else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
  245. t == PTR_TO_MAP_VALUE_OR_NULL)
  246. verbose("(ks=%d,vs=%d)",
  247. env->cur_state.regs[i].map_ptr->key_size,
  248. env->cur_state.regs[i].map_ptr->value_size);
  249. }
  250. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  251. if (env->cur_state.stack_slot_type[i] == STACK_SPILL)
  252. verbose(" fp%d=%s", -MAX_BPF_STACK + i,
  253. reg_type_str[env->cur_state.spilled_regs[i / BPF_REG_SIZE].type]);
  254. }
  255. verbose("\n");
  256. }
  257. static const char *const bpf_class_string[] = {
  258. [BPF_LD] = "ld",
  259. [BPF_LDX] = "ldx",
  260. [BPF_ST] = "st",
  261. [BPF_STX] = "stx",
  262. [BPF_ALU] = "alu",
  263. [BPF_JMP] = "jmp",
  264. [BPF_RET] = "BUG",
  265. [BPF_ALU64] = "alu64",
  266. };
  267. static const char *const bpf_alu_string[16] = {
  268. [BPF_ADD >> 4] = "+=",
  269. [BPF_SUB >> 4] = "-=",
  270. [BPF_MUL >> 4] = "*=",
  271. [BPF_DIV >> 4] = "/=",
  272. [BPF_OR >> 4] = "|=",
  273. [BPF_AND >> 4] = "&=",
  274. [BPF_LSH >> 4] = "<<=",
  275. [BPF_RSH >> 4] = ">>=",
  276. [BPF_NEG >> 4] = "neg",
  277. [BPF_MOD >> 4] = "%=",
  278. [BPF_XOR >> 4] = "^=",
  279. [BPF_MOV >> 4] = "=",
  280. [BPF_ARSH >> 4] = "s>>=",
  281. [BPF_END >> 4] = "endian",
  282. };
  283. static const char *const bpf_ldst_string[] = {
  284. [BPF_W >> 3] = "u32",
  285. [BPF_H >> 3] = "u16",
  286. [BPF_B >> 3] = "u8",
  287. [BPF_DW >> 3] = "u64",
  288. };
  289. static const char *const bpf_jmp_string[16] = {
  290. [BPF_JA >> 4] = "jmp",
  291. [BPF_JEQ >> 4] = "==",
  292. [BPF_JGT >> 4] = ">",
  293. [BPF_JGE >> 4] = ">=",
  294. [BPF_JSET >> 4] = "&",
  295. [BPF_JNE >> 4] = "!=",
  296. [BPF_JSGT >> 4] = "s>",
  297. [BPF_JSGE >> 4] = "s>=",
  298. [BPF_CALL >> 4] = "call",
  299. [BPF_EXIT >> 4] = "exit",
  300. };
  301. static void print_bpf_insn(const struct verifier_env *env,
  302. const struct bpf_insn *insn)
  303. {
  304. u8 class = BPF_CLASS(insn->code);
  305. if (class == BPF_ALU || class == BPF_ALU64) {
  306. if (BPF_SRC(insn->code) == BPF_X)
  307. verbose("(%02x) %sr%d %s %sr%d\n",
  308. insn->code, class == BPF_ALU ? "(u32) " : "",
  309. insn->dst_reg,
  310. bpf_alu_string[BPF_OP(insn->code) >> 4],
  311. class == BPF_ALU ? "(u32) " : "",
  312. insn->src_reg);
  313. else
  314. verbose("(%02x) %sr%d %s %s%d\n",
  315. insn->code, class == BPF_ALU ? "(u32) " : "",
  316. insn->dst_reg,
  317. bpf_alu_string[BPF_OP(insn->code) >> 4],
  318. class == BPF_ALU ? "(u32) " : "",
  319. insn->imm);
  320. } else if (class == BPF_STX) {
  321. if (BPF_MODE(insn->code) == BPF_MEM)
  322. verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
  323. insn->code,
  324. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  325. insn->dst_reg,
  326. insn->off, insn->src_reg);
  327. else if (BPF_MODE(insn->code) == BPF_XADD)
  328. verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
  329. insn->code,
  330. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  331. insn->dst_reg, insn->off,
  332. insn->src_reg);
  333. else
  334. verbose("BUG_%02x\n", insn->code);
  335. } else if (class == BPF_ST) {
  336. if (BPF_MODE(insn->code) != BPF_MEM) {
  337. verbose("BUG_st_%02x\n", insn->code);
  338. return;
  339. }
  340. verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
  341. insn->code,
  342. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  343. insn->dst_reg,
  344. insn->off, insn->imm);
  345. } else if (class == BPF_LDX) {
  346. if (BPF_MODE(insn->code) != BPF_MEM) {
  347. verbose("BUG_ldx_%02x\n", insn->code);
  348. return;
  349. }
  350. verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
  351. insn->code, insn->dst_reg,
  352. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  353. insn->src_reg, insn->off);
  354. } else if (class == BPF_LD) {
  355. if (BPF_MODE(insn->code) == BPF_ABS) {
  356. verbose("(%02x) r0 = *(%s *)skb[%d]\n",
  357. insn->code,
  358. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  359. insn->imm);
  360. } else if (BPF_MODE(insn->code) == BPF_IND) {
  361. verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
  362. insn->code,
  363. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  364. insn->src_reg, insn->imm);
  365. } else if (BPF_MODE(insn->code) == BPF_IMM &&
  366. BPF_SIZE(insn->code) == BPF_DW) {
  367. /* At this point, we already made sure that the second
  368. * part of the ldimm64 insn is accessible.
  369. */
  370. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  371. bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
  372. if (map_ptr && !env->allow_ptr_leaks)
  373. imm = 0;
  374. verbose("(%02x) r%d = 0x%llx\n", insn->code,
  375. insn->dst_reg, (unsigned long long)imm);
  376. } else {
  377. verbose("BUG_ld_%02x\n", insn->code);
  378. return;
  379. }
  380. } else if (class == BPF_JMP) {
  381. u8 opcode = BPF_OP(insn->code);
  382. if (opcode == BPF_CALL) {
  383. verbose("(%02x) call %d\n", insn->code, insn->imm);
  384. } else if (insn->code == (BPF_JMP | BPF_JA)) {
  385. verbose("(%02x) goto pc%+d\n",
  386. insn->code, insn->off);
  387. } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
  388. verbose("(%02x) exit\n", insn->code);
  389. } else if (BPF_SRC(insn->code) == BPF_X) {
  390. verbose("(%02x) if r%d %s r%d goto pc%+d\n",
  391. insn->code, insn->dst_reg,
  392. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  393. insn->src_reg, insn->off);
  394. } else {
  395. verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
  396. insn->code, insn->dst_reg,
  397. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  398. insn->imm, insn->off);
  399. }
  400. } else {
  401. verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
  402. }
  403. }
  404. static int pop_stack(struct verifier_env *env, int *prev_insn_idx)
  405. {
  406. struct verifier_stack_elem *elem;
  407. int insn_idx;
  408. if (env->head == NULL)
  409. return -1;
  410. memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
  411. insn_idx = env->head->insn_idx;
  412. if (prev_insn_idx)
  413. *prev_insn_idx = env->head->prev_insn_idx;
  414. elem = env->head->next;
  415. kfree(env->head);
  416. env->head = elem;
  417. env->stack_size--;
  418. return insn_idx;
  419. }
  420. static struct verifier_state *push_stack(struct verifier_env *env, int insn_idx,
  421. int prev_insn_idx)
  422. {
  423. struct verifier_stack_elem *elem;
  424. elem = kmalloc(sizeof(struct verifier_stack_elem), GFP_KERNEL);
  425. if (!elem)
  426. goto err;
  427. memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
  428. elem->insn_idx = insn_idx;
  429. elem->prev_insn_idx = prev_insn_idx;
  430. elem->next = env->head;
  431. env->head = elem;
  432. env->stack_size++;
  433. if (env->stack_size > 1024) {
  434. verbose("BPF program is too complex\n");
  435. goto err;
  436. }
  437. return &elem->st;
  438. err:
  439. /* pop all elements and return */
  440. while (pop_stack(env, NULL) >= 0);
  441. return NULL;
  442. }
  443. #define CALLER_SAVED_REGS 6
  444. static const int caller_saved[CALLER_SAVED_REGS] = {
  445. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  446. };
  447. static void init_reg_state(struct reg_state *regs)
  448. {
  449. int i;
  450. for (i = 0; i < MAX_BPF_REG; i++) {
  451. regs[i].type = NOT_INIT;
  452. regs[i].imm = 0;
  453. regs[i].map_ptr = NULL;
  454. }
  455. /* frame pointer */
  456. regs[BPF_REG_FP].type = FRAME_PTR;
  457. /* 1st arg to a function */
  458. regs[BPF_REG_1].type = PTR_TO_CTX;
  459. }
  460. static void mark_reg_unknown_value(struct reg_state *regs, u32 regno)
  461. {
  462. BUG_ON(regno >= MAX_BPF_REG);
  463. regs[regno].type = UNKNOWN_VALUE;
  464. regs[regno].imm = 0;
  465. regs[regno].map_ptr = NULL;
  466. }
  467. enum reg_arg_type {
  468. SRC_OP, /* register is used as source operand */
  469. DST_OP, /* register is used as destination operand */
  470. DST_OP_NO_MARK /* same as above, check only, don't mark */
  471. };
  472. static int check_reg_arg(struct reg_state *regs, u32 regno,
  473. enum reg_arg_type t)
  474. {
  475. if (regno >= MAX_BPF_REG) {
  476. verbose("R%d is invalid\n", regno);
  477. return -EINVAL;
  478. }
  479. if (t == SRC_OP) {
  480. /* check whether register used as source operand can be read */
  481. if (regs[regno].type == NOT_INIT) {
  482. verbose("R%d !read_ok\n", regno);
  483. return -EACCES;
  484. }
  485. } else {
  486. /* check whether register used as dest operand can be written to */
  487. if (regno == BPF_REG_FP) {
  488. verbose("frame pointer is read only\n");
  489. return -EACCES;
  490. }
  491. if (t == DST_OP)
  492. mark_reg_unknown_value(regs, regno);
  493. }
  494. return 0;
  495. }
  496. static int bpf_size_to_bytes(int bpf_size)
  497. {
  498. if (bpf_size == BPF_W)
  499. return 4;
  500. else if (bpf_size == BPF_H)
  501. return 2;
  502. else if (bpf_size == BPF_B)
  503. return 1;
  504. else if (bpf_size == BPF_DW)
  505. return 8;
  506. else
  507. return -EINVAL;
  508. }
  509. static bool is_spillable_regtype(enum bpf_reg_type type)
  510. {
  511. switch (type) {
  512. case PTR_TO_MAP_VALUE:
  513. case PTR_TO_MAP_VALUE_OR_NULL:
  514. case PTR_TO_STACK:
  515. case PTR_TO_CTX:
  516. case FRAME_PTR:
  517. case CONST_PTR_TO_MAP:
  518. return true;
  519. default:
  520. return false;
  521. }
  522. }
  523. /* check_stack_read/write functions track spill/fill of registers,
  524. * stack boundary and alignment are checked in check_mem_access()
  525. */
  526. static int check_stack_write(struct verifier_env *env,
  527. struct verifier_state *state, int off,
  528. int size, int value_regno, int insn_idx)
  529. {
  530. int i, spi = (MAX_BPF_STACK + off) / BPF_REG_SIZE;
  531. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  532. * so it's aligned access and [off, off + size) are within stack limits
  533. */
  534. if (value_regno >= 0 &&
  535. is_spillable_regtype(state->regs[value_regno].type)) {
  536. /* register containing pointer is being spilled into stack */
  537. if (size != BPF_REG_SIZE) {
  538. verbose("invalid size of register spill\n");
  539. return -EACCES;
  540. }
  541. /* save register state */
  542. state->spilled_regs[spi] = state->regs[value_regno];
  543. for (i = 0; i < BPF_REG_SIZE; i++) {
  544. if (state->stack_slot_type[MAX_BPF_STACK + off + i] == STACK_MISC &&
  545. !env->allow_ptr_leaks) {
  546. int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
  547. int soff = (-spi - 1) * BPF_REG_SIZE;
  548. /* detected reuse of integer stack slot with a pointer
  549. * which means either llvm is reusing stack slot or
  550. * an attacker is trying to exploit CVE-2018-3639
  551. * (speculative store bypass)
  552. * Have to sanitize that slot with preemptive
  553. * store of zero.
  554. */
  555. if (*poff && *poff != soff) {
  556. /* disallow programs where single insn stores
  557. * into two different stack slots, since verifier
  558. * cannot sanitize them
  559. */
  560. verbose("insn %d cannot access two stack slots fp%d and fp%d",
  561. insn_idx, *poff, soff);
  562. return -EINVAL;
  563. }
  564. *poff = soff;
  565. }
  566. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
  567. }
  568. } else {
  569. /* regular write of data into stack */
  570. state->spilled_regs[spi] = (struct reg_state) {};
  571. for (i = 0; i < size; i++)
  572. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
  573. }
  574. return 0;
  575. }
  576. static int check_stack_read(struct verifier_state *state, int off, int size,
  577. int value_regno)
  578. {
  579. u8 *slot_type;
  580. int i;
  581. slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
  582. if (slot_type[0] == STACK_SPILL) {
  583. if (size != BPF_REG_SIZE) {
  584. verbose("invalid size of register spill\n");
  585. return -EACCES;
  586. }
  587. for (i = 1; i < BPF_REG_SIZE; i++) {
  588. if (slot_type[i] != STACK_SPILL) {
  589. verbose("corrupted spill memory\n");
  590. return -EACCES;
  591. }
  592. }
  593. if (value_regno >= 0)
  594. /* restore register state from stack */
  595. state->regs[value_regno] =
  596. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
  597. return 0;
  598. } else {
  599. for (i = 0; i < size; i++) {
  600. if (slot_type[i] != STACK_MISC) {
  601. verbose("invalid read from stack off %d+%d size %d\n",
  602. off, i, size);
  603. return -EACCES;
  604. }
  605. }
  606. if (value_regno >= 0)
  607. /* have read misc data from the stack */
  608. mark_reg_unknown_value(state->regs, value_regno);
  609. return 0;
  610. }
  611. }
  612. /* check read/write into map element returned by bpf_map_lookup_elem() */
  613. static int check_map_access(struct verifier_env *env, u32 regno, int off,
  614. int size)
  615. {
  616. struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
  617. if (off < 0 || off + size > map->value_size) {
  618. verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
  619. map->value_size, off, size);
  620. return -EACCES;
  621. }
  622. return 0;
  623. }
  624. /* check access to 'struct bpf_context' fields */
  625. static int check_ctx_access(struct verifier_env *env, int off, int size,
  626. enum bpf_access_type t)
  627. {
  628. if (env->prog->aux->ops->is_valid_access &&
  629. env->prog->aux->ops->is_valid_access(off, size, t))
  630. return 0;
  631. verbose("invalid bpf_context access off=%d size=%d\n", off, size);
  632. return -EACCES;
  633. }
  634. static bool is_pointer_value(struct verifier_env *env, int regno)
  635. {
  636. if (env->allow_ptr_leaks)
  637. return false;
  638. switch (env->cur_state.regs[regno].type) {
  639. case UNKNOWN_VALUE:
  640. case CONST_IMM:
  641. return false;
  642. default:
  643. return true;
  644. }
  645. }
  646. static bool is_ctx_reg(struct verifier_env *env, int regno)
  647. {
  648. const struct reg_state *reg = &env->cur_state.regs[regno];
  649. return reg->type == PTR_TO_CTX;
  650. }
  651. /* check whether memory at (regno + off) is accessible for t = (read | write)
  652. * if t==write, value_regno is a register which value is stored into memory
  653. * if t==read, value_regno is a register which will receive the value from memory
  654. * if t==write && value_regno==-1, some unknown value is stored into memory
  655. * if t==read && value_regno==-1, don't care what we read from memory
  656. */
  657. static int check_mem_access(struct verifier_env *env, int insn_idx, u32 regno, int off,
  658. int bpf_size, enum bpf_access_type t,
  659. int value_regno)
  660. {
  661. struct verifier_state *state = &env->cur_state;
  662. int size, err = 0;
  663. if (state->regs[regno].type == PTR_TO_STACK)
  664. off += state->regs[regno].imm;
  665. size = bpf_size_to_bytes(bpf_size);
  666. if (size < 0)
  667. return size;
  668. if (off % size != 0) {
  669. verbose("misaligned access off %d size %d\n", off, size);
  670. return -EACCES;
  671. }
  672. if (state->regs[regno].type == PTR_TO_MAP_VALUE) {
  673. if (t == BPF_WRITE && value_regno >= 0 &&
  674. is_pointer_value(env, value_regno)) {
  675. verbose("R%d leaks addr into map\n", value_regno);
  676. return -EACCES;
  677. }
  678. err = check_map_access(env, regno, off, size);
  679. if (!err && t == BPF_READ && value_regno >= 0)
  680. mark_reg_unknown_value(state->regs, value_regno);
  681. } else if (state->regs[regno].type == PTR_TO_CTX) {
  682. if (t == BPF_WRITE && value_regno >= 0 &&
  683. is_pointer_value(env, value_regno)) {
  684. verbose("R%d leaks addr into ctx\n", value_regno);
  685. return -EACCES;
  686. }
  687. err = check_ctx_access(env, off, size, t);
  688. if (!err && t == BPF_READ && value_regno >= 0)
  689. mark_reg_unknown_value(state->regs, value_regno);
  690. } else if (state->regs[regno].type == FRAME_PTR ||
  691. state->regs[regno].type == PTR_TO_STACK) {
  692. if (off >= 0 || off < -MAX_BPF_STACK) {
  693. verbose("invalid stack off=%d size=%d\n", off, size);
  694. return -EACCES;
  695. }
  696. if (t == BPF_WRITE) {
  697. if (!env->allow_ptr_leaks &&
  698. state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
  699. size != BPF_REG_SIZE) {
  700. verbose("attempt to corrupt spilled pointer on stack\n");
  701. return -EACCES;
  702. }
  703. err = check_stack_write(env, state, off, size,
  704. value_regno, insn_idx);
  705. } else {
  706. err = check_stack_read(state, off, size, value_regno);
  707. }
  708. } else {
  709. verbose("R%d invalid mem access '%s'\n",
  710. regno, reg_type_str[state->regs[regno].type]);
  711. return -EACCES;
  712. }
  713. return err;
  714. }
  715. static int check_xadd(struct verifier_env *env, int insn_idx, struct bpf_insn *insn)
  716. {
  717. struct reg_state *regs = env->cur_state.regs;
  718. int err;
  719. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  720. insn->imm != 0) {
  721. verbose("BPF_XADD uses reserved fields\n");
  722. return -EINVAL;
  723. }
  724. /* check src1 operand */
  725. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  726. if (err)
  727. return err;
  728. /* check src2 operand */
  729. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  730. if (err)
  731. return err;
  732. if (is_pointer_value(env, insn->src_reg)) {
  733. verbose("R%d leaks addr into mem\n", insn->src_reg);
  734. return -EACCES;
  735. }
  736. if (is_ctx_reg(env, insn->dst_reg)) {
  737. verbose("BPF_XADD stores into R%d context is not allowed\n",
  738. insn->dst_reg);
  739. return -EACCES;
  740. }
  741. /* check whether atomic_add can read the memory */
  742. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  743. BPF_SIZE(insn->code), BPF_READ, -1);
  744. if (err)
  745. return err;
  746. /* check whether atomic_add can write into the same memory */
  747. return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  748. BPF_SIZE(insn->code), BPF_WRITE, -1);
  749. }
  750. /* when register 'regno' is passed into function that will read 'access_size'
  751. * bytes from that pointer, make sure that it's within stack boundary
  752. * and all elements of stack are initialized
  753. */
  754. static int check_stack_boundary(struct verifier_env *env,
  755. int regno, int access_size)
  756. {
  757. struct verifier_state *state = &env->cur_state;
  758. struct reg_state *regs = state->regs;
  759. int off, i;
  760. if (regs[regno].type != PTR_TO_STACK)
  761. return -EACCES;
  762. off = regs[regno].imm;
  763. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  764. access_size <= 0) {
  765. verbose("invalid stack type R%d off=%d access_size=%d\n",
  766. regno, off, access_size);
  767. return -EACCES;
  768. }
  769. for (i = 0; i < access_size; i++) {
  770. if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
  771. verbose("invalid indirect read from stack off %d+%d size %d\n",
  772. off, i, access_size);
  773. return -EACCES;
  774. }
  775. }
  776. return 0;
  777. }
  778. static int check_func_arg(struct verifier_env *env, u32 regno,
  779. enum bpf_arg_type arg_type, struct bpf_map **mapp)
  780. {
  781. struct reg_state *reg = env->cur_state.regs + regno;
  782. enum bpf_reg_type expected_type;
  783. int err = 0;
  784. if (arg_type == ARG_DONTCARE)
  785. return 0;
  786. if (reg->type == NOT_INIT) {
  787. verbose("R%d !read_ok\n", regno);
  788. return -EACCES;
  789. }
  790. if (arg_type == ARG_ANYTHING) {
  791. if (is_pointer_value(env, regno)) {
  792. verbose("R%d leaks addr into helper function\n", regno);
  793. return -EACCES;
  794. }
  795. return 0;
  796. }
  797. if (arg_type == ARG_PTR_TO_STACK || arg_type == ARG_PTR_TO_MAP_KEY ||
  798. arg_type == ARG_PTR_TO_MAP_VALUE) {
  799. expected_type = PTR_TO_STACK;
  800. } else if (arg_type == ARG_CONST_STACK_SIZE) {
  801. expected_type = CONST_IMM;
  802. } else if (arg_type == ARG_CONST_MAP_PTR) {
  803. expected_type = CONST_PTR_TO_MAP;
  804. } else if (arg_type == ARG_PTR_TO_CTX) {
  805. expected_type = PTR_TO_CTX;
  806. } else {
  807. verbose("unsupported arg_type %d\n", arg_type);
  808. return -EFAULT;
  809. }
  810. if (reg->type != expected_type) {
  811. verbose("R%d type=%s expected=%s\n", regno,
  812. reg_type_str[reg->type], reg_type_str[expected_type]);
  813. return -EACCES;
  814. }
  815. if (arg_type == ARG_CONST_MAP_PTR) {
  816. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  817. *mapp = reg->map_ptr;
  818. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  819. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  820. * check that [key, key + map->key_size) are within
  821. * stack limits and initialized
  822. */
  823. if (!*mapp) {
  824. /* in function declaration map_ptr must come before
  825. * map_key, so that it's verified and known before
  826. * we have to check map_key here. Otherwise it means
  827. * that kernel subsystem misconfigured verifier
  828. */
  829. verbose("invalid map_ptr to access map->key\n");
  830. return -EACCES;
  831. }
  832. err = check_stack_boundary(env, regno, (*mapp)->key_size);
  833. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  834. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  835. * check [value, value + map->value_size) validity
  836. */
  837. if (!*mapp) {
  838. /* kernel subsystem misconfigured verifier */
  839. verbose("invalid map_ptr to access map->value\n");
  840. return -EACCES;
  841. }
  842. err = check_stack_boundary(env, regno, (*mapp)->value_size);
  843. } else if (arg_type == ARG_CONST_STACK_SIZE) {
  844. /* bpf_xxx(..., buf, len) call will access 'len' bytes
  845. * from stack pointer 'buf'. Check it
  846. * note: regno == len, regno - 1 == buf
  847. */
  848. if (regno == 0) {
  849. /* kernel subsystem misconfigured verifier */
  850. verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
  851. return -EACCES;
  852. }
  853. err = check_stack_boundary(env, regno - 1, reg->imm);
  854. }
  855. return err;
  856. }
  857. static int check_map_func_compatibility(struct bpf_map *map, int func_id)
  858. {
  859. if (!map)
  860. return 0;
  861. /* We need a two way check, first is from map perspective ... */
  862. switch (map->map_type) {
  863. case BPF_MAP_TYPE_PROG_ARRAY:
  864. if (func_id != BPF_FUNC_tail_call)
  865. goto error;
  866. break;
  867. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  868. if (func_id != BPF_FUNC_perf_event_read &&
  869. func_id != BPF_FUNC_perf_event_output)
  870. goto error;
  871. break;
  872. default:
  873. break;
  874. }
  875. /* ... and second from the function itself. */
  876. switch (func_id) {
  877. case BPF_FUNC_tail_call:
  878. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  879. goto error;
  880. break;
  881. case BPF_FUNC_perf_event_read:
  882. case BPF_FUNC_perf_event_output:
  883. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  884. goto error;
  885. break;
  886. default:
  887. break;
  888. }
  889. return 0;
  890. error:
  891. verbose("cannot pass map_type %d into func %d\n",
  892. map->map_type, func_id);
  893. return -EINVAL;
  894. }
  895. static int check_call(struct verifier_env *env, int func_id, int insn_idx)
  896. {
  897. struct verifier_state *state = &env->cur_state;
  898. const struct bpf_func_proto *fn = NULL;
  899. struct reg_state *regs = state->regs;
  900. struct bpf_map *map = NULL;
  901. struct reg_state *reg;
  902. int i, err;
  903. /* find function prototype */
  904. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  905. verbose("invalid func %d\n", func_id);
  906. return -EINVAL;
  907. }
  908. if (env->prog->aux->ops->get_func_proto)
  909. fn = env->prog->aux->ops->get_func_proto(func_id);
  910. if (!fn) {
  911. verbose("unknown func %d\n", func_id);
  912. return -EINVAL;
  913. }
  914. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  915. if (!env->prog->gpl_compatible && fn->gpl_only) {
  916. verbose("cannot call GPL only function from proprietary program\n");
  917. return -EINVAL;
  918. }
  919. /* check args */
  920. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &map);
  921. if (err)
  922. return err;
  923. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &map);
  924. if (err)
  925. return err;
  926. if (func_id == BPF_FUNC_tail_call) {
  927. if (map == NULL) {
  928. verbose("verifier bug\n");
  929. return -EINVAL;
  930. }
  931. env->insn_aux_data[insn_idx].map_ptr = map;
  932. }
  933. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &map);
  934. if (err)
  935. return err;
  936. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &map);
  937. if (err)
  938. return err;
  939. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &map);
  940. if (err)
  941. return err;
  942. /* reset caller saved regs */
  943. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  944. reg = regs + caller_saved[i];
  945. reg->type = NOT_INIT;
  946. reg->imm = 0;
  947. }
  948. /* update return register */
  949. if (fn->ret_type == RET_INTEGER) {
  950. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  951. } else if (fn->ret_type == RET_VOID) {
  952. regs[BPF_REG_0].type = NOT_INIT;
  953. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  954. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  955. /* remember map_ptr, so that check_map_access()
  956. * can check 'value_size' boundary of memory access
  957. * to map element returned from bpf_map_lookup_elem()
  958. */
  959. if (map == NULL) {
  960. verbose("kernel subsystem misconfigured verifier\n");
  961. return -EINVAL;
  962. }
  963. regs[BPF_REG_0].map_ptr = map;
  964. } else {
  965. verbose("unknown return type %d of func %d\n",
  966. fn->ret_type, func_id);
  967. return -EINVAL;
  968. }
  969. err = check_map_func_compatibility(map, func_id);
  970. if (err)
  971. return err;
  972. return 0;
  973. }
  974. /* check validity of 32-bit and 64-bit arithmetic operations */
  975. static int check_alu_op(struct verifier_env *env, struct bpf_insn *insn)
  976. {
  977. struct reg_state *regs = env->cur_state.regs;
  978. u8 opcode = BPF_OP(insn->code);
  979. int err;
  980. if (opcode == BPF_END || opcode == BPF_NEG) {
  981. if (opcode == BPF_NEG) {
  982. if (BPF_SRC(insn->code) != 0 ||
  983. insn->src_reg != BPF_REG_0 ||
  984. insn->off != 0 || insn->imm != 0) {
  985. verbose("BPF_NEG uses reserved fields\n");
  986. return -EINVAL;
  987. }
  988. } else {
  989. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  990. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
  991. BPF_CLASS(insn->code) == BPF_ALU64) {
  992. verbose("BPF_END uses reserved fields\n");
  993. return -EINVAL;
  994. }
  995. }
  996. /* check src operand */
  997. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  998. if (err)
  999. return err;
  1000. if (is_pointer_value(env, insn->dst_reg)) {
  1001. verbose("R%d pointer arithmetic prohibited\n",
  1002. insn->dst_reg);
  1003. return -EACCES;
  1004. }
  1005. /* check dest operand */
  1006. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1007. if (err)
  1008. return err;
  1009. } else if (opcode == BPF_MOV) {
  1010. if (BPF_SRC(insn->code) == BPF_X) {
  1011. if (insn->imm != 0 || insn->off != 0) {
  1012. verbose("BPF_MOV uses reserved fields\n");
  1013. return -EINVAL;
  1014. }
  1015. /* check src operand */
  1016. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1017. if (err)
  1018. return err;
  1019. } else {
  1020. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  1021. verbose("BPF_MOV uses reserved fields\n");
  1022. return -EINVAL;
  1023. }
  1024. }
  1025. /* check dest operand */
  1026. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1027. if (err)
  1028. return err;
  1029. if (BPF_SRC(insn->code) == BPF_X) {
  1030. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  1031. /* case: R1 = R2
  1032. * copy register state to dest reg
  1033. */
  1034. regs[insn->dst_reg] = regs[insn->src_reg];
  1035. } else {
  1036. if (is_pointer_value(env, insn->src_reg)) {
  1037. verbose("R%d partial copy of pointer\n",
  1038. insn->src_reg);
  1039. return -EACCES;
  1040. }
  1041. regs[insn->dst_reg].type = UNKNOWN_VALUE;
  1042. regs[insn->dst_reg].map_ptr = NULL;
  1043. }
  1044. } else if (BPF_CLASS(insn->code) == BPF_ALU64 ||
  1045. insn->imm >= 0) {
  1046. /* case: R = imm
  1047. * remember the value we stored into this reg
  1048. */
  1049. regs[insn->dst_reg].type = CONST_IMM;
  1050. regs[insn->dst_reg].imm = insn->imm;
  1051. }
  1052. } else if (opcode > BPF_END) {
  1053. verbose("invalid BPF_ALU opcode %x\n", opcode);
  1054. return -EINVAL;
  1055. } else { /* all other ALU ops: and, sub, xor, add, ... */
  1056. bool stack_relative = false;
  1057. if (BPF_SRC(insn->code) == BPF_X) {
  1058. if (insn->imm != 0 || insn->off != 0) {
  1059. verbose("BPF_ALU uses reserved fields\n");
  1060. return -EINVAL;
  1061. }
  1062. /* check src1 operand */
  1063. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1064. if (err)
  1065. return err;
  1066. } else {
  1067. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  1068. verbose("BPF_ALU uses reserved fields\n");
  1069. return -EINVAL;
  1070. }
  1071. }
  1072. /* check src2 operand */
  1073. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1074. if (err)
  1075. return err;
  1076. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  1077. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  1078. verbose("div by zero\n");
  1079. return -EINVAL;
  1080. }
  1081. if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
  1082. verbose("BPF_ARSH not supported for 32 bit ALU\n");
  1083. return -EINVAL;
  1084. }
  1085. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  1086. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  1087. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  1088. if (insn->imm < 0 || insn->imm >= size) {
  1089. verbose("invalid shift %d\n", insn->imm);
  1090. return -EINVAL;
  1091. }
  1092. }
  1093. /* pattern match 'bpf_add Rx, imm' instruction */
  1094. if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
  1095. regs[insn->dst_reg].type == FRAME_PTR &&
  1096. BPF_SRC(insn->code) == BPF_K) {
  1097. stack_relative = true;
  1098. } else if (is_pointer_value(env, insn->dst_reg)) {
  1099. verbose("R%d pointer arithmetic prohibited\n",
  1100. insn->dst_reg);
  1101. return -EACCES;
  1102. } else if (BPF_SRC(insn->code) == BPF_X &&
  1103. is_pointer_value(env, insn->src_reg)) {
  1104. verbose("R%d pointer arithmetic prohibited\n",
  1105. insn->src_reg);
  1106. return -EACCES;
  1107. }
  1108. /* check dest operand */
  1109. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1110. if (err)
  1111. return err;
  1112. if (stack_relative) {
  1113. regs[insn->dst_reg].type = PTR_TO_STACK;
  1114. regs[insn->dst_reg].imm = insn->imm;
  1115. }
  1116. }
  1117. return 0;
  1118. }
  1119. static int check_cond_jmp_op(struct verifier_env *env,
  1120. struct bpf_insn *insn, int *insn_idx)
  1121. {
  1122. struct reg_state *regs = env->cur_state.regs;
  1123. struct verifier_state *other_branch;
  1124. u8 opcode = BPF_OP(insn->code);
  1125. int err;
  1126. if (opcode > BPF_EXIT) {
  1127. verbose("invalid BPF_JMP opcode %x\n", opcode);
  1128. return -EINVAL;
  1129. }
  1130. if (BPF_SRC(insn->code) == BPF_X) {
  1131. if (insn->imm != 0) {
  1132. verbose("BPF_JMP uses reserved fields\n");
  1133. return -EINVAL;
  1134. }
  1135. /* check src1 operand */
  1136. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1137. if (err)
  1138. return err;
  1139. if (is_pointer_value(env, insn->src_reg)) {
  1140. verbose("R%d pointer comparison prohibited\n",
  1141. insn->src_reg);
  1142. return -EACCES;
  1143. }
  1144. } else {
  1145. if (insn->src_reg != BPF_REG_0) {
  1146. verbose("BPF_JMP uses reserved fields\n");
  1147. return -EINVAL;
  1148. }
  1149. }
  1150. /* check src2 operand */
  1151. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1152. if (err)
  1153. return err;
  1154. /* detect if R == 0 where R was initialized to zero earlier */
  1155. if (BPF_SRC(insn->code) == BPF_K &&
  1156. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  1157. regs[insn->dst_reg].type == CONST_IMM &&
  1158. regs[insn->dst_reg].imm == insn->imm) {
  1159. if (opcode == BPF_JEQ) {
  1160. /* if (imm == imm) goto pc+off;
  1161. * only follow the goto, ignore fall-through
  1162. */
  1163. *insn_idx += insn->off;
  1164. return 0;
  1165. } else {
  1166. /* if (imm != imm) goto pc+off;
  1167. * only follow fall-through branch, since
  1168. * that's where the program will go
  1169. */
  1170. return 0;
  1171. }
  1172. }
  1173. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  1174. if (!other_branch)
  1175. return -EFAULT;
  1176. /* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
  1177. if (BPF_SRC(insn->code) == BPF_K &&
  1178. insn->imm == 0 && (opcode == BPF_JEQ ||
  1179. opcode == BPF_JNE) &&
  1180. regs[insn->dst_reg].type == PTR_TO_MAP_VALUE_OR_NULL) {
  1181. if (opcode == BPF_JEQ) {
  1182. /* next fallthrough insn can access memory via
  1183. * this register
  1184. */
  1185. regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1186. /* branch targer cannot access it, since reg == 0 */
  1187. other_branch->regs[insn->dst_reg].type = CONST_IMM;
  1188. other_branch->regs[insn->dst_reg].imm = 0;
  1189. } else {
  1190. other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1191. regs[insn->dst_reg].type = CONST_IMM;
  1192. regs[insn->dst_reg].imm = 0;
  1193. }
  1194. } else if (is_pointer_value(env, insn->dst_reg)) {
  1195. verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
  1196. return -EACCES;
  1197. } else if (BPF_SRC(insn->code) == BPF_K &&
  1198. (opcode == BPF_JEQ || opcode == BPF_JNE)) {
  1199. if (opcode == BPF_JEQ) {
  1200. /* detect if (R == imm) goto
  1201. * and in the target state recognize that R = imm
  1202. */
  1203. other_branch->regs[insn->dst_reg].type = CONST_IMM;
  1204. other_branch->regs[insn->dst_reg].imm = insn->imm;
  1205. } else {
  1206. /* detect if (R != imm) goto
  1207. * and in the fall-through state recognize that R = imm
  1208. */
  1209. regs[insn->dst_reg].type = CONST_IMM;
  1210. regs[insn->dst_reg].imm = insn->imm;
  1211. }
  1212. }
  1213. if (log_level)
  1214. print_verifier_state(env);
  1215. return 0;
  1216. }
  1217. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  1218. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  1219. {
  1220. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  1221. return (struct bpf_map *) (unsigned long) imm64;
  1222. }
  1223. /* verify BPF_LD_IMM64 instruction */
  1224. static int check_ld_imm(struct verifier_env *env, struct bpf_insn *insn)
  1225. {
  1226. struct reg_state *regs = env->cur_state.regs;
  1227. int err;
  1228. if (BPF_SIZE(insn->code) != BPF_DW) {
  1229. verbose("invalid BPF_LD_IMM insn\n");
  1230. return -EINVAL;
  1231. }
  1232. if (insn->off != 0) {
  1233. verbose("BPF_LD_IMM64 uses reserved fields\n");
  1234. return -EINVAL;
  1235. }
  1236. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1237. if (err)
  1238. return err;
  1239. if (insn->src_reg == 0)
  1240. /* generic move 64-bit immediate into a register */
  1241. return 0;
  1242. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  1243. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  1244. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  1245. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  1246. return 0;
  1247. }
  1248. static bool may_access_skb(enum bpf_prog_type type)
  1249. {
  1250. switch (type) {
  1251. case BPF_PROG_TYPE_SOCKET_FILTER:
  1252. case BPF_PROG_TYPE_SCHED_CLS:
  1253. case BPF_PROG_TYPE_SCHED_ACT:
  1254. return true;
  1255. default:
  1256. return false;
  1257. }
  1258. }
  1259. /* verify safety of LD_ABS|LD_IND instructions:
  1260. * - they can only appear in the programs where ctx == skb
  1261. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  1262. * preserve R6-R9, and store return value into R0
  1263. *
  1264. * Implicit input:
  1265. * ctx == skb == R6 == CTX
  1266. *
  1267. * Explicit input:
  1268. * SRC == any register
  1269. * IMM == 32-bit immediate
  1270. *
  1271. * Output:
  1272. * R0 - 8/16/32-bit skb data converted to cpu endianness
  1273. */
  1274. static int check_ld_abs(struct verifier_env *env, struct bpf_insn *insn)
  1275. {
  1276. struct reg_state *regs = env->cur_state.regs;
  1277. u8 mode = BPF_MODE(insn->code);
  1278. struct reg_state *reg;
  1279. int i, err;
  1280. if (!may_access_skb(env->prog->type)) {
  1281. verbose("BPF_LD_ABS|IND instructions not allowed for this program type\n");
  1282. return -EINVAL;
  1283. }
  1284. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  1285. BPF_SIZE(insn->code) == BPF_DW ||
  1286. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  1287. verbose("BPF_LD_ABS uses reserved fields\n");
  1288. return -EINVAL;
  1289. }
  1290. /* check whether implicit source operand (register R6) is readable */
  1291. err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
  1292. if (err)
  1293. return err;
  1294. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  1295. verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  1296. return -EINVAL;
  1297. }
  1298. if (mode == BPF_IND) {
  1299. /* check explicit source operand */
  1300. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1301. if (err)
  1302. return err;
  1303. }
  1304. /* reset caller saved regs to unreadable */
  1305. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  1306. reg = regs + caller_saved[i];
  1307. reg->type = NOT_INIT;
  1308. reg->imm = 0;
  1309. }
  1310. /* mark destination R0 register as readable, since it contains
  1311. * the value fetched from the packet
  1312. */
  1313. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  1314. return 0;
  1315. }
  1316. /* non-recursive DFS pseudo code
  1317. * 1 procedure DFS-iterative(G,v):
  1318. * 2 label v as discovered
  1319. * 3 let S be a stack
  1320. * 4 S.push(v)
  1321. * 5 while S is not empty
  1322. * 6 t <- S.pop()
  1323. * 7 if t is what we're looking for:
  1324. * 8 return t
  1325. * 9 for all edges e in G.adjacentEdges(t) do
  1326. * 10 if edge e is already labelled
  1327. * 11 continue with the next edge
  1328. * 12 w <- G.adjacentVertex(t,e)
  1329. * 13 if vertex w is not discovered and not explored
  1330. * 14 label e as tree-edge
  1331. * 15 label w as discovered
  1332. * 16 S.push(w)
  1333. * 17 continue at 5
  1334. * 18 else if vertex w is discovered
  1335. * 19 label e as back-edge
  1336. * 20 else
  1337. * 21 // vertex w is explored
  1338. * 22 label e as forward- or cross-edge
  1339. * 23 label t as explored
  1340. * 24 S.pop()
  1341. *
  1342. * convention:
  1343. * 0x10 - discovered
  1344. * 0x11 - discovered and fall-through edge labelled
  1345. * 0x12 - discovered and fall-through and branch edges labelled
  1346. * 0x20 - explored
  1347. */
  1348. enum {
  1349. DISCOVERED = 0x10,
  1350. EXPLORED = 0x20,
  1351. FALLTHROUGH = 1,
  1352. BRANCH = 2,
  1353. };
  1354. #define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
  1355. static int *insn_stack; /* stack of insns to process */
  1356. static int cur_stack; /* current stack index */
  1357. static int *insn_state;
  1358. /* t, w, e - match pseudo-code above:
  1359. * t - index of current instruction
  1360. * w - next instruction
  1361. * e - edge
  1362. */
  1363. static int push_insn(int t, int w, int e, struct verifier_env *env)
  1364. {
  1365. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  1366. return 0;
  1367. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  1368. return 0;
  1369. if (w < 0 || w >= env->prog->len) {
  1370. verbose("jump out of range from insn %d to %d\n", t, w);
  1371. return -EINVAL;
  1372. }
  1373. if (e == BRANCH)
  1374. /* mark branch target for state pruning */
  1375. env->explored_states[w] = STATE_LIST_MARK;
  1376. if (insn_state[w] == 0) {
  1377. /* tree-edge */
  1378. insn_state[t] = DISCOVERED | e;
  1379. insn_state[w] = DISCOVERED;
  1380. if (cur_stack >= env->prog->len)
  1381. return -E2BIG;
  1382. insn_stack[cur_stack++] = w;
  1383. return 1;
  1384. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  1385. verbose("back-edge from insn %d to %d\n", t, w);
  1386. return -EINVAL;
  1387. } else if (insn_state[w] == EXPLORED) {
  1388. /* forward- or cross-edge */
  1389. insn_state[t] = DISCOVERED | e;
  1390. } else {
  1391. verbose("insn state internal bug\n");
  1392. return -EFAULT;
  1393. }
  1394. return 0;
  1395. }
  1396. /* non-recursive depth-first-search to detect loops in BPF program
  1397. * loop == back-edge in directed graph
  1398. */
  1399. static int check_cfg(struct verifier_env *env)
  1400. {
  1401. struct bpf_insn *insns = env->prog->insnsi;
  1402. int insn_cnt = env->prog->len;
  1403. int ret = 0;
  1404. int i, t;
  1405. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1406. if (!insn_state)
  1407. return -ENOMEM;
  1408. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1409. if (!insn_stack) {
  1410. kfree(insn_state);
  1411. return -ENOMEM;
  1412. }
  1413. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  1414. insn_stack[0] = 0; /* 0 is the first instruction */
  1415. cur_stack = 1;
  1416. peek_stack:
  1417. if (cur_stack == 0)
  1418. goto check_state;
  1419. t = insn_stack[cur_stack - 1];
  1420. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  1421. u8 opcode = BPF_OP(insns[t].code);
  1422. if (opcode == BPF_EXIT) {
  1423. goto mark_explored;
  1424. } else if (opcode == BPF_CALL) {
  1425. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1426. if (ret == 1)
  1427. goto peek_stack;
  1428. else if (ret < 0)
  1429. goto err_free;
  1430. } else if (opcode == BPF_JA) {
  1431. if (BPF_SRC(insns[t].code) != BPF_K) {
  1432. ret = -EINVAL;
  1433. goto err_free;
  1434. }
  1435. /* unconditional jump with single edge */
  1436. ret = push_insn(t, t + insns[t].off + 1,
  1437. FALLTHROUGH, env);
  1438. if (ret == 1)
  1439. goto peek_stack;
  1440. else if (ret < 0)
  1441. goto err_free;
  1442. /* tell verifier to check for equivalent states
  1443. * after every call and jump
  1444. */
  1445. if (t + 1 < insn_cnt)
  1446. env->explored_states[t + 1] = STATE_LIST_MARK;
  1447. } else {
  1448. /* conditional jump with two edges */
  1449. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1450. if (ret == 1)
  1451. goto peek_stack;
  1452. else if (ret < 0)
  1453. goto err_free;
  1454. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  1455. if (ret == 1)
  1456. goto peek_stack;
  1457. else if (ret < 0)
  1458. goto err_free;
  1459. }
  1460. } else {
  1461. /* all other non-branch instructions with single
  1462. * fall-through edge
  1463. */
  1464. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1465. if (ret == 1)
  1466. goto peek_stack;
  1467. else if (ret < 0)
  1468. goto err_free;
  1469. }
  1470. mark_explored:
  1471. insn_state[t] = EXPLORED;
  1472. if (cur_stack-- <= 0) {
  1473. verbose("pop stack internal bug\n");
  1474. ret = -EFAULT;
  1475. goto err_free;
  1476. }
  1477. goto peek_stack;
  1478. check_state:
  1479. for (i = 0; i < insn_cnt; i++) {
  1480. if (insn_state[i] != EXPLORED) {
  1481. verbose("unreachable insn %d\n", i);
  1482. ret = -EINVAL;
  1483. goto err_free;
  1484. }
  1485. }
  1486. ret = 0; /* cfg looks good */
  1487. err_free:
  1488. kfree(insn_state);
  1489. kfree(insn_stack);
  1490. return ret;
  1491. }
  1492. /* compare two verifier states
  1493. *
  1494. * all states stored in state_list are known to be valid, since
  1495. * verifier reached 'bpf_exit' instruction through them
  1496. *
  1497. * this function is called when verifier exploring different branches of
  1498. * execution popped from the state stack. If it sees an old state that has
  1499. * more strict register state and more strict stack state then this execution
  1500. * branch doesn't need to be explored further, since verifier already
  1501. * concluded that more strict state leads to valid finish.
  1502. *
  1503. * Therefore two states are equivalent if register state is more conservative
  1504. * and explored stack state is more conservative than the current one.
  1505. * Example:
  1506. * explored current
  1507. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  1508. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  1509. *
  1510. * In other words if current stack state (one being explored) has more
  1511. * valid slots than old one that already passed validation, it means
  1512. * the verifier can stop exploring and conclude that current state is valid too
  1513. *
  1514. * Similarly with registers. If explored state has register type as invalid
  1515. * whereas register type in current state is meaningful, it means that
  1516. * the current state will reach 'bpf_exit' instruction safely
  1517. */
  1518. static bool states_equal(struct verifier_state *old, struct verifier_state *cur)
  1519. {
  1520. int i;
  1521. for (i = 0; i < MAX_BPF_REG; i++) {
  1522. if (memcmp(&old->regs[i], &cur->regs[i],
  1523. sizeof(old->regs[0])) != 0) {
  1524. if (old->regs[i].type == NOT_INIT ||
  1525. (old->regs[i].type == UNKNOWN_VALUE &&
  1526. cur->regs[i].type != NOT_INIT))
  1527. continue;
  1528. return false;
  1529. }
  1530. }
  1531. for (i = 0; i < MAX_BPF_STACK; i++) {
  1532. if (old->stack_slot_type[i] == STACK_INVALID)
  1533. continue;
  1534. if (old->stack_slot_type[i] != cur->stack_slot_type[i])
  1535. /* Ex: old explored (safe) state has STACK_SPILL in
  1536. * this stack slot, but current has has STACK_MISC ->
  1537. * this verifier states are not equivalent,
  1538. * return false to continue verification of this path
  1539. */
  1540. return false;
  1541. if (i % BPF_REG_SIZE)
  1542. continue;
  1543. if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
  1544. &cur->spilled_regs[i / BPF_REG_SIZE],
  1545. sizeof(old->spilled_regs[0])))
  1546. /* when explored and current stack slot types are
  1547. * the same, check that stored pointers types
  1548. * are the same as well.
  1549. * Ex: explored safe path could have stored
  1550. * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8}
  1551. * but current path has stored:
  1552. * (struct reg_state) {.type = PTR_TO_STACK, .imm = -16}
  1553. * such verifier states are not equivalent.
  1554. * return false to continue verification of this path
  1555. */
  1556. return false;
  1557. else
  1558. continue;
  1559. }
  1560. return true;
  1561. }
  1562. static int is_state_visited(struct verifier_env *env, int insn_idx)
  1563. {
  1564. struct verifier_state_list *new_sl;
  1565. struct verifier_state_list *sl;
  1566. sl = env->explored_states[insn_idx];
  1567. if (!sl)
  1568. /* this 'insn_idx' instruction wasn't marked, so we will not
  1569. * be doing state search here
  1570. */
  1571. return 0;
  1572. while (sl != STATE_LIST_MARK) {
  1573. if (states_equal(&sl->state, &env->cur_state))
  1574. /* reached equivalent register/stack state,
  1575. * prune the search
  1576. */
  1577. return 1;
  1578. sl = sl->next;
  1579. }
  1580. /* there were no equivalent states, remember current one.
  1581. * technically the current state is not proven to be safe yet,
  1582. * but it will either reach bpf_exit (which means it's safe) or
  1583. * it will be rejected. Since there are no loops, we won't be
  1584. * seeing this 'insn_idx' instruction again on the way to bpf_exit
  1585. */
  1586. new_sl = kmalloc(sizeof(struct verifier_state_list), GFP_USER);
  1587. if (!new_sl)
  1588. return -ENOMEM;
  1589. /* add new state to the head of linked list */
  1590. memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
  1591. new_sl->next = env->explored_states[insn_idx];
  1592. env->explored_states[insn_idx] = new_sl;
  1593. return 0;
  1594. }
  1595. static int do_check(struct verifier_env *env)
  1596. {
  1597. struct verifier_state *state = &env->cur_state;
  1598. struct bpf_insn *insns = env->prog->insnsi;
  1599. struct reg_state *regs = state->regs;
  1600. int insn_cnt = env->prog->len;
  1601. int insn_idx, prev_insn_idx = 0;
  1602. int insn_processed = 0;
  1603. bool do_print_state = false;
  1604. init_reg_state(regs);
  1605. insn_idx = 0;
  1606. for (;;) {
  1607. struct bpf_insn *insn;
  1608. u8 class;
  1609. int err;
  1610. if (insn_idx >= insn_cnt) {
  1611. verbose("invalid insn idx %d insn_cnt %d\n",
  1612. insn_idx, insn_cnt);
  1613. return -EFAULT;
  1614. }
  1615. insn = &insns[insn_idx];
  1616. class = BPF_CLASS(insn->code);
  1617. if (++insn_processed > 32768) {
  1618. verbose("BPF program is too large. Proccessed %d insn\n",
  1619. insn_processed);
  1620. return -E2BIG;
  1621. }
  1622. err = is_state_visited(env, insn_idx);
  1623. if (err < 0)
  1624. return err;
  1625. if (err == 1) {
  1626. /* found equivalent state, can prune the search */
  1627. if (log_level) {
  1628. if (do_print_state)
  1629. verbose("\nfrom %d to %d: safe\n",
  1630. prev_insn_idx, insn_idx);
  1631. else
  1632. verbose("%d: safe\n", insn_idx);
  1633. }
  1634. goto process_bpf_exit;
  1635. }
  1636. if (log_level && do_print_state) {
  1637. verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
  1638. print_verifier_state(env);
  1639. do_print_state = false;
  1640. }
  1641. if (log_level) {
  1642. verbose("%d: ", insn_idx);
  1643. print_bpf_insn(env, insn);
  1644. }
  1645. env->insn_aux_data[insn_idx].seen = true;
  1646. if (class == BPF_ALU || class == BPF_ALU64) {
  1647. err = check_alu_op(env, insn);
  1648. if (err)
  1649. return err;
  1650. } else if (class == BPF_LDX) {
  1651. enum bpf_reg_type *prev_src_type, src_reg_type;
  1652. /* check for reserved fields is already done */
  1653. /* check src operand */
  1654. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1655. if (err)
  1656. return err;
  1657. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  1658. if (err)
  1659. return err;
  1660. src_reg_type = regs[insn->src_reg].type;
  1661. /* check that memory (src_reg + off) is readable,
  1662. * the state of dst_reg will be updated by this func
  1663. */
  1664. err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
  1665. BPF_SIZE(insn->code), BPF_READ,
  1666. insn->dst_reg);
  1667. if (err)
  1668. return err;
  1669. if (BPF_SIZE(insn->code) != BPF_W &&
  1670. BPF_SIZE(insn->code) != BPF_DW) {
  1671. insn_idx++;
  1672. continue;
  1673. }
  1674. prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
  1675. if (*prev_src_type == NOT_INIT) {
  1676. /* saw a valid insn
  1677. * dst_reg = *(u32 *)(src_reg + off)
  1678. * save type to validate intersecting paths
  1679. */
  1680. *prev_src_type = src_reg_type;
  1681. } else if (src_reg_type != *prev_src_type &&
  1682. (src_reg_type == PTR_TO_CTX ||
  1683. *prev_src_type == PTR_TO_CTX)) {
  1684. /* ABuser program is trying to use the same insn
  1685. * dst_reg = *(u32*) (src_reg + off)
  1686. * with different pointer types:
  1687. * src_reg == ctx in one branch and
  1688. * src_reg == stack|map in some other branch.
  1689. * Reject it.
  1690. */
  1691. verbose("same insn cannot be used with different pointers\n");
  1692. return -EINVAL;
  1693. }
  1694. } else if (class == BPF_STX) {
  1695. enum bpf_reg_type *prev_dst_type, dst_reg_type;
  1696. if (BPF_MODE(insn->code) == BPF_XADD) {
  1697. err = check_xadd(env, insn_idx, insn);
  1698. if (err)
  1699. return err;
  1700. insn_idx++;
  1701. continue;
  1702. }
  1703. /* check src1 operand */
  1704. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1705. if (err)
  1706. return err;
  1707. /* check src2 operand */
  1708. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1709. if (err)
  1710. return err;
  1711. dst_reg_type = regs[insn->dst_reg].type;
  1712. /* check that memory (dst_reg + off) is writeable */
  1713. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  1714. BPF_SIZE(insn->code), BPF_WRITE,
  1715. insn->src_reg);
  1716. if (err)
  1717. return err;
  1718. prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
  1719. if (*prev_dst_type == NOT_INIT) {
  1720. *prev_dst_type = dst_reg_type;
  1721. } else if (dst_reg_type != *prev_dst_type &&
  1722. (dst_reg_type == PTR_TO_CTX ||
  1723. *prev_dst_type == PTR_TO_CTX)) {
  1724. verbose("same insn cannot be used with different pointers\n");
  1725. return -EINVAL;
  1726. }
  1727. } else if (class == BPF_ST) {
  1728. if (BPF_MODE(insn->code) != BPF_MEM ||
  1729. insn->src_reg != BPF_REG_0) {
  1730. verbose("BPF_ST uses reserved fields\n");
  1731. return -EINVAL;
  1732. }
  1733. /* check src operand */
  1734. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1735. if (err)
  1736. return err;
  1737. if (is_ctx_reg(env, insn->dst_reg)) {
  1738. verbose("BPF_ST stores into R%d context is not allowed\n",
  1739. insn->dst_reg);
  1740. return -EACCES;
  1741. }
  1742. /* check that memory (dst_reg + off) is writeable */
  1743. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  1744. BPF_SIZE(insn->code), BPF_WRITE,
  1745. -1);
  1746. if (err)
  1747. return err;
  1748. } else if (class == BPF_JMP) {
  1749. u8 opcode = BPF_OP(insn->code);
  1750. if (opcode == BPF_CALL) {
  1751. if (BPF_SRC(insn->code) != BPF_K ||
  1752. insn->off != 0 ||
  1753. insn->src_reg != BPF_REG_0 ||
  1754. insn->dst_reg != BPF_REG_0) {
  1755. verbose("BPF_CALL uses reserved fields\n");
  1756. return -EINVAL;
  1757. }
  1758. err = check_call(env, insn->imm, insn_idx);
  1759. if (err)
  1760. return err;
  1761. } else if (opcode == BPF_JA) {
  1762. if (BPF_SRC(insn->code) != BPF_K ||
  1763. insn->imm != 0 ||
  1764. insn->src_reg != BPF_REG_0 ||
  1765. insn->dst_reg != BPF_REG_0) {
  1766. verbose("BPF_JA uses reserved fields\n");
  1767. return -EINVAL;
  1768. }
  1769. insn_idx += insn->off + 1;
  1770. continue;
  1771. } else if (opcode == BPF_EXIT) {
  1772. if (BPF_SRC(insn->code) != BPF_K ||
  1773. insn->imm != 0 ||
  1774. insn->src_reg != BPF_REG_0 ||
  1775. insn->dst_reg != BPF_REG_0) {
  1776. verbose("BPF_EXIT uses reserved fields\n");
  1777. return -EINVAL;
  1778. }
  1779. /* eBPF calling convetion is such that R0 is used
  1780. * to return the value from eBPF program.
  1781. * Make sure that it's readable at this time
  1782. * of bpf_exit, which means that program wrote
  1783. * something into it earlier
  1784. */
  1785. err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
  1786. if (err)
  1787. return err;
  1788. if (is_pointer_value(env, BPF_REG_0)) {
  1789. verbose("R0 leaks addr as return value\n");
  1790. return -EACCES;
  1791. }
  1792. process_bpf_exit:
  1793. insn_idx = pop_stack(env, &prev_insn_idx);
  1794. if (insn_idx < 0) {
  1795. break;
  1796. } else {
  1797. do_print_state = true;
  1798. continue;
  1799. }
  1800. } else {
  1801. err = check_cond_jmp_op(env, insn, &insn_idx);
  1802. if (err)
  1803. return err;
  1804. }
  1805. } else if (class == BPF_LD) {
  1806. u8 mode = BPF_MODE(insn->code);
  1807. if (mode == BPF_ABS || mode == BPF_IND) {
  1808. err = check_ld_abs(env, insn);
  1809. if (err)
  1810. return err;
  1811. } else if (mode == BPF_IMM) {
  1812. err = check_ld_imm(env, insn);
  1813. if (err)
  1814. return err;
  1815. insn_idx++;
  1816. env->insn_aux_data[insn_idx].seen = true;
  1817. } else {
  1818. verbose("invalid BPF_LD mode\n");
  1819. return -EINVAL;
  1820. }
  1821. } else {
  1822. verbose("unknown insn class %d\n", class);
  1823. return -EINVAL;
  1824. }
  1825. insn_idx++;
  1826. }
  1827. return 0;
  1828. }
  1829. /* look for pseudo eBPF instructions that access map FDs and
  1830. * replace them with actual map pointers
  1831. */
  1832. static int replace_map_fd_with_map_ptr(struct verifier_env *env)
  1833. {
  1834. struct bpf_insn *insn = env->prog->insnsi;
  1835. int insn_cnt = env->prog->len;
  1836. int i, j;
  1837. for (i = 0; i < insn_cnt; i++, insn++) {
  1838. if (BPF_CLASS(insn->code) == BPF_LDX &&
  1839. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  1840. verbose("BPF_LDX uses reserved fields\n");
  1841. return -EINVAL;
  1842. }
  1843. if (BPF_CLASS(insn->code) == BPF_STX &&
  1844. ((BPF_MODE(insn->code) != BPF_MEM &&
  1845. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  1846. verbose("BPF_STX uses reserved fields\n");
  1847. return -EINVAL;
  1848. }
  1849. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  1850. struct bpf_map *map;
  1851. struct fd f;
  1852. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  1853. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  1854. insn[1].off != 0) {
  1855. verbose("invalid bpf_ld_imm64 insn\n");
  1856. return -EINVAL;
  1857. }
  1858. if (insn->src_reg == 0)
  1859. /* valid generic load 64-bit imm */
  1860. goto next_insn;
  1861. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  1862. verbose("unrecognized bpf_ld_imm64 insn\n");
  1863. return -EINVAL;
  1864. }
  1865. f = fdget(insn->imm);
  1866. map = __bpf_map_get(f);
  1867. if (IS_ERR(map)) {
  1868. verbose("fd %d is not pointing to valid bpf_map\n",
  1869. insn->imm);
  1870. return PTR_ERR(map);
  1871. }
  1872. /* store map pointer inside BPF_LD_IMM64 instruction */
  1873. insn[0].imm = (u32) (unsigned long) map;
  1874. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  1875. /* check whether we recorded this map already */
  1876. for (j = 0; j < env->used_map_cnt; j++)
  1877. if (env->used_maps[j] == map) {
  1878. fdput(f);
  1879. goto next_insn;
  1880. }
  1881. if (env->used_map_cnt >= MAX_USED_MAPS) {
  1882. fdput(f);
  1883. return -E2BIG;
  1884. }
  1885. /* hold the map. If the program is rejected by verifier,
  1886. * the map will be released by release_maps() or it
  1887. * will be used by the valid program until it's unloaded
  1888. * and all maps are released in free_used_maps()
  1889. */
  1890. map = bpf_map_inc(map, false);
  1891. if (IS_ERR(map)) {
  1892. fdput(f);
  1893. return PTR_ERR(map);
  1894. }
  1895. env->used_maps[env->used_map_cnt++] = map;
  1896. fdput(f);
  1897. next_insn:
  1898. insn++;
  1899. i++;
  1900. }
  1901. }
  1902. /* now all pseudo BPF_LD_IMM64 instructions load valid
  1903. * 'struct bpf_map *' into a register instead of user map_fd.
  1904. * These pointers will be used later by verifier to validate map access.
  1905. */
  1906. return 0;
  1907. }
  1908. /* drop refcnt of maps used by the rejected program */
  1909. static void release_maps(struct verifier_env *env)
  1910. {
  1911. int i;
  1912. for (i = 0; i < env->used_map_cnt; i++)
  1913. bpf_map_put(env->used_maps[i]);
  1914. }
  1915. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  1916. static void convert_pseudo_ld_imm64(struct verifier_env *env)
  1917. {
  1918. struct bpf_insn *insn = env->prog->insnsi;
  1919. int insn_cnt = env->prog->len;
  1920. int i;
  1921. for (i = 0; i < insn_cnt; i++, insn++)
  1922. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  1923. insn->src_reg = 0;
  1924. }
  1925. /* single env->prog->insni[off] instruction was replaced with the range
  1926. * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
  1927. * [0, off) and [off, end) to new locations, so the patched range stays zero
  1928. */
  1929. static int adjust_insn_aux_data(struct verifier_env *env, u32 prog_len,
  1930. u32 off, u32 cnt)
  1931. {
  1932. struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
  1933. int i;
  1934. if (cnt == 1)
  1935. return 0;
  1936. new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
  1937. if (!new_data)
  1938. return -ENOMEM;
  1939. memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
  1940. memcpy(new_data + off + cnt - 1, old_data + off,
  1941. sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
  1942. for (i = off; i < off + cnt - 1; i++)
  1943. new_data[i].seen = true;
  1944. env->insn_aux_data = new_data;
  1945. vfree(old_data);
  1946. return 0;
  1947. }
  1948. static struct bpf_prog *bpf_patch_insn_data(struct verifier_env *env, u32 off,
  1949. const struct bpf_insn *patch, u32 len)
  1950. {
  1951. struct bpf_prog *new_prog;
  1952. new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
  1953. if (!new_prog)
  1954. return NULL;
  1955. if (adjust_insn_aux_data(env, new_prog->len, off, len))
  1956. return NULL;
  1957. return new_prog;
  1958. }
  1959. /* The verifier does more data flow analysis than llvm and will not explore
  1960. * branches that are dead at run time. Malicious programs can have dead code
  1961. * too. Therefore replace all dead at-run-time code with nops.
  1962. */
  1963. static void sanitize_dead_code(struct verifier_env *env)
  1964. {
  1965. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  1966. struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
  1967. struct bpf_insn *insn = env->prog->insnsi;
  1968. const int insn_cnt = env->prog->len;
  1969. int i;
  1970. for (i = 0; i < insn_cnt; i++) {
  1971. if (aux_data[i].seen)
  1972. continue;
  1973. memcpy(insn + i, &nop, sizeof(nop));
  1974. }
  1975. }
  1976. /* convert load instructions that access fields of 'struct __sk_buff'
  1977. * into sequence of instructions that access fields of 'struct sk_buff'
  1978. */
  1979. static int convert_ctx_accesses(struct verifier_env *env)
  1980. {
  1981. struct bpf_insn *insn = env->prog->insnsi;
  1982. const int insn_cnt = env->prog->len;
  1983. struct bpf_insn insn_buf[16];
  1984. struct bpf_prog *new_prog;
  1985. enum bpf_access_type type;
  1986. int i, delta = 0;
  1987. if (!env->prog->aux->ops->convert_ctx_access)
  1988. return 0;
  1989. for (i = 0; i < insn_cnt; i++, insn++) {
  1990. u32 cnt;
  1991. if (insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  1992. insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
  1993. type = BPF_READ;
  1994. else if (insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  1995. insn->code == (BPF_STX | BPF_MEM | BPF_DW))
  1996. type = BPF_WRITE;
  1997. else
  1998. continue;
  1999. if (type == BPF_WRITE &&
  2000. env->insn_aux_data[i + delta].sanitize_stack_off) {
  2001. struct bpf_insn patch[] = {
  2002. /* Sanitize suspicious stack slot with zero.
  2003. * There are no memory dependencies for this store,
  2004. * since it's only using frame pointer and immediate
  2005. * constant of zero
  2006. */
  2007. BPF_ST_MEM(BPF_DW, BPF_REG_FP,
  2008. env->insn_aux_data[i + delta].sanitize_stack_off,
  2009. 0),
  2010. /* the original STX instruction will immediately
  2011. * overwrite the same stack slot with appropriate value
  2012. */
  2013. *insn,
  2014. };
  2015. cnt = ARRAY_SIZE(patch);
  2016. new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
  2017. if (!new_prog)
  2018. return -ENOMEM;
  2019. delta += cnt - 1;
  2020. env->prog = new_prog;
  2021. insn = new_prog->insnsi + i + delta;
  2022. continue;
  2023. }
  2024. if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
  2025. continue;
  2026. cnt = env->prog->aux->ops->
  2027. convert_ctx_access(type, insn->dst_reg, insn->src_reg,
  2028. insn->off, insn_buf, env->prog);
  2029. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  2030. verbose("bpf verifier is misconfigured\n");
  2031. return -EINVAL;
  2032. }
  2033. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  2034. if (!new_prog)
  2035. return -ENOMEM;
  2036. delta += cnt - 1;
  2037. /* keep walking new program and skip insns we just inserted */
  2038. env->prog = new_prog;
  2039. insn = new_prog->insnsi + i + delta;
  2040. }
  2041. return 0;
  2042. }
  2043. /* fixup insn->imm field of bpf_call instructions
  2044. *
  2045. * this function is called after eBPF program passed verification
  2046. */
  2047. static int fixup_bpf_calls(struct verifier_env *env)
  2048. {
  2049. struct bpf_prog *prog = env->prog;
  2050. struct bpf_insn *insn = prog->insnsi;
  2051. const struct bpf_func_proto *fn;
  2052. const int insn_cnt = prog->len;
  2053. struct bpf_insn insn_buf[16];
  2054. struct bpf_prog *new_prog;
  2055. struct bpf_map *map_ptr;
  2056. int i, cnt, delta = 0;
  2057. for (i = 0; i < insn_cnt; i++, insn++) {
  2058. if (insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
  2059. insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
  2060. /* due to JIT bugs clear upper 32-bits of src register
  2061. * before div/mod operation
  2062. */
  2063. insn_buf[0] = BPF_MOV32_REG(insn->src_reg, insn->src_reg);
  2064. insn_buf[1] = *insn;
  2065. cnt = 2;
  2066. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  2067. if (!new_prog)
  2068. return -ENOMEM;
  2069. delta += cnt - 1;
  2070. env->prog = prog = new_prog;
  2071. insn = new_prog->insnsi + i + delta;
  2072. continue;
  2073. }
  2074. if (insn->code != (BPF_JMP | BPF_CALL))
  2075. continue;
  2076. if (insn->imm == BPF_FUNC_get_route_realm)
  2077. prog->dst_needed = 1;
  2078. if (insn->imm == BPF_FUNC_get_prandom_u32)
  2079. bpf_user_rnd_init_once();
  2080. if (insn->imm == BPF_FUNC_tail_call) {
  2081. /* mark bpf_tail_call as different opcode to avoid
  2082. * conditional branch in the interpeter for every normal
  2083. * call and to prevent accidental JITing by JIT compiler
  2084. * that doesn't support bpf_tail_call yet
  2085. */
  2086. insn->imm = 0;
  2087. insn->code |= BPF_X;
  2088. /* instead of changing every JIT dealing with tail_call
  2089. * emit two extra insns:
  2090. * if (index >= max_entries) goto out;
  2091. * index &= array->index_mask;
  2092. * to avoid out-of-bounds cpu speculation
  2093. */
  2094. map_ptr = env->insn_aux_data[i + delta].map_ptr;
  2095. if (!map_ptr->unpriv_array)
  2096. continue;
  2097. insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
  2098. map_ptr->max_entries, 2);
  2099. insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
  2100. container_of(map_ptr,
  2101. struct bpf_array,
  2102. map)->index_mask);
  2103. insn_buf[2] = *insn;
  2104. cnt = 3;
  2105. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  2106. if (!new_prog)
  2107. return -ENOMEM;
  2108. delta += cnt - 1;
  2109. env->prog = prog = new_prog;
  2110. insn = new_prog->insnsi + i + delta;
  2111. continue;
  2112. }
  2113. fn = prog->aux->ops->get_func_proto(insn->imm);
  2114. /* all functions that have prototype and verifier allowed
  2115. * programs to call them, must be real in-kernel functions
  2116. */
  2117. if (!fn->func) {
  2118. verbose("kernel subsystem misconfigured func %d\n",
  2119. insn->imm);
  2120. return -EFAULT;
  2121. }
  2122. insn->imm = fn->func - __bpf_call_base;
  2123. }
  2124. return 0;
  2125. }
  2126. static void free_states(struct verifier_env *env)
  2127. {
  2128. struct verifier_state_list *sl, *sln;
  2129. int i;
  2130. if (!env->explored_states)
  2131. return;
  2132. for (i = 0; i < env->prog->len; i++) {
  2133. sl = env->explored_states[i];
  2134. if (sl)
  2135. while (sl != STATE_LIST_MARK) {
  2136. sln = sl->next;
  2137. kfree(sl);
  2138. sl = sln;
  2139. }
  2140. }
  2141. kfree(env->explored_states);
  2142. }
  2143. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  2144. {
  2145. char __user *log_ubuf = NULL;
  2146. struct verifier_env *env;
  2147. int ret = -EINVAL;
  2148. if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
  2149. return -E2BIG;
  2150. /* 'struct verifier_env' can be global, but since it's not small,
  2151. * allocate/free it every time bpf_check() is called
  2152. */
  2153. env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL);
  2154. if (!env)
  2155. return -ENOMEM;
  2156. env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
  2157. (*prog)->len);
  2158. ret = -ENOMEM;
  2159. if (!env->insn_aux_data)
  2160. goto err_free_env;
  2161. env->prog = *prog;
  2162. /* grab the mutex to protect few globals used by verifier */
  2163. mutex_lock(&bpf_verifier_lock);
  2164. if (attr->log_level || attr->log_buf || attr->log_size) {
  2165. /* user requested verbose verifier output
  2166. * and supplied buffer to store the verification trace
  2167. */
  2168. log_level = attr->log_level;
  2169. log_ubuf = (char __user *) (unsigned long) attr->log_buf;
  2170. log_size = attr->log_size;
  2171. log_len = 0;
  2172. ret = -EINVAL;
  2173. /* log_* values have to be sane */
  2174. if (log_size < 128 || log_size > UINT_MAX >> 8 ||
  2175. log_level == 0 || log_ubuf == NULL)
  2176. goto err_unlock;
  2177. ret = -ENOMEM;
  2178. log_buf = vmalloc(log_size);
  2179. if (!log_buf)
  2180. goto err_unlock;
  2181. } else {
  2182. log_level = 0;
  2183. }
  2184. ret = replace_map_fd_with_map_ptr(env);
  2185. if (ret < 0)
  2186. goto skip_full_check;
  2187. env->explored_states = kcalloc(env->prog->len,
  2188. sizeof(struct verifier_state_list *),
  2189. GFP_USER);
  2190. ret = -ENOMEM;
  2191. if (!env->explored_states)
  2192. goto skip_full_check;
  2193. ret = check_cfg(env);
  2194. if (ret < 0)
  2195. goto skip_full_check;
  2196. env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
  2197. ret = do_check(env);
  2198. skip_full_check:
  2199. while (pop_stack(env, NULL) >= 0);
  2200. free_states(env);
  2201. if (ret == 0)
  2202. sanitize_dead_code(env);
  2203. if (ret == 0)
  2204. /* program is valid, convert *(u32*)(ctx + off) accesses */
  2205. ret = convert_ctx_accesses(env);
  2206. if (ret == 0)
  2207. ret = fixup_bpf_calls(env);
  2208. if (log_level && log_len >= log_size - 1) {
  2209. BUG_ON(log_len >= log_size);
  2210. /* verifier log exceeded user supplied buffer */
  2211. ret = -ENOSPC;
  2212. /* fall through to return what was recorded */
  2213. }
  2214. /* copy verifier log back to user space including trailing zero */
  2215. if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
  2216. ret = -EFAULT;
  2217. goto free_log_buf;
  2218. }
  2219. if (ret == 0 && env->used_map_cnt) {
  2220. /* if program passed verifier, update used_maps in bpf_prog_info */
  2221. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  2222. sizeof(env->used_maps[0]),
  2223. GFP_KERNEL);
  2224. if (!env->prog->aux->used_maps) {
  2225. ret = -ENOMEM;
  2226. goto free_log_buf;
  2227. }
  2228. memcpy(env->prog->aux->used_maps, env->used_maps,
  2229. sizeof(env->used_maps[0]) * env->used_map_cnt);
  2230. env->prog->aux->used_map_cnt = env->used_map_cnt;
  2231. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  2232. * bpf_ld_imm64 instructions
  2233. */
  2234. convert_pseudo_ld_imm64(env);
  2235. }
  2236. free_log_buf:
  2237. if (log_level)
  2238. vfree(log_buf);
  2239. if (!env->prog->aux->used_maps)
  2240. /* if we didn't copy map pointers into bpf_prog_info, release
  2241. * them now. Otherwise free_used_maps() will release them.
  2242. */
  2243. release_maps(env);
  2244. *prog = env->prog;
  2245. err_unlock:
  2246. mutex_unlock(&bpf_verifier_lock);
  2247. vfree(env->insn_aux_data);
  2248. err_free_env:
  2249. kfree(env);
  2250. return ret;
  2251. }