Branch data Line data Source code
1 : : /* SPDX-License-Identifier: GPL-2.0-only */
2 : : /*
3 : : * Copyright (c) 2023 Meta Platforms, Inc. and affiliates.
4 : : */
5 : :
6 : : #pragma once
7 : :
8 : : #include <stddef.h>
9 : : #include <stdint.h>
10 : :
11 : : #include <bpfilter/chain.h>
12 : : #include <bpfilter/core/list.h>
13 : : #include <bpfilter/core/vector.h>
14 : : #include <bpfilter/dump.h>
15 : : #include <bpfilter/elfstub.h>
16 : : #include <bpfilter/flavor.h>
17 : : #include <bpfilter/helper.h>
18 : : #include <bpfilter/pack.h>
19 : :
20 : : #include "cgen/fixup.h"
21 : : #include "cgen/printer.h"
22 : : #include "cgen/runtime.h"
23 : : #include "filter.h"
24 : :
25 : : /**
26 : : * @file codegen.h
27 : : *
28 : : * `bf_codegen` is a temporary bytecode generation and loading context. It
29 : : * owns bytecode, fixups, and generation buffers. It borrows its read-only
30 : : * chain and mutable handle, which must outlive the context.
31 : : *
32 : : * **Workflow**
33 : : *
34 : : * The program is composed of different steps:
35 : : * 1. Initialize the generic context
36 : : * 2. Preprocess the packet's headers: gather information about the packet's
37 : : * size, the protocols available, the input interface...
38 : : * 3. Execute the filtering rules: execute all the rules defined in the program
39 : : * sequentially. If a rule matches the packet, apply its verdict and return.
40 : : * 4. Apply the policy if no rule matched: if no rule matched the packet, return
41 : : * the chain's policy (default action).
42 : : *
43 : : * **Memory layout**
44 : : *
45 : : * The program will use the BPF registers to following way:
46 : : * - @c r0 : return value
47 : : * - @c r1 to @c r5 (included): general purpose registers
48 : : * - @c r6 : address of the header currently filtered on
49 : : * - @c r7 : L3 protocol ID
50 : : * - @c r8 : L4 protocol ID
51 : : * - @c r9 : unused
52 : : * - @c r10 : frame pointer
53 : : *
54 : : * This convention is followed throughout the project and must be followed all
55 : : * the time to prevent incompatibilities. Debugging this kind of issues is not
56 : : * fun, so stick to it.
57 : : *
58 : : * @warning L3 and L4 protocol IDs **must** be stored in registers, no on the
59 : : * stack, as older verifier aren't able to keep track of scalar values located
60 : : * on the stack. This means the verification will fail because the verifier
61 : : * can't verify branches properly.
62 : : *
63 : : * `bf_runtime` is used to represent the layout of the first stack frame in the
64 : : * program. It is filled during preprocessing and contains data required for
65 : : * packet filtering.
66 : : *
67 : : * **About preprocessing**
68 : : *
69 : : * The packets are preprocessed according to the program type (i.e. BPF flavor).
70 : : * Each flavor needs to perform the following steps during preprocessing:
71 : : * - Store the packet size and the input interface index into the runtime context
72 : : * - Create a BPF dynamic pointer for the packet
73 : : * - Preprocess the L2, L3, and L4 headers
74 : : *
75 : : * The header's preprocessing is required to discover the protocols used in the
76 : : * packet: processing L2 will provide us with information about L3, and so on. The
77 : : * logic used to process layer X is responsible for discovering layer X+1: the L2
78 : : * header preprocessing logic will discover the L3 protocol ID. When processing
79 : : * layer X, if the protocol is not supported, the protocol ID is reset to 0 (so
80 : : * we won't execute the rules for this layer) and subsequent layers are not
81 : : * processed (because we can't discover their protocol).
82 : : *
83 : : * For example, assuming IPv6 and TCP are the only supported protocols:
84 : : * - L2 processing: discover the packet's ethertype (IPv6), and store it into
85 : : * @c r7 .
86 : : * - L3 processing: the protocol ID in @c r7 is supported (IPv6), so a slice is
87 : : * created, and the L4 protocol ID is read from the IPV6 header into @c r8 .
88 : : * - L4 processing: the protocol ID in @c r8 is supported (TCP), so a slice
89 : : * is created.
90 : : * - The program can now start executing the rules.
91 : : *
92 : : * However, assuming only IPv6 and UDP are supported:
93 : : * - L2 processing: discover the packet's ethertype (IPv6), and store it into
94 : : * @c r7 .
95 : : * - L3 processing: the protocol ID in @c r7 is supported (IPv6), so a slice is
96 : : * created, and the L4 protocol ID is read from the IPV6 header into @c r8 .
97 : : * - L4 processing: the protocol ID in @c r8 is no supported (TCP), @c r8 is
98 : : * set to 0 and we stop processing this layer.
99 : : * - The program can now start executing the rules. No layer 4 rule will be
100 : : * executed as @c r8 won't match any protocol ID.
101 : : */
102 : :
103 : : #define EMIT(program, x) \
104 : : ({ \
105 : : int __r = bf_codegen_emit((program), (x)); \
106 : : if (__r < 0) \
107 : : return __r; \
108 : : })
109 : :
110 : : #define EMIT_KFUNC_CALL(program, function) \
111 : : ({ \
112 : : int __r = bf_codegen_emit_kfunc_call((program), (function)); \
113 : : if (__r < 0) \
114 : : return __r; \
115 : : })
116 : :
117 : : #define EMIT_FIXUP(program, type, insn) \
118 : : ({ \
119 : : int __r = bf_codegen_emit_fixup((program), (type), (insn), NULL); \
120 : : if (__r < 0) \
121 : : return __r; \
122 : : })
123 : :
124 : : #define EMIT_FIXUP_ELFSTUB(program, elfstub_id) \
125 : : ({ \
126 : : int __r = bf_codegen_emit_fixup_elfstub((program), (elfstub_id)); \
127 : : if (__r < 0) \
128 : : return __r; \
129 : : })
130 : :
131 : : #define EMIT_FIXUP_JMP_NEXT_RULE(program, insn) \
132 : : ({ \
133 : : int __r = bf_codegen_emit_fixup( \
134 : : (program), BF_FIXUP_TYPE_JMP_NEXT_RULE, (insn), NULL); \
135 : : if (__r < 0) \
136 : : return __r; \
137 : : })
138 : :
139 : : #define EMIT_LOAD_COUNTERS_FD_FIXUP(program, reg) \
140 : : ({ \
141 : : const struct bpf_insn ld_insn[2] = {BPF_LD_MAP_FD(reg, 0)}; \
142 : : int __r = bf_codegen_emit_fixup( \
143 : : (program), BF_FIXUP_TYPE_COUNTERS_MAP_FD, ld_insn[0], NULL); \
144 : : if (__r < 0) \
145 : : return __r; \
146 : : __r = bf_codegen_emit((program), ld_insn[1]); \
147 : : if (__r < 0) \
148 : : return __r; \
149 : : })
150 : :
151 : : #define EMIT_LOAD_LOG_FD_FIXUP(program, reg) \
152 : : ({ \
153 : : const struct bpf_insn ld_insn[2] = {BPF_LD_MAP_FD(reg, 0)}; \
154 : : int __r = bf_codegen_emit_fixup((program), BF_FIXUP_TYPE_LOG_MAP_FD, \
155 : : ld_insn[0], NULL); \
156 : : if (__r < 0) \
157 : : return __r; \
158 : : __r = bf_codegen_emit((program), ld_insn[1]); \
159 : : if (__r < 0) \
160 : : return __r; \
161 : : })
162 : :
163 : : #define EMIT_LOAD_STATE_FD_FIXUP(program, reg) \
164 : : ({ \
165 : : const struct bpf_insn ld_insn[2] = {BPF_LD_MAP_FD(reg, 0)}; \
166 : : int __r = bf_codegen_emit_fixup((program), BF_FIXUP_TYPE_STATE_MAP_FD, \
167 : : ld_insn[0], NULL); \
168 : : if (__r < 0) \
169 : : return __r; \
170 : : __r = bf_codegen_emit((program), ld_insn[1]); \
171 : : if (__r < 0) \
172 : : return __r; \
173 : : })
174 : :
175 : : /**
176 : : * Load a specific set's file descriptor.
177 : : *
178 : : * @note Similarly to every @c EMIT_* macro, it must be called from a function
179 : : * returning an @c int , if the call fails, the macro will return a negative
180 : : * errno value.
181 : : *
182 : : * @param program Program to generate the bytecode for. Can't be NULL.
183 : : * @param reg Register to store the set file descriptor in.
184 : : * @param set Non-owning pointer to the referenced `bf_set`. The set must
185 : : * live at least until `bf_codegen_load()` returns.
186 : : */
187 : : #define EMIT_LOAD_SET_FD_FIXUP(program, reg, set) \
188 : : ({ \
189 : : union bf_fixup_attr __attr; \
190 : : memset(&__attr, 0, sizeof(__attr)); \
191 : : __attr.set_ptr = (set); \
192 : : const struct bpf_insn ld_insn[2] = {BPF_LD_MAP_FD(reg, 0)}; \
193 : : int __r = bf_codegen_emit_fixup((program), BF_FIXUP_TYPE_SET_MAP_FD, \
194 : : ld_insn[0], &__attr); \
195 : : if (__r < 0) \
196 : : return __r; \
197 : : __r = bf_codegen_emit((program), ld_insn[1]); \
198 : : if (__r < 0) \
199 : : return __r; \
200 : : })
201 : :
202 : : struct bf_chain;
203 : : struct bf_counter;
204 : : struct bf_hookopts;
205 : : struct bf_handle;
206 : : struct bf_set;
207 : : struct bf_set_group;
208 : :
209 : : struct bf_codegen
210 : : {
211 : : enum bf_flavor flavor;
212 : :
213 : : /// Log messages printer
214 : : struct bf_printer *printer;
215 : :
216 : : /** Borrowed handle populated during loading. The caller owns the handle
217 : : * and must keep it alive until this context is freed. */
218 : : struct bf_handle *handle;
219 : :
220 : : /* Bytecode */
221 : : uint32_t elfstubs_location[_BF_ELFSTUB_MAX];
222 : : bf_vector img;
223 : : bf_list fixups;
224 : :
225 : : /** Non-empty sets from `runtime.chain->sets`, partitioned into groups
226 : : * that each back a single BPF map. Hash-keyed sets sharing a key
227 : : * format are placed in the same group; each LPM trie set sits in a
228 : : * group of its own. A set's position within a group is its bit index
229 : : * in the map's bitmask value. Not serialized. */
230 : : bf_list set_groups;
231 : :
232 : : /** Runtime data used to interact with the program and cache information.
233 : : * This data is not serialized. */
234 : : struct
235 : : {
236 : : /** Hook-specific ops to use to generate the program. */
237 : : const struct bf_flavor_ops *ops;
238 : :
239 : : /** Borrowed, read-only chain. The caller must keep the chain and its
240 : : * contained objects alive until this context is freed. */
241 : : const struct bf_chain *chain;
242 : : } runtime;
243 : : };
244 : :
245 : : #define _free_bf_codegen_ __attribute__((__cleanup__(bf_codegen_free)))
246 : :
247 : : /**
248 : : * @brief Allocate and initialize a new `bf_codegen` object.
249 : : *
250 : : * The chain's rules are validated, and their derived state is updated in
251 : : * `chain` (see `bf_chain_validate_rules()`). The context then reads the chain
252 : : * without modifying it.
253 : : *
254 : : * @todo Compute the derived state in the context instead of updating the
255 : : * caller's chain.
256 : : *
257 : : * @param program `bf_codegen` object to allocate and initialize. Can't be NULL.
258 : : * @param chain Borrowed chain. Must outlive the context. Can't be NULL.
259 : : * @param handle Borrowed handle populated during loading. Must outlive the
260 : : * context. Can't be NULL.
261 : : * @return 0 on success, or a negative error value on failure.
262 : : */
263 : : int bf_codegen_new(struct bf_codegen **program, struct bf_chain *chain,
264 : : struct bf_handle *handle);
265 : :
266 : : void bf_codegen_free(struct bf_codegen **program);
267 : :
268 : : void bf_codegen_dump(const struct bf_codegen *program, prefix_t *prefix);
269 : :
270 : : static inline int bf_codegen_emit(struct bf_codegen *program,
271 : : struct bpf_insn insn)
272 : : {
273 : : assert(program);
274 : :
275 : 349415 : return bf_vector_add(&program->img, &insn);
276 : : }
277 : :
278 : : int bf_codegen_emit_kfunc_call(struct bf_codegen *program, const char *name);
279 : : int bf_codegen_emit_fixup(struct bf_codegen *program, enum bf_fixup_type type,
280 : : struct bpf_insn insn,
281 : : const union bf_fixup_attr *attr);
282 : : int bf_codegen_emit_fixup_elfstub(struct bf_codegen *program,
283 : : enum bf_elfstub_id id);
284 : : int bf_codegen_generate(struct bf_codegen *program);
285 : :
286 : : /**
287 : : * @brief Get the bit position of a set within its group.
288 : : *
289 : : * Hash-keyed sets sharing a key format are grouped together and share a
290 : : * single BPF map; LPM trie sets each live in a group of size 1. Either
291 : : * way, each set's elements are stored in the group's map with a bitmask
292 : : * value where one bit identifies which set owns the element. This
293 : : * function returns that bit's position for `set` within its group (always
294 : : * 0 for LPM trie sets).
295 : : *
296 : : * @param program Program whose groups have been built. Can't be NULL.
297 : : * @param set Set to locate in the program's groups. Can't be NULL.
298 : : * @param bit_index Output: position of `set` within its group's bit layout.
299 : : * Can't be NULL.
300 : : * @return 0 on success, `-ENOENT` if `set` is not part of any group (for
301 : : * example, because it is empty).
302 : : */
303 : : int bf_codegen_set_bit_index(const struct bf_codegen *program,
304 : : const struct bf_set *set, size_t *bit_index);
305 : :
306 : : /**
307 : : * Load the BPF program into the kernel.
308 : : *
309 : : * Prior to loading the BPF program, multiple BPF maps are created to store
310 : : * the counters, the debug strings, and the sets. If `prog->handle` already has
311 : : * a log map, it is reused instead of creating a new one. If the program can't
312 : : * be loaded, the maps created by this function are destroyed, and a reused log
313 : : * map is only closed.
314 : : *
315 : : * Once the loading succeeds, the program and the maps are pinned to the
316 : : * filesystem. If the BPF objects can't be pinned, the program is unloaded and
317 : : * the maps destroyed.
318 : : *
319 : : * @param prog Program to load into the kernel. Can't be NULL and must contain
320 : : * instructions.
321 : : * @return 0 on success, or negative errno value on failure.
322 : : */
323 : : int bf_codegen_load(struct bf_codegen *prog);
324 : :
325 : : int bf_codegen_get_counter(const struct bf_codegen *program,
326 : : uint32_t counter_idx, struct bf_counter *counter);
327 : : int bf_codegen_set_counters(struct bf_codegen *program,
328 : : const struct bf_counter *counters);
329 : :
330 : : size_t bf_codegen_chain_counter_idx(const struct bf_codegen *program);
331 : : size_t bf_codegen_error_counter_idx(const struct bf_codegen *program);
332 : : size_t bf_codegen_parser_drop_counter_idx(const struct bf_codegen *program);
|