verifier.c 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182
  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. #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
  180. /* single container for all structs
  181. * one verifier_env per bpf_check() call
  182. */
  183. struct verifier_env {
  184. struct bpf_prog *prog; /* eBPF program being verified */
  185. struct verifier_stack_elem *head; /* stack of verifier states to be processed */
  186. int stack_size; /* number of states to be processed */
  187. struct verifier_state cur_state; /* current verifier state */
  188. struct verifier_state_list **explored_states; /* search pruning optimization */
  189. struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
  190. u32 used_map_cnt; /* number of used maps */
  191. };
  192. /* verbose verifier prints what it's seeing
  193. * bpf_check() is called under lock, so no race to access these global vars
  194. */
  195. static u32 log_level, log_size, log_len;
  196. static char *log_buf;
  197. static DEFINE_MUTEX(bpf_verifier_lock);
  198. /* log_level controls verbosity level of eBPF verifier.
  199. * verbose() is used to dump the verification trace to the log, so the user
  200. * can figure out what's wrong with the program
  201. */
  202. static void verbose(const char *fmt, ...)
  203. {
  204. va_list args;
  205. if (log_level == 0 || log_len >= log_size - 1)
  206. return;
  207. va_start(args, fmt);
  208. log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
  209. va_end(args);
  210. }
  211. /* string representation of 'enum bpf_reg_type' */
  212. static const char * const reg_type_str[] = {
  213. [NOT_INIT] = "?",
  214. [UNKNOWN_VALUE] = "inv",
  215. [PTR_TO_CTX] = "ctx",
  216. [CONST_PTR_TO_MAP] = "map_ptr",
  217. [PTR_TO_MAP_VALUE] = "map_value",
  218. [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
  219. [FRAME_PTR] = "fp",
  220. [PTR_TO_STACK] = "fp",
  221. [CONST_IMM] = "imm",
  222. };
  223. static void print_verifier_state(struct verifier_env *env)
  224. {
  225. enum bpf_reg_type t;
  226. int i;
  227. for (i = 0; i < MAX_BPF_REG; i++) {
  228. t = env->cur_state.regs[i].type;
  229. if (t == NOT_INIT)
  230. continue;
  231. verbose(" R%d=%s", i, reg_type_str[t]);
  232. if (t == CONST_IMM || t == PTR_TO_STACK)
  233. verbose("%d", env->cur_state.regs[i].imm);
  234. else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
  235. t == PTR_TO_MAP_VALUE_OR_NULL)
  236. verbose("(ks=%d,vs=%d)",
  237. env->cur_state.regs[i].map_ptr->key_size,
  238. env->cur_state.regs[i].map_ptr->value_size);
  239. }
  240. for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
  241. if (env->cur_state.stack_slot_type[i] == STACK_SPILL)
  242. verbose(" fp%d=%s", -MAX_BPF_STACK + i,
  243. reg_type_str[env->cur_state.spilled_regs[i / BPF_REG_SIZE].type]);
  244. }
  245. verbose("\n");
  246. }
  247. static const char *const bpf_class_string[] = {
  248. [BPF_LD] = "ld",
  249. [BPF_LDX] = "ldx",
  250. [BPF_ST] = "st",
  251. [BPF_STX] = "stx",
  252. [BPF_ALU] = "alu",
  253. [BPF_JMP] = "jmp",
  254. [BPF_RET] = "BUG",
  255. [BPF_ALU64] = "alu64",
  256. };
  257. static const char *const bpf_alu_string[] = {
  258. [BPF_ADD >> 4] = "+=",
  259. [BPF_SUB >> 4] = "-=",
  260. [BPF_MUL >> 4] = "*=",
  261. [BPF_DIV >> 4] = "/=",
  262. [BPF_OR >> 4] = "|=",
  263. [BPF_AND >> 4] = "&=",
  264. [BPF_LSH >> 4] = "<<=",
  265. [BPF_RSH >> 4] = ">>=",
  266. [BPF_NEG >> 4] = "neg",
  267. [BPF_MOD >> 4] = "%=",
  268. [BPF_XOR >> 4] = "^=",
  269. [BPF_MOV >> 4] = "=",
  270. [BPF_ARSH >> 4] = "s>>=",
  271. [BPF_END >> 4] = "endian",
  272. };
  273. static const char *const bpf_ldst_string[] = {
  274. [BPF_W >> 3] = "u32",
  275. [BPF_H >> 3] = "u16",
  276. [BPF_B >> 3] = "u8",
  277. [BPF_DW >> 3] = "u64",
  278. };
  279. static const char *const bpf_jmp_string[] = {
  280. [BPF_JA >> 4] = "jmp",
  281. [BPF_JEQ >> 4] = "==",
  282. [BPF_JGT >> 4] = ">",
  283. [BPF_JGE >> 4] = ">=",
  284. [BPF_JSET >> 4] = "&",
  285. [BPF_JNE >> 4] = "!=",
  286. [BPF_JSGT >> 4] = "s>",
  287. [BPF_JSGE >> 4] = "s>=",
  288. [BPF_CALL >> 4] = "call",
  289. [BPF_EXIT >> 4] = "exit",
  290. };
  291. static void print_bpf_insn(struct bpf_insn *insn)
  292. {
  293. u8 class = BPF_CLASS(insn->code);
  294. if (class == BPF_ALU || class == BPF_ALU64) {
  295. if (BPF_SRC(insn->code) == BPF_X)
  296. verbose("(%02x) %sr%d %s %sr%d\n",
  297. insn->code, class == BPF_ALU ? "(u32) " : "",
  298. insn->dst_reg,
  299. bpf_alu_string[BPF_OP(insn->code) >> 4],
  300. class == BPF_ALU ? "(u32) " : "",
  301. insn->src_reg);
  302. else
  303. verbose("(%02x) %sr%d %s %s%d\n",
  304. insn->code, class == BPF_ALU ? "(u32) " : "",
  305. insn->dst_reg,
  306. bpf_alu_string[BPF_OP(insn->code) >> 4],
  307. class == BPF_ALU ? "(u32) " : "",
  308. insn->imm);
  309. } else if (class == BPF_STX) {
  310. if (BPF_MODE(insn->code) == BPF_MEM)
  311. verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
  312. insn->code,
  313. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  314. insn->dst_reg,
  315. insn->off, insn->src_reg);
  316. else if (BPF_MODE(insn->code) == BPF_XADD)
  317. verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
  318. insn->code,
  319. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  320. insn->dst_reg, insn->off,
  321. insn->src_reg);
  322. else
  323. verbose("BUG_%02x\n", insn->code);
  324. } else if (class == BPF_ST) {
  325. if (BPF_MODE(insn->code) != BPF_MEM) {
  326. verbose("BUG_st_%02x\n", insn->code);
  327. return;
  328. }
  329. verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
  330. insn->code,
  331. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  332. insn->dst_reg,
  333. insn->off, insn->imm);
  334. } else if (class == BPF_LDX) {
  335. if (BPF_MODE(insn->code) != BPF_MEM) {
  336. verbose("BUG_ldx_%02x\n", insn->code);
  337. return;
  338. }
  339. verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
  340. insn->code, insn->dst_reg,
  341. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  342. insn->src_reg, insn->off);
  343. } else if (class == BPF_LD) {
  344. if (BPF_MODE(insn->code) == BPF_ABS) {
  345. verbose("(%02x) r0 = *(%s *)skb[%d]\n",
  346. insn->code,
  347. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  348. insn->imm);
  349. } else if (BPF_MODE(insn->code) == BPF_IND) {
  350. verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
  351. insn->code,
  352. bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
  353. insn->src_reg, insn->imm);
  354. } else if (BPF_MODE(insn->code) == BPF_IMM) {
  355. verbose("(%02x) r%d = 0x%x\n",
  356. insn->code, insn->dst_reg, insn->imm);
  357. } else {
  358. verbose("BUG_ld_%02x\n", insn->code);
  359. return;
  360. }
  361. } else if (class == BPF_JMP) {
  362. u8 opcode = BPF_OP(insn->code);
  363. if (opcode == BPF_CALL) {
  364. verbose("(%02x) call %d\n", insn->code, insn->imm);
  365. } else if (insn->code == (BPF_JMP | BPF_JA)) {
  366. verbose("(%02x) goto pc%+d\n",
  367. insn->code, insn->off);
  368. } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
  369. verbose("(%02x) exit\n", insn->code);
  370. } else if (BPF_SRC(insn->code) == BPF_X) {
  371. verbose("(%02x) if r%d %s r%d goto pc%+d\n",
  372. insn->code, insn->dst_reg,
  373. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  374. insn->src_reg, insn->off);
  375. } else {
  376. verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
  377. insn->code, insn->dst_reg,
  378. bpf_jmp_string[BPF_OP(insn->code) >> 4],
  379. insn->imm, insn->off);
  380. }
  381. } else {
  382. verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
  383. }
  384. }
  385. static int pop_stack(struct verifier_env *env, int *prev_insn_idx)
  386. {
  387. struct verifier_stack_elem *elem;
  388. int insn_idx;
  389. if (env->head == NULL)
  390. return -1;
  391. memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
  392. insn_idx = env->head->insn_idx;
  393. if (prev_insn_idx)
  394. *prev_insn_idx = env->head->prev_insn_idx;
  395. elem = env->head->next;
  396. kfree(env->head);
  397. env->head = elem;
  398. env->stack_size--;
  399. return insn_idx;
  400. }
  401. static struct verifier_state *push_stack(struct verifier_env *env, int insn_idx,
  402. int prev_insn_idx)
  403. {
  404. struct verifier_stack_elem *elem;
  405. elem = kmalloc(sizeof(struct verifier_stack_elem), GFP_KERNEL);
  406. if (!elem)
  407. goto err;
  408. memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
  409. elem->insn_idx = insn_idx;
  410. elem->prev_insn_idx = prev_insn_idx;
  411. elem->next = env->head;
  412. env->head = elem;
  413. env->stack_size++;
  414. if (env->stack_size > 1024) {
  415. verbose("BPF program is too complex\n");
  416. goto err;
  417. }
  418. return &elem->st;
  419. err:
  420. /* pop all elements and return */
  421. while (pop_stack(env, NULL) >= 0);
  422. return NULL;
  423. }
  424. #define CALLER_SAVED_REGS 6
  425. static const int caller_saved[CALLER_SAVED_REGS] = {
  426. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  427. };
  428. static void init_reg_state(struct reg_state *regs)
  429. {
  430. int i;
  431. for (i = 0; i < MAX_BPF_REG; i++) {
  432. regs[i].type = NOT_INIT;
  433. regs[i].imm = 0;
  434. regs[i].map_ptr = NULL;
  435. }
  436. /* frame pointer */
  437. regs[BPF_REG_FP].type = FRAME_PTR;
  438. /* 1st arg to a function */
  439. regs[BPF_REG_1].type = PTR_TO_CTX;
  440. }
  441. static void mark_reg_unknown_value(struct reg_state *regs, u32 regno)
  442. {
  443. BUG_ON(regno >= MAX_BPF_REG);
  444. regs[regno].type = UNKNOWN_VALUE;
  445. regs[regno].imm = 0;
  446. regs[regno].map_ptr = NULL;
  447. }
  448. enum reg_arg_type {
  449. SRC_OP, /* register is used as source operand */
  450. DST_OP, /* register is used as destination operand */
  451. DST_OP_NO_MARK /* same as above, check only, don't mark */
  452. };
  453. static int check_reg_arg(struct reg_state *regs, u32 regno,
  454. enum reg_arg_type t)
  455. {
  456. if (regno >= MAX_BPF_REG) {
  457. verbose("R%d is invalid\n", regno);
  458. return -EINVAL;
  459. }
  460. if (t == SRC_OP) {
  461. /* check whether register used as source operand can be read */
  462. if (regs[regno].type == NOT_INIT) {
  463. verbose("R%d !read_ok\n", regno);
  464. return -EACCES;
  465. }
  466. } else {
  467. /* check whether register used as dest operand can be written to */
  468. if (regno == BPF_REG_FP) {
  469. verbose("frame pointer is read only\n");
  470. return -EACCES;
  471. }
  472. if (t == DST_OP)
  473. mark_reg_unknown_value(regs, regno);
  474. }
  475. return 0;
  476. }
  477. static int bpf_size_to_bytes(int bpf_size)
  478. {
  479. if (bpf_size == BPF_W)
  480. return 4;
  481. else if (bpf_size == BPF_H)
  482. return 2;
  483. else if (bpf_size == BPF_B)
  484. return 1;
  485. else if (bpf_size == BPF_DW)
  486. return 8;
  487. else
  488. return -EINVAL;
  489. }
  490. /* check_stack_read/write functions track spill/fill of registers,
  491. * stack boundary and alignment are checked in check_mem_access()
  492. */
  493. static int check_stack_write(struct verifier_state *state, int off, int size,
  494. int value_regno)
  495. {
  496. int i;
  497. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  498. * so it's aligned access and [off, off + size) are within stack limits
  499. */
  500. if (value_regno >= 0 &&
  501. (state->regs[value_regno].type == PTR_TO_MAP_VALUE ||
  502. state->regs[value_regno].type == PTR_TO_STACK ||
  503. state->regs[value_regno].type == PTR_TO_CTX)) {
  504. /* register containing pointer is being spilled into stack */
  505. if (size != BPF_REG_SIZE) {
  506. verbose("invalid size of register spill\n");
  507. return -EACCES;
  508. }
  509. /* save register state */
  510. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
  511. state->regs[value_regno];
  512. for (i = 0; i < BPF_REG_SIZE; i++)
  513. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
  514. } else {
  515. /* regular write of data into stack */
  516. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
  517. (struct reg_state) {};
  518. for (i = 0; i < size; i++)
  519. state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
  520. }
  521. return 0;
  522. }
  523. static int check_stack_read(struct verifier_state *state, int off, int size,
  524. int value_regno)
  525. {
  526. u8 *slot_type;
  527. int i;
  528. slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
  529. if (slot_type[0] == STACK_SPILL) {
  530. if (size != BPF_REG_SIZE) {
  531. verbose("invalid size of register spill\n");
  532. return -EACCES;
  533. }
  534. for (i = 1; i < BPF_REG_SIZE; i++) {
  535. if (slot_type[i] != STACK_SPILL) {
  536. verbose("corrupted spill memory\n");
  537. return -EACCES;
  538. }
  539. }
  540. if (value_regno >= 0)
  541. /* restore register state from stack */
  542. state->regs[value_regno] =
  543. state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
  544. return 0;
  545. } else {
  546. for (i = 0; i < size; i++) {
  547. if (slot_type[i] != STACK_MISC) {
  548. verbose("invalid read from stack off %d+%d size %d\n",
  549. off, i, size);
  550. return -EACCES;
  551. }
  552. }
  553. if (value_regno >= 0)
  554. /* have read misc data from the stack */
  555. mark_reg_unknown_value(state->regs, value_regno);
  556. return 0;
  557. }
  558. }
  559. /* check read/write into map element returned by bpf_map_lookup_elem() */
  560. static int check_map_access(struct verifier_env *env, u32 regno, int off,
  561. int size)
  562. {
  563. struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
  564. if (off < 0 || off + size > map->value_size) {
  565. verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
  566. map->value_size, off, size);
  567. return -EACCES;
  568. }
  569. return 0;
  570. }
  571. /* check access to 'struct bpf_context' fields */
  572. static int check_ctx_access(struct verifier_env *env, int off, int size,
  573. enum bpf_access_type t)
  574. {
  575. if (env->prog->aux->ops->is_valid_access &&
  576. env->prog->aux->ops->is_valid_access(off, size, t))
  577. return 0;
  578. verbose("invalid bpf_context access off=%d size=%d\n", off, size);
  579. return -EACCES;
  580. }
  581. /* check whether memory at (regno + off) is accessible for t = (read | write)
  582. * if t==write, value_regno is a register which value is stored into memory
  583. * if t==read, value_regno is a register which will receive the value from memory
  584. * if t==write && value_regno==-1, some unknown value is stored into memory
  585. * if t==read && value_regno==-1, don't care what we read from memory
  586. */
  587. static int check_mem_access(struct verifier_env *env, u32 regno, int off,
  588. int bpf_size, enum bpf_access_type t,
  589. int value_regno)
  590. {
  591. struct verifier_state *state = &env->cur_state;
  592. int size, err = 0;
  593. size = bpf_size_to_bytes(bpf_size);
  594. if (size < 0)
  595. return size;
  596. if (off % size != 0) {
  597. verbose("misaligned access off %d size %d\n", off, size);
  598. return -EACCES;
  599. }
  600. if (state->regs[regno].type == PTR_TO_MAP_VALUE) {
  601. err = check_map_access(env, regno, off, size);
  602. if (!err && t == BPF_READ && value_regno >= 0)
  603. mark_reg_unknown_value(state->regs, value_regno);
  604. } else if (state->regs[regno].type == PTR_TO_CTX) {
  605. err = check_ctx_access(env, off, size, t);
  606. if (!err && t == BPF_READ && value_regno >= 0)
  607. mark_reg_unknown_value(state->regs, value_regno);
  608. } else if (state->regs[regno].type == FRAME_PTR) {
  609. if (off >= 0 || off < -MAX_BPF_STACK) {
  610. verbose("invalid stack off=%d size=%d\n", off, size);
  611. return -EACCES;
  612. }
  613. if (t == BPF_WRITE)
  614. err = check_stack_write(state, off, size, value_regno);
  615. else
  616. err = check_stack_read(state, off, size, value_regno);
  617. } else {
  618. verbose("R%d invalid mem access '%s'\n",
  619. regno, reg_type_str[state->regs[regno].type]);
  620. return -EACCES;
  621. }
  622. return err;
  623. }
  624. static int check_xadd(struct verifier_env *env, struct bpf_insn *insn)
  625. {
  626. struct reg_state *regs = env->cur_state.regs;
  627. int err;
  628. if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
  629. insn->imm != 0) {
  630. verbose("BPF_XADD uses reserved fields\n");
  631. return -EINVAL;
  632. }
  633. /* check src1 operand */
  634. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  635. if (err)
  636. return err;
  637. /* check src2 operand */
  638. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  639. if (err)
  640. return err;
  641. /* check whether atomic_add can read the memory */
  642. err = check_mem_access(env, insn->dst_reg, insn->off,
  643. BPF_SIZE(insn->code), BPF_READ, -1);
  644. if (err)
  645. return err;
  646. /* check whether atomic_add can write into the same memory */
  647. return check_mem_access(env, insn->dst_reg, insn->off,
  648. BPF_SIZE(insn->code), BPF_WRITE, -1);
  649. }
  650. /* when register 'regno' is passed into function that will read 'access_size'
  651. * bytes from that pointer, make sure that it's within stack boundary
  652. * and all elements of stack are initialized
  653. */
  654. static int check_stack_boundary(struct verifier_env *env,
  655. int regno, int access_size)
  656. {
  657. struct verifier_state *state = &env->cur_state;
  658. struct reg_state *regs = state->regs;
  659. int off, i;
  660. if (regs[regno].type != PTR_TO_STACK)
  661. return -EACCES;
  662. off = regs[regno].imm;
  663. if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
  664. access_size <= 0) {
  665. verbose("invalid stack type R%d off=%d access_size=%d\n",
  666. regno, off, access_size);
  667. return -EACCES;
  668. }
  669. for (i = 0; i < access_size; i++) {
  670. if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
  671. verbose("invalid indirect read from stack off %d+%d size %d\n",
  672. off, i, access_size);
  673. return -EACCES;
  674. }
  675. }
  676. return 0;
  677. }
  678. static int check_func_arg(struct verifier_env *env, u32 regno,
  679. enum bpf_arg_type arg_type, struct bpf_map **mapp)
  680. {
  681. struct reg_state *reg = env->cur_state.regs + regno;
  682. enum bpf_reg_type expected_type;
  683. int err = 0;
  684. if (arg_type == ARG_DONTCARE)
  685. return 0;
  686. if (reg->type == NOT_INIT) {
  687. verbose("R%d !read_ok\n", regno);
  688. return -EACCES;
  689. }
  690. if (arg_type == ARG_ANYTHING)
  691. return 0;
  692. if (arg_type == ARG_PTR_TO_STACK || arg_type == ARG_PTR_TO_MAP_KEY ||
  693. arg_type == ARG_PTR_TO_MAP_VALUE) {
  694. expected_type = PTR_TO_STACK;
  695. } else if (arg_type == ARG_CONST_STACK_SIZE) {
  696. expected_type = CONST_IMM;
  697. } else if (arg_type == ARG_CONST_MAP_PTR) {
  698. expected_type = CONST_PTR_TO_MAP;
  699. } else if (arg_type == ARG_PTR_TO_CTX) {
  700. expected_type = PTR_TO_CTX;
  701. } else {
  702. verbose("unsupported arg_type %d\n", arg_type);
  703. return -EFAULT;
  704. }
  705. if (reg->type != expected_type) {
  706. verbose("R%d type=%s expected=%s\n", regno,
  707. reg_type_str[reg->type], reg_type_str[expected_type]);
  708. return -EACCES;
  709. }
  710. if (arg_type == ARG_CONST_MAP_PTR) {
  711. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  712. *mapp = reg->map_ptr;
  713. } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
  714. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  715. * check that [key, key + map->key_size) are within
  716. * stack limits and initialized
  717. */
  718. if (!*mapp) {
  719. /* in function declaration map_ptr must come before
  720. * map_key, so that it's verified and known before
  721. * we have to check map_key here. Otherwise it means
  722. * that kernel subsystem misconfigured verifier
  723. */
  724. verbose("invalid map_ptr to access map->key\n");
  725. return -EACCES;
  726. }
  727. err = check_stack_boundary(env, regno, (*mapp)->key_size);
  728. } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
  729. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  730. * check [value, value + map->value_size) validity
  731. */
  732. if (!*mapp) {
  733. /* kernel subsystem misconfigured verifier */
  734. verbose("invalid map_ptr to access map->value\n");
  735. return -EACCES;
  736. }
  737. err = check_stack_boundary(env, regno, (*mapp)->value_size);
  738. } else if (arg_type == ARG_CONST_STACK_SIZE) {
  739. /* bpf_xxx(..., buf, len) call will access 'len' bytes
  740. * from stack pointer 'buf'. Check it
  741. * note: regno == len, regno - 1 == buf
  742. */
  743. if (regno == 0) {
  744. /* kernel subsystem misconfigured verifier */
  745. verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
  746. return -EACCES;
  747. }
  748. err = check_stack_boundary(env, regno - 1, reg->imm);
  749. }
  750. return err;
  751. }
  752. static int check_call(struct verifier_env *env, int func_id)
  753. {
  754. struct verifier_state *state = &env->cur_state;
  755. const struct bpf_func_proto *fn = NULL;
  756. struct reg_state *regs = state->regs;
  757. struct bpf_map *map = NULL;
  758. struct reg_state *reg;
  759. int i, err;
  760. /* find function prototype */
  761. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
  762. verbose("invalid func %d\n", func_id);
  763. return -EINVAL;
  764. }
  765. if (env->prog->aux->ops->get_func_proto)
  766. fn = env->prog->aux->ops->get_func_proto(func_id);
  767. if (!fn) {
  768. verbose("unknown func %d\n", func_id);
  769. return -EINVAL;
  770. }
  771. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  772. if (!env->prog->gpl_compatible && fn->gpl_only) {
  773. verbose("cannot call GPL only function from proprietary program\n");
  774. return -EINVAL;
  775. }
  776. /* check args */
  777. err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &map);
  778. if (err)
  779. return err;
  780. err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &map);
  781. if (err)
  782. return err;
  783. err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &map);
  784. if (err)
  785. return err;
  786. err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &map);
  787. if (err)
  788. return err;
  789. err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &map);
  790. if (err)
  791. return err;
  792. /* reset caller saved regs */
  793. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  794. reg = regs + caller_saved[i];
  795. reg->type = NOT_INIT;
  796. reg->imm = 0;
  797. }
  798. /* update return register */
  799. if (fn->ret_type == RET_INTEGER) {
  800. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  801. } else if (fn->ret_type == RET_VOID) {
  802. regs[BPF_REG_0].type = NOT_INIT;
  803. } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
  804. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
  805. /* remember map_ptr, so that check_map_access()
  806. * can check 'value_size' boundary of memory access
  807. * to map element returned from bpf_map_lookup_elem()
  808. */
  809. if (map == NULL) {
  810. verbose("kernel subsystem misconfigured verifier\n");
  811. return -EINVAL;
  812. }
  813. regs[BPF_REG_0].map_ptr = map;
  814. } else {
  815. verbose("unknown return type %d of func %d\n",
  816. fn->ret_type, func_id);
  817. return -EINVAL;
  818. }
  819. if (map && map->map_type == BPF_MAP_TYPE_PROG_ARRAY &&
  820. func_id != BPF_FUNC_tail_call)
  821. /* prog_array map type needs extra care:
  822. * only allow to pass it into bpf_tail_call() for now.
  823. * bpf_map_delete_elem() can be allowed in the future,
  824. * while bpf_map_update_elem() must only be done via syscall
  825. */
  826. return -EINVAL;
  827. if (func_id == BPF_FUNC_tail_call &&
  828. map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  829. /* don't allow any other map type to be passed into
  830. * bpf_tail_call()
  831. */
  832. return -EINVAL;
  833. return 0;
  834. }
  835. /* check validity of 32-bit and 64-bit arithmetic operations */
  836. static int check_alu_op(struct reg_state *regs, struct bpf_insn *insn)
  837. {
  838. u8 opcode = BPF_OP(insn->code);
  839. int err;
  840. if (opcode == BPF_END || opcode == BPF_NEG) {
  841. if (opcode == BPF_NEG) {
  842. if (BPF_SRC(insn->code) != 0 ||
  843. insn->src_reg != BPF_REG_0 ||
  844. insn->off != 0 || insn->imm != 0) {
  845. verbose("BPF_NEG uses reserved fields\n");
  846. return -EINVAL;
  847. }
  848. } else {
  849. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  850. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
  851. verbose("BPF_END uses reserved fields\n");
  852. return -EINVAL;
  853. }
  854. }
  855. /* check src operand */
  856. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  857. if (err)
  858. return err;
  859. /* check dest operand */
  860. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  861. if (err)
  862. return err;
  863. } else if (opcode == BPF_MOV) {
  864. if (BPF_SRC(insn->code) == BPF_X) {
  865. if (insn->imm != 0 || insn->off != 0) {
  866. verbose("BPF_MOV uses reserved fields\n");
  867. return -EINVAL;
  868. }
  869. /* check src operand */
  870. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  871. if (err)
  872. return err;
  873. } else {
  874. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  875. verbose("BPF_MOV uses reserved fields\n");
  876. return -EINVAL;
  877. }
  878. }
  879. /* check dest operand */
  880. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  881. if (err)
  882. return err;
  883. if (BPF_SRC(insn->code) == BPF_X) {
  884. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  885. /* case: R1 = R2
  886. * copy register state to dest reg
  887. */
  888. regs[insn->dst_reg] = regs[insn->src_reg];
  889. } else {
  890. regs[insn->dst_reg].type = UNKNOWN_VALUE;
  891. regs[insn->dst_reg].map_ptr = NULL;
  892. }
  893. } else {
  894. /* case: R = imm
  895. * remember the value we stored into this reg
  896. */
  897. regs[insn->dst_reg].type = CONST_IMM;
  898. regs[insn->dst_reg].imm = insn->imm;
  899. }
  900. } else if (opcode > BPF_END) {
  901. verbose("invalid BPF_ALU opcode %x\n", opcode);
  902. return -EINVAL;
  903. } else { /* all other ALU ops: and, sub, xor, add, ... */
  904. bool stack_relative = false;
  905. if (BPF_SRC(insn->code) == BPF_X) {
  906. if (insn->imm != 0 || insn->off != 0) {
  907. verbose("BPF_ALU uses reserved fields\n");
  908. return -EINVAL;
  909. }
  910. /* check src1 operand */
  911. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  912. if (err)
  913. return err;
  914. } else {
  915. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  916. verbose("BPF_ALU uses reserved fields\n");
  917. return -EINVAL;
  918. }
  919. }
  920. /* check src2 operand */
  921. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  922. if (err)
  923. return err;
  924. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  925. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  926. verbose("div by zero\n");
  927. return -EINVAL;
  928. }
  929. /* pattern match 'bpf_add Rx, imm' instruction */
  930. if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
  931. regs[insn->dst_reg].type == FRAME_PTR &&
  932. BPF_SRC(insn->code) == BPF_K)
  933. stack_relative = true;
  934. /* check dest operand */
  935. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  936. if (err)
  937. return err;
  938. if (stack_relative) {
  939. regs[insn->dst_reg].type = PTR_TO_STACK;
  940. regs[insn->dst_reg].imm = insn->imm;
  941. }
  942. }
  943. return 0;
  944. }
  945. static int check_cond_jmp_op(struct verifier_env *env,
  946. struct bpf_insn *insn, int *insn_idx)
  947. {
  948. struct reg_state *regs = env->cur_state.regs;
  949. struct verifier_state *other_branch;
  950. u8 opcode = BPF_OP(insn->code);
  951. int err;
  952. if (opcode > BPF_EXIT) {
  953. verbose("invalid BPF_JMP opcode %x\n", opcode);
  954. return -EINVAL;
  955. }
  956. if (BPF_SRC(insn->code) == BPF_X) {
  957. if (insn->imm != 0) {
  958. verbose("BPF_JMP uses reserved fields\n");
  959. return -EINVAL;
  960. }
  961. /* check src1 operand */
  962. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  963. if (err)
  964. return err;
  965. } else {
  966. if (insn->src_reg != BPF_REG_0) {
  967. verbose("BPF_JMP uses reserved fields\n");
  968. return -EINVAL;
  969. }
  970. }
  971. /* check src2 operand */
  972. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  973. if (err)
  974. return err;
  975. /* detect if R == 0 where R was initialized to zero earlier */
  976. if (BPF_SRC(insn->code) == BPF_K &&
  977. (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  978. regs[insn->dst_reg].type == CONST_IMM &&
  979. regs[insn->dst_reg].imm == insn->imm) {
  980. if (opcode == BPF_JEQ) {
  981. /* if (imm == imm) goto pc+off;
  982. * only follow the goto, ignore fall-through
  983. */
  984. *insn_idx += insn->off;
  985. return 0;
  986. } else {
  987. /* if (imm != imm) goto pc+off;
  988. * only follow fall-through branch, since
  989. * that's where the program will go
  990. */
  991. return 0;
  992. }
  993. }
  994. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
  995. if (!other_branch)
  996. return -EFAULT;
  997. /* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
  998. if (BPF_SRC(insn->code) == BPF_K &&
  999. insn->imm == 0 && (opcode == BPF_JEQ ||
  1000. opcode == BPF_JNE) &&
  1001. regs[insn->dst_reg].type == PTR_TO_MAP_VALUE_OR_NULL) {
  1002. if (opcode == BPF_JEQ) {
  1003. /* next fallthrough insn can access memory via
  1004. * this register
  1005. */
  1006. regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1007. /* branch targer cannot access it, since reg == 0 */
  1008. other_branch->regs[insn->dst_reg].type = CONST_IMM;
  1009. other_branch->regs[insn->dst_reg].imm = 0;
  1010. } else {
  1011. other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
  1012. regs[insn->dst_reg].type = CONST_IMM;
  1013. regs[insn->dst_reg].imm = 0;
  1014. }
  1015. } else if (BPF_SRC(insn->code) == BPF_K &&
  1016. (opcode == BPF_JEQ || opcode == BPF_JNE)) {
  1017. if (opcode == BPF_JEQ) {
  1018. /* detect if (R == imm) goto
  1019. * and in the target state recognize that R = imm
  1020. */
  1021. other_branch->regs[insn->dst_reg].type = CONST_IMM;
  1022. other_branch->regs[insn->dst_reg].imm = insn->imm;
  1023. } else {
  1024. /* detect if (R != imm) goto
  1025. * and in the fall-through state recognize that R = imm
  1026. */
  1027. regs[insn->dst_reg].type = CONST_IMM;
  1028. regs[insn->dst_reg].imm = insn->imm;
  1029. }
  1030. }
  1031. if (log_level)
  1032. print_verifier_state(env);
  1033. return 0;
  1034. }
  1035. /* return the map pointer stored inside BPF_LD_IMM64 instruction */
  1036. static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
  1037. {
  1038. u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
  1039. return (struct bpf_map *) (unsigned long) imm64;
  1040. }
  1041. /* verify BPF_LD_IMM64 instruction */
  1042. static int check_ld_imm(struct verifier_env *env, struct bpf_insn *insn)
  1043. {
  1044. struct reg_state *regs = env->cur_state.regs;
  1045. int err;
  1046. if (BPF_SIZE(insn->code) != BPF_DW) {
  1047. verbose("invalid BPF_LD_IMM insn\n");
  1048. return -EINVAL;
  1049. }
  1050. if (insn->off != 0) {
  1051. verbose("BPF_LD_IMM64 uses reserved fields\n");
  1052. return -EINVAL;
  1053. }
  1054. err = check_reg_arg(regs, insn->dst_reg, DST_OP);
  1055. if (err)
  1056. return err;
  1057. if (insn->src_reg == 0)
  1058. /* generic move 64-bit immediate into a register */
  1059. return 0;
  1060. /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
  1061. BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
  1062. regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
  1063. regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
  1064. return 0;
  1065. }
  1066. static bool may_access_skb(enum bpf_prog_type type)
  1067. {
  1068. switch (type) {
  1069. case BPF_PROG_TYPE_SOCKET_FILTER:
  1070. case BPF_PROG_TYPE_SCHED_CLS:
  1071. case BPF_PROG_TYPE_SCHED_ACT:
  1072. return true;
  1073. default:
  1074. return false;
  1075. }
  1076. }
  1077. /* verify safety of LD_ABS|LD_IND instructions:
  1078. * - they can only appear in the programs where ctx == skb
  1079. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  1080. * preserve R6-R9, and store return value into R0
  1081. *
  1082. * Implicit input:
  1083. * ctx == skb == R6 == CTX
  1084. *
  1085. * Explicit input:
  1086. * SRC == any register
  1087. * IMM == 32-bit immediate
  1088. *
  1089. * Output:
  1090. * R0 - 8/16/32-bit skb data converted to cpu endianness
  1091. */
  1092. static int check_ld_abs(struct verifier_env *env, struct bpf_insn *insn)
  1093. {
  1094. struct reg_state *regs = env->cur_state.regs;
  1095. u8 mode = BPF_MODE(insn->code);
  1096. struct reg_state *reg;
  1097. int i, err;
  1098. if (!may_access_skb(env->prog->type)) {
  1099. verbose("BPF_LD_ABS|IND instructions not allowed for this program type\n");
  1100. return -EINVAL;
  1101. }
  1102. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  1103. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  1104. verbose("BPF_LD_ABS uses reserved fields\n");
  1105. return -EINVAL;
  1106. }
  1107. /* check whether implicit source operand (register R6) is readable */
  1108. err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
  1109. if (err)
  1110. return err;
  1111. if (regs[BPF_REG_6].type != PTR_TO_CTX) {
  1112. verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  1113. return -EINVAL;
  1114. }
  1115. if (mode == BPF_IND) {
  1116. /* check explicit source operand */
  1117. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1118. if (err)
  1119. return err;
  1120. }
  1121. /* reset caller saved regs to unreadable */
  1122. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  1123. reg = regs + caller_saved[i];
  1124. reg->type = NOT_INIT;
  1125. reg->imm = 0;
  1126. }
  1127. /* mark destination R0 register as readable, since it contains
  1128. * the value fetched from the packet
  1129. */
  1130. regs[BPF_REG_0].type = UNKNOWN_VALUE;
  1131. return 0;
  1132. }
  1133. /* non-recursive DFS pseudo code
  1134. * 1 procedure DFS-iterative(G,v):
  1135. * 2 label v as discovered
  1136. * 3 let S be a stack
  1137. * 4 S.push(v)
  1138. * 5 while S is not empty
  1139. * 6 t <- S.pop()
  1140. * 7 if t is what we're looking for:
  1141. * 8 return t
  1142. * 9 for all edges e in G.adjacentEdges(t) do
  1143. * 10 if edge e is already labelled
  1144. * 11 continue with the next edge
  1145. * 12 w <- G.adjacentVertex(t,e)
  1146. * 13 if vertex w is not discovered and not explored
  1147. * 14 label e as tree-edge
  1148. * 15 label w as discovered
  1149. * 16 S.push(w)
  1150. * 17 continue at 5
  1151. * 18 else if vertex w is discovered
  1152. * 19 label e as back-edge
  1153. * 20 else
  1154. * 21 // vertex w is explored
  1155. * 22 label e as forward- or cross-edge
  1156. * 23 label t as explored
  1157. * 24 S.pop()
  1158. *
  1159. * convention:
  1160. * 0x10 - discovered
  1161. * 0x11 - discovered and fall-through edge labelled
  1162. * 0x12 - discovered and fall-through and branch edges labelled
  1163. * 0x20 - explored
  1164. */
  1165. enum {
  1166. DISCOVERED = 0x10,
  1167. EXPLORED = 0x20,
  1168. FALLTHROUGH = 1,
  1169. BRANCH = 2,
  1170. };
  1171. #define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
  1172. static int *insn_stack; /* stack of insns to process */
  1173. static int cur_stack; /* current stack index */
  1174. static int *insn_state;
  1175. /* t, w, e - match pseudo-code above:
  1176. * t - index of current instruction
  1177. * w - next instruction
  1178. * e - edge
  1179. */
  1180. static int push_insn(int t, int w, int e, struct verifier_env *env)
  1181. {
  1182. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  1183. return 0;
  1184. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  1185. return 0;
  1186. if (w < 0 || w >= env->prog->len) {
  1187. verbose("jump out of range from insn %d to %d\n", t, w);
  1188. return -EINVAL;
  1189. }
  1190. if (e == BRANCH)
  1191. /* mark branch target for state pruning */
  1192. env->explored_states[w] = STATE_LIST_MARK;
  1193. if (insn_state[w] == 0) {
  1194. /* tree-edge */
  1195. insn_state[t] = DISCOVERED | e;
  1196. insn_state[w] = DISCOVERED;
  1197. if (cur_stack >= env->prog->len)
  1198. return -E2BIG;
  1199. insn_stack[cur_stack++] = w;
  1200. return 1;
  1201. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  1202. verbose("back-edge from insn %d to %d\n", t, w);
  1203. return -EINVAL;
  1204. } else if (insn_state[w] == EXPLORED) {
  1205. /* forward- or cross-edge */
  1206. insn_state[t] = DISCOVERED | e;
  1207. } else {
  1208. verbose("insn state internal bug\n");
  1209. return -EFAULT;
  1210. }
  1211. return 0;
  1212. }
  1213. /* non-recursive depth-first-search to detect loops in BPF program
  1214. * loop == back-edge in directed graph
  1215. */
  1216. static int check_cfg(struct verifier_env *env)
  1217. {
  1218. struct bpf_insn *insns = env->prog->insnsi;
  1219. int insn_cnt = env->prog->len;
  1220. int ret = 0;
  1221. int i, t;
  1222. insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1223. if (!insn_state)
  1224. return -ENOMEM;
  1225. insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  1226. if (!insn_stack) {
  1227. kfree(insn_state);
  1228. return -ENOMEM;
  1229. }
  1230. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  1231. insn_stack[0] = 0; /* 0 is the first instruction */
  1232. cur_stack = 1;
  1233. peek_stack:
  1234. if (cur_stack == 0)
  1235. goto check_state;
  1236. t = insn_stack[cur_stack - 1];
  1237. if (BPF_CLASS(insns[t].code) == BPF_JMP) {
  1238. u8 opcode = BPF_OP(insns[t].code);
  1239. if (opcode == BPF_EXIT) {
  1240. goto mark_explored;
  1241. } else if (opcode == BPF_CALL) {
  1242. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1243. if (ret == 1)
  1244. goto peek_stack;
  1245. else if (ret < 0)
  1246. goto err_free;
  1247. } else if (opcode == BPF_JA) {
  1248. if (BPF_SRC(insns[t].code) != BPF_K) {
  1249. ret = -EINVAL;
  1250. goto err_free;
  1251. }
  1252. /* unconditional jump with single edge */
  1253. ret = push_insn(t, t + insns[t].off + 1,
  1254. FALLTHROUGH, env);
  1255. if (ret == 1)
  1256. goto peek_stack;
  1257. else if (ret < 0)
  1258. goto err_free;
  1259. /* tell verifier to check for equivalent states
  1260. * after every call and jump
  1261. */
  1262. if (t + 1 < insn_cnt)
  1263. env->explored_states[t + 1] = STATE_LIST_MARK;
  1264. } else {
  1265. /* conditional jump with two edges */
  1266. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1267. if (ret == 1)
  1268. goto peek_stack;
  1269. else if (ret < 0)
  1270. goto err_free;
  1271. ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
  1272. if (ret == 1)
  1273. goto peek_stack;
  1274. else if (ret < 0)
  1275. goto err_free;
  1276. }
  1277. } else {
  1278. /* all other non-branch instructions with single
  1279. * fall-through edge
  1280. */
  1281. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  1282. if (ret == 1)
  1283. goto peek_stack;
  1284. else if (ret < 0)
  1285. goto err_free;
  1286. }
  1287. mark_explored:
  1288. insn_state[t] = EXPLORED;
  1289. if (cur_stack-- <= 0) {
  1290. verbose("pop stack internal bug\n");
  1291. ret = -EFAULT;
  1292. goto err_free;
  1293. }
  1294. goto peek_stack;
  1295. check_state:
  1296. for (i = 0; i < insn_cnt; i++) {
  1297. if (insn_state[i] != EXPLORED) {
  1298. verbose("unreachable insn %d\n", i);
  1299. ret = -EINVAL;
  1300. goto err_free;
  1301. }
  1302. }
  1303. ret = 0; /* cfg looks good */
  1304. err_free:
  1305. kfree(insn_state);
  1306. kfree(insn_stack);
  1307. return ret;
  1308. }
  1309. /* compare two verifier states
  1310. *
  1311. * all states stored in state_list are known to be valid, since
  1312. * verifier reached 'bpf_exit' instruction through them
  1313. *
  1314. * this function is called when verifier exploring different branches of
  1315. * execution popped from the state stack. If it sees an old state that has
  1316. * more strict register state and more strict stack state then this execution
  1317. * branch doesn't need to be explored further, since verifier already
  1318. * concluded that more strict state leads to valid finish.
  1319. *
  1320. * Therefore two states are equivalent if register state is more conservative
  1321. * and explored stack state is more conservative than the current one.
  1322. * Example:
  1323. * explored current
  1324. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  1325. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  1326. *
  1327. * In other words if current stack state (one being explored) has more
  1328. * valid slots than old one that already passed validation, it means
  1329. * the verifier can stop exploring and conclude that current state is valid too
  1330. *
  1331. * Similarly with registers. If explored state has register type as invalid
  1332. * whereas register type in current state is meaningful, it means that
  1333. * the current state will reach 'bpf_exit' instruction safely
  1334. */
  1335. static bool states_equal(struct verifier_state *old, struct verifier_state *cur)
  1336. {
  1337. int i;
  1338. for (i = 0; i < MAX_BPF_REG; i++) {
  1339. if (memcmp(&old->regs[i], &cur->regs[i],
  1340. sizeof(old->regs[0])) != 0) {
  1341. if (old->regs[i].type == NOT_INIT ||
  1342. (old->regs[i].type == UNKNOWN_VALUE &&
  1343. cur->regs[i].type != NOT_INIT))
  1344. continue;
  1345. return false;
  1346. }
  1347. }
  1348. for (i = 0; i < MAX_BPF_STACK; i++) {
  1349. if (old->stack_slot_type[i] == STACK_INVALID)
  1350. continue;
  1351. if (old->stack_slot_type[i] != cur->stack_slot_type[i])
  1352. /* Ex: old explored (safe) state has STACK_SPILL in
  1353. * this stack slot, but current has has STACK_MISC ->
  1354. * this verifier states are not equivalent,
  1355. * return false to continue verification of this path
  1356. */
  1357. return false;
  1358. if (i % BPF_REG_SIZE)
  1359. continue;
  1360. if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
  1361. &cur->spilled_regs[i / BPF_REG_SIZE],
  1362. sizeof(old->spilled_regs[0])))
  1363. /* when explored and current stack slot types are
  1364. * the same, check that stored pointers types
  1365. * are the same as well.
  1366. * Ex: explored safe path could have stored
  1367. * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8}
  1368. * but current path has stored:
  1369. * (struct reg_state) {.type = PTR_TO_STACK, .imm = -16}
  1370. * such verifier states are not equivalent.
  1371. * return false to continue verification of this path
  1372. */
  1373. return false;
  1374. else
  1375. continue;
  1376. }
  1377. return true;
  1378. }
  1379. static int is_state_visited(struct verifier_env *env, int insn_idx)
  1380. {
  1381. struct verifier_state_list *new_sl;
  1382. struct verifier_state_list *sl;
  1383. sl = env->explored_states[insn_idx];
  1384. if (!sl)
  1385. /* this 'insn_idx' instruction wasn't marked, so we will not
  1386. * be doing state search here
  1387. */
  1388. return 0;
  1389. while (sl != STATE_LIST_MARK) {
  1390. if (states_equal(&sl->state, &env->cur_state))
  1391. /* reached equivalent register/stack state,
  1392. * prune the search
  1393. */
  1394. return 1;
  1395. sl = sl->next;
  1396. }
  1397. /* there were no equivalent states, remember current one.
  1398. * technically the current state is not proven to be safe yet,
  1399. * but it will either reach bpf_exit (which means it's safe) or
  1400. * it will be rejected. Since there are no loops, we won't be
  1401. * seeing this 'insn_idx' instruction again on the way to bpf_exit
  1402. */
  1403. new_sl = kmalloc(sizeof(struct verifier_state_list), GFP_USER);
  1404. if (!new_sl)
  1405. return -ENOMEM;
  1406. /* add new state to the head of linked list */
  1407. memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
  1408. new_sl->next = env->explored_states[insn_idx];
  1409. env->explored_states[insn_idx] = new_sl;
  1410. return 0;
  1411. }
  1412. static int do_check(struct verifier_env *env)
  1413. {
  1414. struct verifier_state *state = &env->cur_state;
  1415. struct bpf_insn *insns = env->prog->insnsi;
  1416. struct reg_state *regs = state->regs;
  1417. int insn_cnt = env->prog->len;
  1418. int insn_idx, prev_insn_idx = 0;
  1419. int insn_processed = 0;
  1420. bool do_print_state = false;
  1421. init_reg_state(regs);
  1422. insn_idx = 0;
  1423. for (;;) {
  1424. struct bpf_insn *insn;
  1425. u8 class;
  1426. int err;
  1427. if (insn_idx >= insn_cnt) {
  1428. verbose("invalid insn idx %d insn_cnt %d\n",
  1429. insn_idx, insn_cnt);
  1430. return -EFAULT;
  1431. }
  1432. insn = &insns[insn_idx];
  1433. class = BPF_CLASS(insn->code);
  1434. if (++insn_processed > 32768) {
  1435. verbose("BPF program is too large. Proccessed %d insn\n",
  1436. insn_processed);
  1437. return -E2BIG;
  1438. }
  1439. err = is_state_visited(env, insn_idx);
  1440. if (err < 0)
  1441. return err;
  1442. if (err == 1) {
  1443. /* found equivalent state, can prune the search */
  1444. if (log_level) {
  1445. if (do_print_state)
  1446. verbose("\nfrom %d to %d: safe\n",
  1447. prev_insn_idx, insn_idx);
  1448. else
  1449. verbose("%d: safe\n", insn_idx);
  1450. }
  1451. goto process_bpf_exit;
  1452. }
  1453. if (log_level && do_print_state) {
  1454. verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
  1455. print_verifier_state(env);
  1456. do_print_state = false;
  1457. }
  1458. if (log_level) {
  1459. verbose("%d: ", insn_idx);
  1460. print_bpf_insn(insn);
  1461. }
  1462. if (class == BPF_ALU || class == BPF_ALU64) {
  1463. err = check_alu_op(regs, insn);
  1464. if (err)
  1465. return err;
  1466. } else if (class == BPF_LDX) {
  1467. enum bpf_reg_type src_reg_type;
  1468. /* check for reserved fields is already done */
  1469. /* check src operand */
  1470. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1471. if (err)
  1472. return err;
  1473. err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
  1474. if (err)
  1475. return err;
  1476. src_reg_type = regs[insn->src_reg].type;
  1477. /* check that memory (src_reg + off) is readable,
  1478. * the state of dst_reg will be updated by this func
  1479. */
  1480. err = check_mem_access(env, insn->src_reg, insn->off,
  1481. BPF_SIZE(insn->code), BPF_READ,
  1482. insn->dst_reg);
  1483. if (err)
  1484. return err;
  1485. if (BPF_SIZE(insn->code) != BPF_W) {
  1486. insn_idx++;
  1487. continue;
  1488. }
  1489. if (insn->imm == 0) {
  1490. /* saw a valid insn
  1491. * dst_reg = *(u32 *)(src_reg + off)
  1492. * use reserved 'imm' field to mark this insn
  1493. */
  1494. insn->imm = src_reg_type;
  1495. } else if (src_reg_type != insn->imm &&
  1496. (src_reg_type == PTR_TO_CTX ||
  1497. insn->imm == PTR_TO_CTX)) {
  1498. /* ABuser program is trying to use the same insn
  1499. * dst_reg = *(u32*) (src_reg + off)
  1500. * with different pointer types:
  1501. * src_reg == ctx in one branch and
  1502. * src_reg == stack|map in some other branch.
  1503. * Reject it.
  1504. */
  1505. verbose("same insn cannot be used with different pointers\n");
  1506. return -EINVAL;
  1507. }
  1508. } else if (class == BPF_STX) {
  1509. enum bpf_reg_type dst_reg_type;
  1510. if (BPF_MODE(insn->code) == BPF_XADD) {
  1511. err = check_xadd(env, insn);
  1512. if (err)
  1513. return err;
  1514. insn_idx++;
  1515. continue;
  1516. }
  1517. /* check src1 operand */
  1518. err = check_reg_arg(regs, insn->src_reg, SRC_OP);
  1519. if (err)
  1520. return err;
  1521. /* check src2 operand */
  1522. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1523. if (err)
  1524. return err;
  1525. dst_reg_type = regs[insn->dst_reg].type;
  1526. /* check that memory (dst_reg + off) is writeable */
  1527. err = check_mem_access(env, insn->dst_reg, insn->off,
  1528. BPF_SIZE(insn->code), BPF_WRITE,
  1529. insn->src_reg);
  1530. if (err)
  1531. return err;
  1532. if (insn->imm == 0) {
  1533. insn->imm = dst_reg_type;
  1534. } else if (dst_reg_type != insn->imm &&
  1535. (dst_reg_type == PTR_TO_CTX ||
  1536. insn->imm == PTR_TO_CTX)) {
  1537. verbose("same insn cannot be used with different pointers\n");
  1538. return -EINVAL;
  1539. }
  1540. } else if (class == BPF_ST) {
  1541. if (BPF_MODE(insn->code) != BPF_MEM ||
  1542. insn->src_reg != BPF_REG_0) {
  1543. verbose("BPF_ST uses reserved fields\n");
  1544. return -EINVAL;
  1545. }
  1546. /* check src operand */
  1547. err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
  1548. if (err)
  1549. return err;
  1550. /* check that memory (dst_reg + off) is writeable */
  1551. err = check_mem_access(env, insn->dst_reg, insn->off,
  1552. BPF_SIZE(insn->code), BPF_WRITE,
  1553. -1);
  1554. if (err)
  1555. return err;
  1556. } else if (class == BPF_JMP) {
  1557. u8 opcode = BPF_OP(insn->code);
  1558. if (opcode == BPF_CALL) {
  1559. if (BPF_SRC(insn->code) != BPF_K ||
  1560. insn->off != 0 ||
  1561. insn->src_reg != BPF_REG_0 ||
  1562. insn->dst_reg != BPF_REG_0) {
  1563. verbose("BPF_CALL uses reserved fields\n");
  1564. return -EINVAL;
  1565. }
  1566. err = check_call(env, insn->imm);
  1567. if (err)
  1568. return err;
  1569. } else if (opcode == BPF_JA) {
  1570. if (BPF_SRC(insn->code) != BPF_K ||
  1571. insn->imm != 0 ||
  1572. insn->src_reg != BPF_REG_0 ||
  1573. insn->dst_reg != BPF_REG_0) {
  1574. verbose("BPF_JA uses reserved fields\n");
  1575. return -EINVAL;
  1576. }
  1577. insn_idx += insn->off + 1;
  1578. continue;
  1579. } else if (opcode == BPF_EXIT) {
  1580. if (BPF_SRC(insn->code) != BPF_K ||
  1581. insn->imm != 0 ||
  1582. insn->src_reg != BPF_REG_0 ||
  1583. insn->dst_reg != BPF_REG_0) {
  1584. verbose("BPF_EXIT uses reserved fields\n");
  1585. return -EINVAL;
  1586. }
  1587. /* eBPF calling convetion is such that R0 is used
  1588. * to return the value from eBPF program.
  1589. * Make sure that it's readable at this time
  1590. * of bpf_exit, which means that program wrote
  1591. * something into it earlier
  1592. */
  1593. err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
  1594. if (err)
  1595. return err;
  1596. process_bpf_exit:
  1597. insn_idx = pop_stack(env, &prev_insn_idx);
  1598. if (insn_idx < 0) {
  1599. break;
  1600. } else {
  1601. do_print_state = true;
  1602. continue;
  1603. }
  1604. } else {
  1605. err = check_cond_jmp_op(env, insn, &insn_idx);
  1606. if (err)
  1607. return err;
  1608. }
  1609. } else if (class == BPF_LD) {
  1610. u8 mode = BPF_MODE(insn->code);
  1611. if (mode == BPF_ABS || mode == BPF_IND) {
  1612. err = check_ld_abs(env, insn);
  1613. if (err)
  1614. return err;
  1615. } else if (mode == BPF_IMM) {
  1616. err = check_ld_imm(env, insn);
  1617. if (err)
  1618. return err;
  1619. insn_idx++;
  1620. } else {
  1621. verbose("invalid BPF_LD mode\n");
  1622. return -EINVAL;
  1623. }
  1624. } else {
  1625. verbose("unknown insn class %d\n", class);
  1626. return -EINVAL;
  1627. }
  1628. insn_idx++;
  1629. }
  1630. return 0;
  1631. }
  1632. /* look for pseudo eBPF instructions that access map FDs and
  1633. * replace them with actual map pointers
  1634. */
  1635. static int replace_map_fd_with_map_ptr(struct verifier_env *env)
  1636. {
  1637. struct bpf_insn *insn = env->prog->insnsi;
  1638. int insn_cnt = env->prog->len;
  1639. int i, j;
  1640. for (i = 0; i < insn_cnt; i++, insn++) {
  1641. if (BPF_CLASS(insn->code) == BPF_LDX &&
  1642. (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
  1643. verbose("BPF_LDX uses reserved fields\n");
  1644. return -EINVAL;
  1645. }
  1646. if (BPF_CLASS(insn->code) == BPF_STX &&
  1647. ((BPF_MODE(insn->code) != BPF_MEM &&
  1648. BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
  1649. verbose("BPF_STX uses reserved fields\n");
  1650. return -EINVAL;
  1651. }
  1652. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  1653. struct bpf_map *map;
  1654. struct fd f;
  1655. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  1656. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  1657. insn[1].off != 0) {
  1658. verbose("invalid bpf_ld_imm64 insn\n");
  1659. return -EINVAL;
  1660. }
  1661. if (insn->src_reg == 0)
  1662. /* valid generic load 64-bit imm */
  1663. goto next_insn;
  1664. if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
  1665. verbose("unrecognized bpf_ld_imm64 insn\n");
  1666. return -EINVAL;
  1667. }
  1668. f = fdget(insn->imm);
  1669. map = bpf_map_get(f);
  1670. if (IS_ERR(map)) {
  1671. verbose("fd %d is not pointing to valid bpf_map\n",
  1672. insn->imm);
  1673. fdput(f);
  1674. return PTR_ERR(map);
  1675. }
  1676. /* store map pointer inside BPF_LD_IMM64 instruction */
  1677. insn[0].imm = (u32) (unsigned long) map;
  1678. insn[1].imm = ((u64) (unsigned long) map) >> 32;
  1679. /* check whether we recorded this map already */
  1680. for (j = 0; j < env->used_map_cnt; j++)
  1681. if (env->used_maps[j] == map) {
  1682. fdput(f);
  1683. goto next_insn;
  1684. }
  1685. if (env->used_map_cnt >= MAX_USED_MAPS) {
  1686. fdput(f);
  1687. return -E2BIG;
  1688. }
  1689. /* remember this map */
  1690. env->used_maps[env->used_map_cnt++] = map;
  1691. /* hold the map. If the program is rejected by verifier,
  1692. * the map will be released by release_maps() or it
  1693. * will be used by the valid program until it's unloaded
  1694. * and all maps are released in free_bpf_prog_info()
  1695. */
  1696. atomic_inc(&map->refcnt);
  1697. fdput(f);
  1698. next_insn:
  1699. insn++;
  1700. i++;
  1701. }
  1702. }
  1703. /* now all pseudo BPF_LD_IMM64 instructions load valid
  1704. * 'struct bpf_map *' into a register instead of user map_fd.
  1705. * These pointers will be used later by verifier to validate map access.
  1706. */
  1707. return 0;
  1708. }
  1709. /* drop refcnt of maps used by the rejected program */
  1710. static void release_maps(struct verifier_env *env)
  1711. {
  1712. int i;
  1713. for (i = 0; i < env->used_map_cnt; i++)
  1714. bpf_map_put(env->used_maps[i]);
  1715. }
  1716. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  1717. static void convert_pseudo_ld_imm64(struct verifier_env *env)
  1718. {
  1719. struct bpf_insn *insn = env->prog->insnsi;
  1720. int insn_cnt = env->prog->len;
  1721. int i;
  1722. for (i = 0; i < insn_cnt; i++, insn++)
  1723. if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
  1724. insn->src_reg = 0;
  1725. }
  1726. static void adjust_branches(struct bpf_prog *prog, int pos, int delta)
  1727. {
  1728. struct bpf_insn *insn = prog->insnsi;
  1729. int insn_cnt = prog->len;
  1730. int i;
  1731. for (i = 0; i < insn_cnt; i++, insn++) {
  1732. if (BPF_CLASS(insn->code) != BPF_JMP ||
  1733. BPF_OP(insn->code) == BPF_CALL ||
  1734. BPF_OP(insn->code) == BPF_EXIT)
  1735. continue;
  1736. /* adjust offset of jmps if necessary */
  1737. if (i < pos && i + insn->off + 1 > pos)
  1738. insn->off += delta;
  1739. else if (i > pos && i + insn->off + 1 < pos)
  1740. insn->off -= delta;
  1741. }
  1742. }
  1743. /* convert load instructions that access fields of 'struct __sk_buff'
  1744. * into sequence of instructions that access fields of 'struct sk_buff'
  1745. */
  1746. static int convert_ctx_accesses(struct verifier_env *env)
  1747. {
  1748. struct bpf_insn *insn = env->prog->insnsi;
  1749. int insn_cnt = env->prog->len;
  1750. struct bpf_insn insn_buf[16];
  1751. struct bpf_prog *new_prog;
  1752. u32 cnt;
  1753. int i;
  1754. enum bpf_access_type type;
  1755. if (!env->prog->aux->ops->convert_ctx_access)
  1756. return 0;
  1757. for (i = 0; i < insn_cnt; i++, insn++) {
  1758. if (insn->code == (BPF_LDX | BPF_MEM | BPF_W))
  1759. type = BPF_READ;
  1760. else if (insn->code == (BPF_STX | BPF_MEM | BPF_W))
  1761. type = BPF_WRITE;
  1762. else
  1763. continue;
  1764. if (insn->imm != PTR_TO_CTX) {
  1765. /* clear internal mark */
  1766. insn->imm = 0;
  1767. continue;
  1768. }
  1769. cnt = env->prog->aux->ops->
  1770. convert_ctx_access(type, insn->dst_reg, insn->src_reg,
  1771. insn->off, insn_buf);
  1772. if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
  1773. verbose("bpf verifier is misconfigured\n");
  1774. return -EINVAL;
  1775. }
  1776. if (cnt == 1) {
  1777. memcpy(insn, insn_buf, sizeof(*insn));
  1778. continue;
  1779. }
  1780. /* several new insns need to be inserted. Make room for them */
  1781. insn_cnt += cnt - 1;
  1782. new_prog = bpf_prog_realloc(env->prog,
  1783. bpf_prog_size(insn_cnt),
  1784. GFP_USER);
  1785. if (!new_prog)
  1786. return -ENOMEM;
  1787. new_prog->len = insn_cnt;
  1788. memmove(new_prog->insnsi + i + cnt, new_prog->insns + i + 1,
  1789. sizeof(*insn) * (insn_cnt - i - cnt));
  1790. /* copy substitute insns in place of load instruction */
  1791. memcpy(new_prog->insnsi + i, insn_buf, sizeof(*insn) * cnt);
  1792. /* adjust branches in the whole program */
  1793. adjust_branches(new_prog, i, cnt - 1);
  1794. /* keep walking new program and skip insns we just inserted */
  1795. env->prog = new_prog;
  1796. insn = new_prog->insnsi + i + cnt - 1;
  1797. i += cnt - 1;
  1798. }
  1799. return 0;
  1800. }
  1801. static void free_states(struct verifier_env *env)
  1802. {
  1803. struct verifier_state_list *sl, *sln;
  1804. int i;
  1805. if (!env->explored_states)
  1806. return;
  1807. for (i = 0; i < env->prog->len; i++) {
  1808. sl = env->explored_states[i];
  1809. if (sl)
  1810. while (sl != STATE_LIST_MARK) {
  1811. sln = sl->next;
  1812. kfree(sl);
  1813. sl = sln;
  1814. }
  1815. }
  1816. kfree(env->explored_states);
  1817. }
  1818. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
  1819. {
  1820. char __user *log_ubuf = NULL;
  1821. struct verifier_env *env;
  1822. int ret = -EINVAL;
  1823. if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
  1824. return -E2BIG;
  1825. /* 'struct verifier_env' can be global, but since it's not small,
  1826. * allocate/free it every time bpf_check() is called
  1827. */
  1828. env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL);
  1829. if (!env)
  1830. return -ENOMEM;
  1831. env->prog = *prog;
  1832. /* grab the mutex to protect few globals used by verifier */
  1833. mutex_lock(&bpf_verifier_lock);
  1834. if (attr->log_level || attr->log_buf || attr->log_size) {
  1835. /* user requested verbose verifier output
  1836. * and supplied buffer to store the verification trace
  1837. */
  1838. log_level = attr->log_level;
  1839. log_ubuf = (char __user *) (unsigned long) attr->log_buf;
  1840. log_size = attr->log_size;
  1841. log_len = 0;
  1842. ret = -EINVAL;
  1843. /* log_* values have to be sane */
  1844. if (log_size < 128 || log_size > UINT_MAX >> 8 ||
  1845. log_level == 0 || log_ubuf == NULL)
  1846. goto free_env;
  1847. ret = -ENOMEM;
  1848. log_buf = vmalloc(log_size);
  1849. if (!log_buf)
  1850. goto free_env;
  1851. } else {
  1852. log_level = 0;
  1853. }
  1854. ret = replace_map_fd_with_map_ptr(env);
  1855. if (ret < 0)
  1856. goto skip_full_check;
  1857. env->explored_states = kcalloc(env->prog->len,
  1858. sizeof(struct verifier_state_list *),
  1859. GFP_USER);
  1860. ret = -ENOMEM;
  1861. if (!env->explored_states)
  1862. goto skip_full_check;
  1863. ret = check_cfg(env);
  1864. if (ret < 0)
  1865. goto skip_full_check;
  1866. ret = do_check(env);
  1867. skip_full_check:
  1868. while (pop_stack(env, NULL) >= 0);
  1869. free_states(env);
  1870. if (ret == 0)
  1871. /* program is valid, convert *(u32*)(ctx + off) accesses */
  1872. ret = convert_ctx_accesses(env);
  1873. if (log_level && log_len >= log_size - 1) {
  1874. BUG_ON(log_len >= log_size);
  1875. /* verifier log exceeded user supplied buffer */
  1876. ret = -ENOSPC;
  1877. /* fall through to return what was recorded */
  1878. }
  1879. /* copy verifier log back to user space including trailing zero */
  1880. if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
  1881. ret = -EFAULT;
  1882. goto free_log_buf;
  1883. }
  1884. if (ret == 0 && env->used_map_cnt) {
  1885. /* if program passed verifier, update used_maps in bpf_prog_info */
  1886. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  1887. sizeof(env->used_maps[0]),
  1888. GFP_KERNEL);
  1889. if (!env->prog->aux->used_maps) {
  1890. ret = -ENOMEM;
  1891. goto free_log_buf;
  1892. }
  1893. memcpy(env->prog->aux->used_maps, env->used_maps,
  1894. sizeof(env->used_maps[0]) * env->used_map_cnt);
  1895. env->prog->aux->used_map_cnt = env->used_map_cnt;
  1896. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  1897. * bpf_ld_imm64 instructions
  1898. */
  1899. convert_pseudo_ld_imm64(env);
  1900. }
  1901. free_log_buf:
  1902. if (log_level)
  1903. vfree(log_buf);
  1904. free_env:
  1905. if (!env->prog->aux->used_maps)
  1906. /* if we didn't copy map pointers into bpf_prog_info, release
  1907. * them now. Otherwise free_bpf_prog_info() will release them.
  1908. */
  1909. release_maps(env);
  1910. *prog = env->prog;
  1911. kfree(env);
  1912. mutex_unlock(&bpf_verifier_lock);
  1913. return ret;
  1914. }