bpf_verifier.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /* SPDX-License-Identifier: GPL-2.0-only */
  2. /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  3. */
  4. #ifndef _LINUX_BPF_VERIFIER_H
  5. #define _LINUX_BPF_VERIFIER_H 1
  6. #include <linux/bpf.h> /* for enum bpf_reg_type */
  7. #include <linux/filter.h> /* for MAX_BPF_STACK */
  8. #include <linux/tnum.h>
  9. #include <linux/android_kabi.h>
  10. /* Maximum variable offset umax_value permitted when resolving memory accesses.
  11. * In practice this is far bigger than any realistic pointer offset; this limit
  12. * ensures that umax_value + (int)off + (int)size cannot overflow a u64.
  13. */
  14. #define BPF_MAX_VAR_OFF (1 << 29)
  15. /* Maximum variable size permitted for ARG_CONST_SIZE[_OR_ZERO]. This ensures
  16. * that converting umax_value to int cannot overflow.
  17. */
  18. #define BPF_MAX_VAR_SIZ (1 << 29)
  19. /* Liveness marks, used for registers and spilled-regs (in stack slots).
  20. * Read marks propagate upwards until they find a write mark; they record that
  21. * "one of this state's descendants read this reg" (and therefore the reg is
  22. * relevant for states_equal() checks).
  23. * Write marks collect downwards and do not propagate; they record that "the
  24. * straight-line code that reached this state (from its parent) wrote this reg"
  25. * (and therefore that reads propagated from this state or its descendants
  26. * should not propagate to its parent).
  27. * A state with a write mark can receive read marks; it just won't propagate
  28. * them to its parent, since the write mark is a property, not of the state,
  29. * but of the link between it and its parent. See mark_reg_read() and
  30. * mark_stack_slot_read() in kernel/bpf/verifier.c.
  31. */
  32. enum bpf_reg_liveness {
  33. REG_LIVE_NONE = 0, /* reg hasn't been read or written this branch */
  34. REG_LIVE_READ32 = 0x1, /* reg was read, so we're sensitive to initial value */
  35. REG_LIVE_READ64 = 0x2, /* likewise, but full 64-bit content matters */
  36. REG_LIVE_READ = REG_LIVE_READ32 | REG_LIVE_READ64,
  37. REG_LIVE_WRITTEN = 0x4, /* reg was written first, screening off later reads */
  38. REG_LIVE_DONE = 0x8, /* liveness won't be updating this register anymore */
  39. };
  40. struct bpf_reg_state {
  41. /* Ordering of fields matters. See states_equal() */
  42. enum bpf_reg_type type;
  43. union {
  44. /* valid when type == PTR_TO_PACKET */
  45. u16 range;
  46. /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
  47. * PTR_TO_MAP_VALUE_OR_NULL
  48. */
  49. struct bpf_map *map_ptr;
  50. u32 btf_id; /* for PTR_TO_BTF_ID */
  51. u32 mem_size; /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */
  52. /* Max size from any of the above. */
  53. unsigned long raw;
  54. };
  55. /* Fixed part of pointer offset, pointer types only */
  56. s32 off;
  57. /* For PTR_TO_PACKET, used to find other pointers with the same variable
  58. * offset, so they can share range knowledge.
  59. * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we
  60. * came from, when one is tested for != NULL.
  61. * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation
  62. * for the purpose of tracking that it's freed.
  63. * For PTR_TO_SOCKET this is used to share which pointers retain the
  64. * same reference to the socket, to determine proper reference freeing.
  65. */
  66. u32 id;
  67. /* PTR_TO_SOCKET and PTR_TO_TCP_SOCK could be a ptr returned
  68. * from a pointer-cast helper, bpf_sk_fullsock() and
  69. * bpf_tcp_sock().
  70. *
  71. * Consider the following where "sk" is a reference counted
  72. * pointer returned from "sk = bpf_sk_lookup_tcp();":
  73. *
  74. * 1: sk = bpf_sk_lookup_tcp();
  75. * 2: if (!sk) { return 0; }
  76. * 3: fullsock = bpf_sk_fullsock(sk);
  77. * 4: if (!fullsock) { bpf_sk_release(sk); return 0; }
  78. * 5: tp = bpf_tcp_sock(fullsock);
  79. * 6: if (!tp) { bpf_sk_release(sk); return 0; }
  80. * 7: bpf_sk_release(sk);
  81. * 8: snd_cwnd = tp->snd_cwnd; // verifier will complain
  82. *
  83. * After bpf_sk_release(sk) at line 7, both "fullsock" ptr and
  84. * "tp" ptr should be invalidated also. In order to do that,
  85. * the reg holding "fullsock" and "sk" need to remember
  86. * the original refcounted ptr id (i.e. sk_reg->id) in ref_obj_id
  87. * such that the verifier can reset all regs which have
  88. * ref_obj_id matching the sk_reg->id.
  89. *
  90. * sk_reg->ref_obj_id is set to sk_reg->id at line 1.
  91. * sk_reg->id will stay as NULL-marking purpose only.
  92. * After NULL-marking is done, sk_reg->id can be reset to 0.
  93. *
  94. * After "fullsock = bpf_sk_fullsock(sk);" at line 3,
  95. * fullsock_reg->ref_obj_id is set to sk_reg->ref_obj_id.
  96. *
  97. * After "tp = bpf_tcp_sock(fullsock);" at line 5,
  98. * tp_reg->ref_obj_id is set to fullsock_reg->ref_obj_id
  99. * which is the same as sk_reg->ref_obj_id.
  100. *
  101. * From the verifier perspective, if sk, fullsock and tp
  102. * are not NULL, they are the same ptr with different
  103. * reg->type. In particular, bpf_sk_release(tp) is also
  104. * allowed and has the same effect as bpf_sk_release(sk).
  105. */
  106. u32 ref_obj_id;
  107. /* For scalar types (SCALAR_VALUE), this represents our knowledge of
  108. * the actual value.
  109. * For pointer types, this represents the variable part of the offset
  110. * from the pointed-to object, and is shared with all bpf_reg_states
  111. * with the same id as us.
  112. */
  113. struct tnum var_off;
  114. /* Used to determine if any memory access using this register will
  115. * result in a bad access.
  116. * These refer to the same value as var_off, not necessarily the actual
  117. * contents of the register.
  118. */
  119. s64 smin_value; /* minimum possible (s64)value */
  120. s64 smax_value; /* maximum possible (s64)value */
  121. u64 umin_value; /* minimum possible (u64)value */
  122. u64 umax_value; /* maximum possible (u64)value */
  123. s32 s32_min_value; /* minimum possible (s32)value */
  124. s32 s32_max_value; /* maximum possible (s32)value */
  125. u32 u32_min_value; /* minimum possible (u32)value */
  126. u32 u32_max_value; /* maximum possible (u32)value */
  127. /* parentage chain for liveness checking */
  128. struct bpf_reg_state *parent;
  129. /* Inside the callee two registers can be both PTR_TO_STACK like
  130. * R1=fp-8 and R2=fp-8, but one of them points to this function stack
  131. * while another to the caller's stack. To differentiate them 'frameno'
  132. * is used which is an index in bpf_verifier_state->frame[] array
  133. * pointing to bpf_func_state.
  134. */
  135. u32 frameno;
  136. /* Tracks subreg definition. The stored value is the insn_idx of the
  137. * writing insn. This is safe because subreg_def is used before any insn
  138. * patching which only happens after main verification finished.
  139. */
  140. s32 subreg_def;
  141. enum bpf_reg_liveness live;
  142. /* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */
  143. bool precise;
  144. };
  145. enum bpf_stack_slot_type {
  146. STACK_INVALID, /* nothing was stored in this stack slot */
  147. STACK_SPILL, /* register spilled into stack */
  148. STACK_MISC, /* BPF program wrote some data into this slot */
  149. STACK_ZERO, /* BPF program wrote constant zero */
  150. };
  151. #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */
  152. struct bpf_stack_state {
  153. struct bpf_reg_state spilled_ptr;
  154. u8 slot_type[BPF_REG_SIZE];
  155. };
  156. struct bpf_reference_state {
  157. /* Track each reference created with a unique id, even if the same
  158. * instruction creates the reference multiple times (eg, via CALL).
  159. */
  160. int id;
  161. /* Instruction where the allocation of this reference occurred. This
  162. * is used purely to inform the user of a reference leak.
  163. */
  164. int insn_idx;
  165. };
  166. /* state of the program:
  167. * type of all registers and stack info
  168. */
  169. struct bpf_func_state {
  170. struct bpf_reg_state regs[MAX_BPF_REG];
  171. /* index of call instruction that called into this func */
  172. int callsite;
  173. /* stack frame number of this function state from pov of
  174. * enclosing bpf_verifier_state.
  175. * 0 = main function, 1 = first callee.
  176. */
  177. u32 frameno;
  178. /* subprog number == index within subprog_info
  179. * zero == main subprog
  180. */
  181. u32 subprogno;
  182. /* The following fields should be last. See copy_func_state() */
  183. int acquired_refs;
  184. struct bpf_reference_state *refs;
  185. int allocated_stack;
  186. struct bpf_stack_state *stack;
  187. };
  188. struct bpf_idx_pair {
  189. u32 prev_idx;
  190. u32 idx;
  191. };
  192. struct bpf_id_pair {
  193. u32 old;
  194. u32 cur;
  195. };
  196. /* Maximum number of register states that can exist at once */
  197. #define BPF_ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
  198. #define MAX_CALL_FRAMES 8
  199. struct bpf_verifier_state {
  200. /* call stack tracking */
  201. struct bpf_func_state *frame[MAX_CALL_FRAMES];
  202. struct bpf_verifier_state *parent;
  203. /*
  204. * 'branches' field is the number of branches left to explore:
  205. * 0 - all possible paths from this state reached bpf_exit or
  206. * were safely pruned
  207. * 1 - at least one path is being explored.
  208. * This state hasn't reached bpf_exit
  209. * 2 - at least two paths are being explored.
  210. * This state is an immediate parent of two children.
  211. * One is fallthrough branch with branches==1 and another
  212. * state is pushed into stack (to be explored later) also with
  213. * branches==1. The parent of this state has branches==1.
  214. * The verifier state tree connected via 'parent' pointer looks like:
  215. * 1
  216. * 1
  217. * 2 -> 1 (first 'if' pushed into stack)
  218. * 1
  219. * 2 -> 1 (second 'if' pushed into stack)
  220. * 1
  221. * 1
  222. * 1 bpf_exit.
  223. *
  224. * Once do_check() reaches bpf_exit, it calls update_branch_counts()
  225. * and the verifier state tree will look:
  226. * 1
  227. * 1
  228. * 2 -> 1 (first 'if' pushed into stack)
  229. * 1
  230. * 1 -> 1 (second 'if' pushed into stack)
  231. * 0
  232. * 0
  233. * 0 bpf_exit.
  234. * After pop_stack() the do_check() will resume at second 'if'.
  235. *
  236. * If is_state_visited() sees a state with branches > 0 it means
  237. * there is a loop. If such state is exactly equal to the current state
  238. * it's an infinite loop. Note states_equal() checks for states
  239. * equvalency, so two states being 'states_equal' does not mean
  240. * infinite loop. The exact comparison is provided by
  241. * states_maybe_looping() function. It's a stronger pre-check and
  242. * much faster than states_equal().
  243. *
  244. * This algorithm may not find all possible infinite loops or
  245. * loop iteration count may be too high.
  246. * In such cases BPF_COMPLEXITY_LIMIT_INSNS limit kicks in.
  247. */
  248. u32 branches;
  249. u32 insn_idx;
  250. u32 curframe;
  251. u32 active_spin_lock;
  252. bool speculative;
  253. /* first and last insn idx of this verifier state */
  254. u32 first_insn_idx;
  255. u32 last_insn_idx;
  256. /* jmp history recorded from first to last.
  257. * backtracking is using it to go from last to first.
  258. * For most states jmp_history_cnt is [0-3].
  259. * For loops can go up to ~40.
  260. */
  261. struct bpf_idx_pair *jmp_history;
  262. u32 jmp_history_cnt;
  263. };
  264. #define bpf_get_spilled_reg(slot, frame) \
  265. (((slot < frame->allocated_stack / BPF_REG_SIZE) && \
  266. (frame->stack[slot].slot_type[0] == STACK_SPILL)) \
  267. ? &frame->stack[slot].spilled_ptr : NULL)
  268. /* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */
  269. #define bpf_for_each_spilled_reg(iter, frame, reg) \
  270. for (iter = 0, reg = bpf_get_spilled_reg(iter, frame); \
  271. iter < frame->allocated_stack / BPF_REG_SIZE; \
  272. iter++, reg = bpf_get_spilled_reg(iter, frame))
  273. /* linked list of verifier states used to prune search */
  274. struct bpf_verifier_state_list {
  275. struct bpf_verifier_state state;
  276. struct bpf_verifier_state_list *next;
  277. int miss_cnt, hit_cnt;
  278. };
  279. /* Possible states for alu_state member. */
  280. #define BPF_ALU_SANITIZE_SRC (1U << 0)
  281. #define BPF_ALU_SANITIZE_DST (1U << 1)
  282. #define BPF_ALU_NEG_VALUE (1U << 2)
  283. #define BPF_ALU_NON_POINTER (1U << 3)
  284. #define BPF_ALU_IMMEDIATE (1U << 4)
  285. #define BPF_ALU_SANITIZE (BPF_ALU_SANITIZE_SRC | \
  286. BPF_ALU_SANITIZE_DST)
  287. struct bpf_insn_aux_data {
  288. union {
  289. enum bpf_reg_type ptr_type; /* pointer type for load/store insns */
  290. unsigned long map_ptr_state; /* pointer/poison value for maps */
  291. s32 call_imm; /* saved imm field of call insn */
  292. u32 alu_limit; /* limit for add/sub register with pointer */
  293. struct {
  294. u32 map_index; /* index into used_maps[] */
  295. u32 map_off; /* offset from value base address */
  296. };
  297. struct {
  298. enum bpf_reg_type reg_type; /* type of pseudo_btf_id */
  299. union {
  300. u32 btf_id; /* btf_id for struct typed var */
  301. u32 mem_size; /* mem_size for non-struct typed var */
  302. };
  303. } btf_var;
  304. };
  305. u64 map_key_state; /* constant (32 bit) key tracking for maps */
  306. int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
  307. u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
  308. bool sanitize_stack_spill; /* subject to Spectre v4 sanitation */
  309. bool zext_dst; /* this insn zero extends dst reg */
  310. u8 alu_state; /* used in combination with alu_limit */
  311. /* below fields are initialized once */
  312. unsigned int orig_idx; /* original instruction index */
  313. bool prune_point;
  314. };
  315. #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
  316. #define BPF_VERIFIER_TMP_LOG_SIZE 1024
  317. struct bpf_verifier_log {
  318. u32 level;
  319. char kbuf[BPF_VERIFIER_TMP_LOG_SIZE];
  320. char __user *ubuf;
  321. u32 len_used;
  322. u32 len_total;
  323. };
  324. static inline bool bpf_verifier_log_full(const struct bpf_verifier_log *log)
  325. {
  326. return log->len_used >= log->len_total - 1;
  327. }
  328. #define BPF_LOG_LEVEL1 1
  329. #define BPF_LOG_LEVEL2 2
  330. #define BPF_LOG_STATS 4
  331. #define BPF_LOG_LEVEL (BPF_LOG_LEVEL1 | BPF_LOG_LEVEL2)
  332. #define BPF_LOG_MASK (BPF_LOG_LEVEL | BPF_LOG_STATS)
  333. #define BPF_LOG_KERNEL (BPF_LOG_MASK + 1) /* kernel internal flag */
  334. static inline bool bpf_verifier_log_needed(const struct bpf_verifier_log *log)
  335. {
  336. return log &&
  337. ((log->level && log->ubuf && !bpf_verifier_log_full(log)) ||
  338. log->level == BPF_LOG_KERNEL);
  339. }
  340. static inline bool
  341. bpf_verifier_log_attr_valid(const struct bpf_verifier_log *log)
  342. {
  343. return log->len_total >= 128 && log->len_total <= UINT_MAX >> 2 &&
  344. log->level && log->ubuf && !(log->level & ~BPF_LOG_MASK);
  345. }
  346. #define BPF_MAX_SUBPROGS 256
  347. struct bpf_subprog_info {
  348. /* 'start' has to be the first field otherwise find_subprog() won't work */
  349. u32 start; /* insn idx of function entry point */
  350. u32 linfo_idx; /* The idx to the main_prog->aux->linfo */
  351. u16 stack_depth; /* max. stack depth used by this function */
  352. bool has_tail_call;
  353. bool tail_call_reachable;
  354. bool has_ld_abs;
  355. ANDROID_KABI_RESERVE(1);
  356. };
  357. /* single container for all structs
  358. * one verifier_env per bpf_check() call
  359. */
  360. struct bpf_verifier_env {
  361. u32 insn_idx;
  362. u32 prev_insn_idx;
  363. struct bpf_prog *prog; /* eBPF program being verified */
  364. const struct bpf_verifier_ops *ops;
  365. struct bpf_verifier_stack_elem *head; /* stack of verifier states to be processed */
  366. int stack_size; /* number of states to be processed */
  367. bool strict_alignment; /* perform strict pointer alignment checks */
  368. bool test_state_freq; /* test verifier with different pruning frequency */
  369. struct bpf_verifier_state *cur_state; /* current verifier state */
  370. struct bpf_verifier_state_list **explored_states; /* search pruning optimization */
  371. struct bpf_verifier_state_list *free_list;
  372. struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
  373. u32 used_map_cnt; /* number of used maps */
  374. u32 id_gen; /* used to generate unique reg IDs */
  375. bool explore_alu_limits;
  376. bool allow_ptr_leaks;
  377. bool allow_uninit_stack;
  378. bool allow_ptr_to_map_access;
  379. bool bpf_capable;
  380. bool bypass_spec_v1;
  381. bool bypass_spec_v4;
  382. bool seen_direct_write;
  383. struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
  384. const struct bpf_line_info *prev_linfo;
  385. struct bpf_verifier_log log;
  386. struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 1];
  387. struct bpf_id_pair idmap_scratch[BPF_ID_MAP_SIZE];
  388. struct {
  389. int *insn_state;
  390. int *insn_stack;
  391. int cur_stack;
  392. } cfg;
  393. u32 pass_cnt; /* number of times do_check() was called */
  394. u32 subprog_cnt;
  395. /* number of instructions analyzed by the verifier */
  396. u32 prev_insn_processed, insn_processed;
  397. /* number of jmps, calls, exits analyzed so far */
  398. u32 prev_jmps_processed, jmps_processed;
  399. /* total verification time */
  400. u64 verification_time;
  401. /* maximum number of verifier states kept in 'branching' instructions */
  402. u32 max_states_per_insn;
  403. /* total number of allocated verifier states */
  404. u32 total_states;
  405. /* some states are freed during program analysis.
  406. * this is peak number of states. this number dominates kernel
  407. * memory consumption during verification
  408. */
  409. u32 peak_states;
  410. /* longest register parentage chain walked for liveness marking */
  411. u32 longest_mark_read_walk;
  412. ANDROID_KABI_RESERVE(1);
  413. ANDROID_KABI_RESERVE(2);
  414. };
  415. __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log,
  416. const char *fmt, va_list args);
  417. __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
  418. const char *fmt, ...);
  419. __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
  420. const char *fmt, ...);
  421. static inline struct bpf_func_state *cur_func(struct bpf_verifier_env *env)
  422. {
  423. struct bpf_verifier_state *cur = env->cur_state;
  424. return cur->frame[cur->curframe];
  425. }
  426. static inline struct bpf_reg_state *cur_regs(struct bpf_verifier_env *env)
  427. {
  428. return cur_func(env)->regs;
  429. }
  430. int bpf_prog_offload_verifier_prep(struct bpf_prog *prog);
  431. int bpf_prog_offload_verify_insn(struct bpf_verifier_env *env,
  432. int insn_idx, int prev_insn_idx);
  433. int bpf_prog_offload_finalize(struct bpf_verifier_env *env);
  434. void
  435. bpf_prog_offload_replace_insn(struct bpf_verifier_env *env, u32 off,
  436. struct bpf_insn *insn);
  437. void
  438. bpf_prog_offload_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt);
  439. int check_ctx_reg(struct bpf_verifier_env *env,
  440. const struct bpf_reg_state *reg, int regno);
  441. /* this lives here instead of in bpf.h because it needs to dereference tgt_prog */
  442. static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog,
  443. u32 btf_id)
  444. {
  445. return tgt_prog ? (((u64)tgt_prog->aux->id) << 32 | btf_id) : btf_id;
  446. }
  447. int bpf_check_attach_target(struct bpf_verifier_log *log,
  448. const struct bpf_prog *prog,
  449. const struct bpf_prog *tgt_prog,
  450. u32 btf_id,
  451. struct bpf_attach_target_info *tgt_info);
  452. #endif /* _LINUX_BPF_VERIFIER_H */