Documentation: ABI: usb: chipidea: Update Li Jun's e-mail
[linux-2.6-microblaze.git] / Documentation / networking / filter.rst
1 .. SPDX-License-Identifier: GPL-2.0
2
3 =======================================================
4 Linux Socket Filtering aka Berkeley Packet Filter (BPF)
5 =======================================================
6
7 Introduction
8 ------------
9
10 Linux Socket Filtering (LSF) is derived from the Berkeley Packet Filter.
11 Though there are some distinct differences between the BSD and Linux
12 Kernel filtering, but when we speak of BPF or LSF in Linux context, we
13 mean the very same mechanism of filtering in the Linux kernel.
14
15 BPF allows a user-space program to attach a filter onto any socket and
16 allow or disallow certain types of data to come through the socket. LSF
17 follows exactly the same filter code structure as BSD's BPF, so referring
18 to the BSD bpf.4 manpage is very helpful in creating filters.
19
20 On Linux, BPF is much simpler than on BSD. One does not have to worry
21 about devices or anything like that. You simply create your filter code,
22 send it to the kernel via the SO_ATTACH_FILTER option and if your filter
23 code passes the kernel check on it, you then immediately begin filtering
24 data on that socket.
25
26 You can also detach filters from your socket via the SO_DETACH_FILTER
27 option. This will probably not be used much since when you close a socket
28 that has a filter on it the filter is automagically removed. The other
29 less common case may be adding a different filter on the same socket where
30 you had another filter that is still running: the kernel takes care of
31 removing the old one and placing your new one in its place, assuming your
32 filter has passed the checks, otherwise if it fails the old filter will
33 remain on that socket.
34
35 SO_LOCK_FILTER option allows to lock the filter attached to a socket. Once
36 set, a filter cannot be removed or changed. This allows one process to
37 setup a socket, attach a filter, lock it then drop privileges and be
38 assured that the filter will be kept until the socket is closed.
39
40 The biggest user of this construct might be libpcap. Issuing a high-level
41 filter command like `tcpdump -i em1 port 22` passes through the libpcap
42 internal compiler that generates a structure that can eventually be loaded
43 via SO_ATTACH_FILTER to the kernel. `tcpdump -i em1 port 22 -ddd`
44 displays what is being placed into this structure.
45
46 Although we were only speaking about sockets here, BPF in Linux is used
47 in many more places. There's xt_bpf for netfilter, cls_bpf in the kernel
48 qdisc layer, SECCOMP-BPF (SECure COMPuting [1]_), and lots of other places
49 such as team driver, PTP code, etc where BPF is being used.
50
51 .. [1] Documentation/userspace-api/seccomp_filter.rst
52
53 Original BPF paper:
54
55 Steven McCanne and Van Jacobson. 1993. The BSD packet filter: a new
56 architecture for user-level packet capture. In Proceedings of the
57 USENIX Winter 1993 Conference Proceedings on USENIX Winter 1993
58 Conference Proceedings (USENIX'93). USENIX Association, Berkeley,
59 CA, USA, 2-2. [http://www.tcpdump.org/papers/bpf-usenix93.pdf]
60
61 Structure
62 ---------
63
64 User space applications include <linux/filter.h> which contains the
65 following relevant structures::
66
67         struct sock_filter {    /* Filter block */
68                 __u16   code;   /* Actual filter code */
69                 __u8    jt;     /* Jump true */
70                 __u8    jf;     /* Jump false */
71                 __u32   k;      /* Generic multiuse field */
72         };
73
74 Such a structure is assembled as an array of 4-tuples, that contains
75 a code, jt, jf and k value. jt and jf are jump offsets and k a generic
76 value to be used for a provided code::
77
78         struct sock_fprog {                     /* Required for SO_ATTACH_FILTER. */
79                 unsigned short             len; /* Number of filter blocks */
80                 struct sock_filter __user *filter;
81         };
82
83 For socket filtering, a pointer to this structure (as shown in
84 follow-up example) is being passed to the kernel through setsockopt(2).
85
86 Example
87 -------
88
89 ::
90
91     #include <sys/socket.h>
92     #include <sys/types.h>
93     #include <arpa/inet.h>
94     #include <linux/if_ether.h>
95     /* ... */
96
97     /* From the example above: tcpdump -i em1 port 22 -dd */
98     struct sock_filter code[] = {
99             { 0x28,  0,  0, 0x0000000c },
100             { 0x15,  0,  8, 0x000086dd },
101             { 0x30,  0,  0, 0x00000014 },
102             { 0x15,  2,  0, 0x00000084 },
103             { 0x15,  1,  0, 0x00000006 },
104             { 0x15,  0, 17, 0x00000011 },
105             { 0x28,  0,  0, 0x00000036 },
106             { 0x15, 14,  0, 0x00000016 },
107             { 0x28,  0,  0, 0x00000038 },
108             { 0x15, 12, 13, 0x00000016 },
109             { 0x15,  0, 12, 0x00000800 },
110             { 0x30,  0,  0, 0x00000017 },
111             { 0x15,  2,  0, 0x00000084 },
112             { 0x15,  1,  0, 0x00000006 },
113             { 0x15,  0,  8, 0x00000011 },
114             { 0x28,  0,  0, 0x00000014 },
115             { 0x45,  6,  0, 0x00001fff },
116             { 0xb1,  0,  0, 0x0000000e },
117             { 0x48,  0,  0, 0x0000000e },
118             { 0x15,  2,  0, 0x00000016 },
119             { 0x48,  0,  0, 0x00000010 },
120             { 0x15,  0,  1, 0x00000016 },
121             { 0x06,  0,  0, 0x0000ffff },
122             { 0x06,  0,  0, 0x00000000 },
123     };
124
125     struct sock_fprog bpf = {
126             .len = ARRAY_SIZE(code),
127             .filter = code,
128     };
129
130     sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
131     if (sock < 0)
132             /* ... bail out ... */
133
134     ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
135     if (ret < 0)
136             /* ... bail out ... */
137
138     /* ... */
139     close(sock);
140
141 The above example code attaches a socket filter for a PF_PACKET socket
142 in order to let all IPv4/IPv6 packets with port 22 pass. The rest will
143 be dropped for this socket.
144
145 The setsockopt(2) call to SO_DETACH_FILTER doesn't need any arguments
146 and SO_LOCK_FILTER for preventing the filter to be detached, takes an
147 integer value with 0 or 1.
148
149 Note that socket filters are not restricted to PF_PACKET sockets only,
150 but can also be used on other socket families.
151
152 Summary of system calls:
153
154  * setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &val, sizeof(val));
155  * setsockopt(sockfd, SOL_SOCKET, SO_DETACH_FILTER, &val, sizeof(val));
156  * setsockopt(sockfd, SOL_SOCKET, SO_LOCK_FILTER,   &val, sizeof(val));
157
158 Normally, most use cases for socket filtering on packet sockets will be
159 covered by libpcap in high-level syntax, so as an application developer
160 you should stick to that. libpcap wraps its own layer around all that.
161
162 Unless i) using/linking to libpcap is not an option, ii) the required BPF
163 filters use Linux extensions that are not supported by libpcap's compiler,
164 iii) a filter might be more complex and not cleanly implementable with
165 libpcap's compiler, or iv) particular filter codes should be optimized
166 differently than libpcap's internal compiler does; then in such cases
167 writing such a filter "by hand" can be of an alternative. For example,
168 xt_bpf and cls_bpf users might have requirements that could result in
169 more complex filter code, or one that cannot be expressed with libpcap
170 (e.g. different return codes for various code paths). Moreover, BPF JIT
171 implementors may wish to manually write test cases and thus need low-level
172 access to BPF code as well.
173
174 BPF engine and instruction set
175 ------------------------------
176
177 Under tools/bpf/ there's a small helper tool called bpf_asm which can
178 be used to write low-level filters for example scenarios mentioned in the
179 previous section. Asm-like syntax mentioned here has been implemented in
180 bpf_asm and will be used for further explanations (instead of dealing with
181 less readable opcodes directly, principles are the same). The syntax is
182 closely modelled after Steven McCanne's and Van Jacobson's BPF paper.
183
184 The BPF architecture consists of the following basic elements:
185
186   =======          ====================================================
187   Element          Description
188   =======          ====================================================
189   A                32 bit wide accumulator
190   X                32 bit wide X register
191   M[]              16 x 32 bit wide misc registers aka "scratch memory
192                    store", addressable from 0 to 15
193   =======          ====================================================
194
195 A program, that is translated by bpf_asm into "opcodes" is an array that
196 consists of the following elements (as already mentioned)::
197
198   op:16, jt:8, jf:8, k:32
199
200 The element op is a 16 bit wide opcode that has a particular instruction
201 encoded. jt and jf are two 8 bit wide jump targets, one for condition
202 "jump if true", the other one "jump if false". Eventually, element k
203 contains a miscellaneous argument that can be interpreted in different
204 ways depending on the given instruction in op.
205
206 The instruction set consists of load, store, branch, alu, miscellaneous
207 and return instructions that are also represented in bpf_asm syntax. This
208 table lists all bpf_asm instructions available resp. what their underlying
209 opcodes as defined in linux/filter.h stand for:
210
211   ===========      ===================  =====================
212   Instruction      Addressing mode      Description
213   ===========      ===================  =====================
214   ld               1, 2, 3, 4, 12       Load word into A
215   ldi              4                    Load word into A
216   ldh              1, 2                 Load half-word into A
217   ldb              1, 2                 Load byte into A
218   ldx              3, 4, 5, 12          Load word into X
219   ldxi             4                    Load word into X
220   ldxb             5                    Load byte into X
221
222   st               3                    Store A into M[]
223   stx              3                    Store X into M[]
224
225   jmp              6                    Jump to label
226   ja               6                    Jump to label
227   jeq              7, 8, 9, 10          Jump on A == <x>
228   jneq             9, 10                Jump on A != <x>
229   jne              9, 10                Jump on A != <x>
230   jlt              9, 10                Jump on A <  <x>
231   jle              9, 10                Jump on A <= <x>
232   jgt              7, 8, 9, 10          Jump on A >  <x>
233   jge              7, 8, 9, 10          Jump on A >= <x>
234   jset             7, 8, 9, 10          Jump on A &  <x>
235
236   add              0, 4                 A + <x>
237   sub              0, 4                 A - <x>
238   mul              0, 4                 A * <x>
239   div              0, 4                 A / <x>
240   mod              0, 4                 A % <x>
241   neg                                   !A
242   and              0, 4                 A & <x>
243   or               0, 4                 A | <x>
244   xor              0, 4                 A ^ <x>
245   lsh              0, 4                 A << <x>
246   rsh              0, 4                 A >> <x>
247
248   tax                                   Copy A into X
249   txa                                   Copy X into A
250
251   ret              4, 11                Return
252   ===========      ===================  =====================
253
254 The next table shows addressing formats from the 2nd column:
255
256   ===============  ===================  ===============================================
257   Addressing mode  Syntax               Description
258   ===============  ===================  ===============================================
259    0               x/%x                 Register X
260    1               [k]                  BHW at byte offset k in the packet
261    2               [x + k]              BHW at the offset X + k in the packet
262    3               M[k]                 Word at offset k in M[]
263    4               #k                   Literal value stored in k
264    5               4*([k]&0xf)          Lower nibble * 4 at byte offset k in the packet
265    6               L                    Jump label L
266    7               #k,Lt,Lf             Jump to Lt if true, otherwise jump to Lf
267    8               x/%x,Lt,Lf           Jump to Lt if true, otherwise jump to Lf
268    9               #k,Lt                Jump to Lt if predicate is true
269   10               x/%x,Lt              Jump to Lt if predicate is true
270   11               a/%a                 Accumulator A
271   12               extension            BPF extension
272   ===============  ===================  ===============================================
273
274 The Linux kernel also has a couple of BPF extensions that are used along
275 with the class of load instructions by "overloading" the k argument with
276 a negative offset + a particular extension offset. The result of such BPF
277 extensions are loaded into A.
278
279 Possible BPF extensions are shown in the following table:
280
281   ===================================   =================================================
282   Extension                             Description
283   ===================================   =================================================
284   len                                   skb->len
285   proto                                 skb->protocol
286   type                                  skb->pkt_type
287   poff                                  Payload start offset
288   ifidx                                 skb->dev->ifindex
289   nla                                   Netlink attribute of type X with offset A
290   nlan                                  Nested Netlink attribute of type X with offset A
291   mark                                  skb->mark
292   queue                                 skb->queue_mapping
293   hatype                                skb->dev->type
294   rxhash                                skb->hash
295   cpu                                   raw_smp_processor_id()
296   vlan_tci                              skb_vlan_tag_get(skb)
297   vlan_avail                            skb_vlan_tag_present(skb)
298   vlan_tpid                             skb->vlan_proto
299   rand                                  prandom_u32()
300   ===================================   =================================================
301
302 These extensions can also be prefixed with '#'.
303 Examples for low-level BPF:
304
305 **ARP packets**::
306
307   ldh [12]
308   jne #0x806, drop
309   ret #-1
310   drop: ret #0
311
312 **IPv4 TCP packets**::
313
314   ldh [12]
315   jne #0x800, drop
316   ldb [23]
317   jneq #6, drop
318   ret #-1
319   drop: ret #0
320
321 **(Accelerated) VLAN w/ id 10**::
322
323   ld vlan_tci
324   jneq #10, drop
325   ret #-1
326   drop: ret #0
327
328 **icmp random packet sampling, 1 in 4**:
329
330   ldh [12]
331   jne #0x800, drop
332   ldb [23]
333   jneq #1, drop
334   # get a random uint32 number
335   ld rand
336   mod #4
337   jneq #1, drop
338   ret #-1
339   drop: ret #0
340
341 **SECCOMP filter example**::
342
343   ld [4]                  /* offsetof(struct seccomp_data, arch) */
344   jne #0xc000003e, bad    /* AUDIT_ARCH_X86_64 */
345   ld [0]                  /* offsetof(struct seccomp_data, nr) */
346   jeq #15, good           /* __NR_rt_sigreturn */
347   jeq #231, good          /* __NR_exit_group */
348   jeq #60, good           /* __NR_exit */
349   jeq #0, good            /* __NR_read */
350   jeq #1, good            /* __NR_write */
351   jeq #5, good            /* __NR_fstat */
352   jeq #9, good            /* __NR_mmap */
353   jeq #14, good           /* __NR_rt_sigprocmask */
354   jeq #13, good           /* __NR_rt_sigaction */
355   jeq #35, good           /* __NR_nanosleep */
356   bad: ret #0             /* SECCOMP_RET_KILL_THREAD */
357   good: ret #0x7fff0000   /* SECCOMP_RET_ALLOW */
358
359 The above example code can be placed into a file (here called "foo"), and
360 then be passed to the bpf_asm tool for generating opcodes, output that xt_bpf
361 and cls_bpf understands and can directly be loaded with. Example with above
362 ARP code::
363
364     $ ./bpf_asm foo
365     4,40 0 0 12,21 0 1 2054,6 0 0 4294967295,6 0 0 0,
366
367 In copy and paste C-like output::
368
369     $ ./bpf_asm -c foo
370     { 0x28,  0,  0, 0x0000000c },
371     { 0x15,  0,  1, 0x00000806 },
372     { 0x06,  0,  0, 0xffffffff },
373     { 0x06,  0,  0, 0000000000 },
374
375 In particular, as usage with xt_bpf or cls_bpf can result in more complex BPF
376 filters that might not be obvious at first, it's good to test filters before
377 attaching to a live system. For that purpose, there's a small tool called
378 bpf_dbg under tools/bpf/ in the kernel source directory. This debugger allows
379 for testing BPF filters against given pcap files, single stepping through the
380 BPF code on the pcap's packets and to do BPF machine register dumps.
381
382 Starting bpf_dbg is trivial and just requires issuing::
383
384     # ./bpf_dbg
385
386 In case input and output do not equal stdin/stdout, bpf_dbg takes an
387 alternative stdin source as a first argument, and an alternative stdout
388 sink as a second one, e.g. `./bpf_dbg test_in.txt test_out.txt`.
389
390 Other than that, a particular libreadline configuration can be set via
391 file "~/.bpf_dbg_init" and the command history is stored in the file
392 "~/.bpf_dbg_history".
393
394 Interaction in bpf_dbg happens through a shell that also has auto-completion
395 support (follow-up example commands starting with '>' denote bpf_dbg shell).
396 The usual workflow would be to ...
397
398 * load bpf 6,40 0 0 12,21 0 3 2048,48 0 0 23,21 0 1 1,6 0 0 65535,6 0 0 0
399   Loads a BPF filter from standard output of bpf_asm, or transformed via
400   e.g. ``tcpdump -iem1 -ddd port 22 | tr '\n' ','``. Note that for JIT
401   debugging (next section), this command creates a temporary socket and
402   loads the BPF code into the kernel. Thus, this will also be useful for
403   JIT developers.
404
405 * load pcap foo.pcap
406
407   Loads standard tcpdump pcap file.
408
409 * run [<n>]
410
411 bpf passes:1 fails:9
412   Runs through all packets from a pcap to account how many passes and fails
413   the filter will generate. A limit of packets to traverse can be given.
414
415 * disassemble::
416
417         l0:     ldh [12]
418         l1:     jeq #0x800, l2, l5
419         l2:     ldb [23]
420         l3:     jeq #0x1, l4, l5
421         l4:     ret #0xffff
422         l5:     ret #0
423
424   Prints out BPF code disassembly.
425
426 * dump::
427
428         /* { op, jt, jf, k }, */
429         { 0x28,  0,  0, 0x0000000c },
430         { 0x15,  0,  3, 0x00000800 },
431         { 0x30,  0,  0, 0x00000017 },
432         { 0x15,  0,  1, 0x00000001 },
433         { 0x06,  0,  0, 0x0000ffff },
434         { 0x06,  0,  0, 0000000000 },
435
436   Prints out C-style BPF code dump.
437
438 * breakpoint 0::
439
440         breakpoint at: l0:      ldh [12]
441
442 * breakpoint 1::
443
444         breakpoint at: l1:      jeq #0x800, l2, l5
445
446   ...
447
448   Sets breakpoints at particular BPF instructions. Issuing a `run` command
449   will walk through the pcap file continuing from the current packet and
450   break when a breakpoint is being hit (another `run` will continue from
451   the currently active breakpoint executing next instructions):
452
453   * run::
454
455         -- register dump --
456         pc:       [0]                       <-- program counter
457         code:     [40] jt[0] jf[0] k[12]    <-- plain BPF code of current instruction
458         curr:     l0:   ldh [12]              <-- disassembly of current instruction
459         A:        [00000000][0]             <-- content of A (hex, decimal)
460         X:        [00000000][0]             <-- content of X (hex, decimal)
461         M[0,15]:  [00000000][0]             <-- folded content of M (hex, decimal)
462         -- packet dump --                   <-- Current packet from pcap (hex)
463         len: 42
464             0: 00 19 cb 55 55 a4 00 14 a4 43 78 69 08 06 00 01
465         16: 08 00 06 04 00 01 00 14 a4 43 78 69 0a 3b 01 26
466         32: 00 00 00 00 00 00 0a 3b 01 01
467         (breakpoint)
468         >
469
470   * breakpoint::
471
472         breakpoints: 0 1
473
474     Prints currently set breakpoints.
475
476 * step [-<n>, +<n>]
477
478   Performs single stepping through the BPF program from the current pc
479   offset. Thus, on each step invocation, above register dump is issued.
480   This can go forwards and backwards in time, a plain `step` will break
481   on the next BPF instruction, thus +1. (No `run` needs to be issued here.)
482
483 * select <n>
484
485   Selects a given packet from the pcap file to continue from. Thus, on
486   the next `run` or `step`, the BPF program is being evaluated against
487   the user pre-selected packet. Numbering starts just as in Wireshark
488   with index 1.
489
490 * quit
491
492   Exits bpf_dbg.
493
494 JIT compiler
495 ------------
496
497 The Linux kernel has a built-in BPF JIT compiler for x86_64, SPARC,
498 PowerPC, ARM, ARM64, MIPS, RISC-V and s390 and can be enabled through
499 CONFIG_BPF_JIT. The JIT compiler is transparently invoked for each
500 attached filter from user space or for internal kernel users if it has
501 been previously enabled by root::
502
503   echo 1 > /proc/sys/net/core/bpf_jit_enable
504
505 For JIT developers, doing audits etc, each compile run can output the generated
506 opcode image into the kernel log via::
507
508   echo 2 > /proc/sys/net/core/bpf_jit_enable
509
510 Example output from dmesg::
511
512     [ 3389.935842] flen=6 proglen=70 pass=3 image=ffffffffa0069c8f
513     [ 3389.935847] JIT code: 00000000: 55 48 89 e5 48 83 ec 60 48 89 5d f8 44 8b 4f 68
514     [ 3389.935849] JIT code: 00000010: 44 2b 4f 6c 4c 8b 87 d8 00 00 00 be 0c 00 00 00
515     [ 3389.935850] JIT code: 00000020: e8 1d 94 ff e0 3d 00 08 00 00 75 16 be 17 00 00
516     [ 3389.935851] JIT code: 00000030: 00 e8 28 94 ff e0 83 f8 01 75 07 b8 ff ff 00 00
517     [ 3389.935852] JIT code: 00000040: eb 02 31 c0 c9 c3
518
519 When CONFIG_BPF_JIT_ALWAYS_ON is enabled, bpf_jit_enable is permanently set to 1 and
520 setting any other value than that will return in failure. This is even the case for
521 setting bpf_jit_enable to 2, since dumping the final JIT image into the kernel log
522 is discouraged and introspection through bpftool (under tools/bpf/bpftool/) is the
523 generally recommended approach instead.
524
525 In the kernel source tree under tools/bpf/, there's bpf_jit_disasm for
526 generating disassembly out of the kernel log's hexdump::
527
528         # ./bpf_jit_disasm
529         70 bytes emitted from JIT compiler (pass:3, flen:6)
530         ffffffffa0069c8f + <x>:
531         0:      push   %rbp
532         1:      mov    %rsp,%rbp
533         4:      sub    $0x60,%rsp
534         8:      mov    %rbx,-0x8(%rbp)
535         c:      mov    0x68(%rdi),%r9d
536         10:     sub    0x6c(%rdi),%r9d
537         14:     mov    0xd8(%rdi),%r8
538         1b:     mov    $0xc,%esi
539         20:     callq  0xffffffffe0ff9442
540         25:     cmp    $0x800,%eax
541         2a:     jne    0x0000000000000042
542         2c:     mov    $0x17,%esi
543         31:     callq  0xffffffffe0ff945e
544         36:     cmp    $0x1,%eax
545         39:     jne    0x0000000000000042
546         3b:     mov    $0xffff,%eax
547         40:     jmp    0x0000000000000044
548         42:     xor    %eax,%eax
549         44:     leaveq
550         45:     retq
551
552         Issuing option `-o` will "annotate" opcodes to resulting assembler
553         instructions, which can be very useful for JIT developers:
554
555         # ./bpf_jit_disasm -o
556         70 bytes emitted from JIT compiler (pass:3, flen:6)
557         ffffffffa0069c8f + <x>:
558         0:      push   %rbp
559                 55
560         1:      mov    %rsp,%rbp
561                 48 89 e5
562         4:      sub    $0x60,%rsp
563                 48 83 ec 60
564         8:      mov    %rbx,-0x8(%rbp)
565                 48 89 5d f8
566         c:      mov    0x68(%rdi),%r9d
567                 44 8b 4f 68
568         10:     sub    0x6c(%rdi),%r9d
569                 44 2b 4f 6c
570         14:     mov    0xd8(%rdi),%r8
571                 4c 8b 87 d8 00 00 00
572         1b:     mov    $0xc,%esi
573                 be 0c 00 00 00
574         20:     callq  0xffffffffe0ff9442
575                 e8 1d 94 ff e0
576         25:     cmp    $0x800,%eax
577                 3d 00 08 00 00
578         2a:     jne    0x0000000000000042
579                 75 16
580         2c:     mov    $0x17,%esi
581                 be 17 00 00 00
582         31:     callq  0xffffffffe0ff945e
583                 e8 28 94 ff e0
584         36:     cmp    $0x1,%eax
585                 83 f8 01
586         39:     jne    0x0000000000000042
587                 75 07
588         3b:     mov    $0xffff,%eax
589                 b8 ff ff 00 00
590         40:     jmp    0x0000000000000044
591                 eb 02
592         42:     xor    %eax,%eax
593                 31 c0
594         44:     leaveq
595                 c9
596         45:     retq
597                 c3
598
599 For BPF JIT developers, bpf_jit_disasm, bpf_asm and bpf_dbg provides a useful
600 toolchain for developing and testing the kernel's JIT compiler.
601
602 BPF kernel internals
603 --------------------
604 Internally, for the kernel interpreter, a different instruction set
605 format with similar underlying principles from BPF described in previous
606 paragraphs is being used. However, the instruction set format is modelled
607 closer to the underlying architecture to mimic native instruction sets, so
608 that a better performance can be achieved (more details later). This new
609 ISA is called 'eBPF' or 'internal BPF' interchangeably. (Note: eBPF which
610 originates from [e]xtended BPF is not the same as BPF extensions! While
611 eBPF is an ISA, BPF extensions date back to classic BPF's 'overloading'
612 of BPF_LD | BPF_{B,H,W} | BPF_ABS instruction.)
613
614 It is designed to be JITed with one to one mapping, which can also open up
615 the possibility for GCC/LLVM compilers to generate optimized eBPF code through
616 an eBPF backend that performs almost as fast as natively compiled code.
617
618 The new instruction set was originally designed with the possible goal in
619 mind to write programs in "restricted C" and compile into eBPF with a optional
620 GCC/LLVM backend, so that it can just-in-time map to modern 64-bit CPUs with
621 minimal performance overhead over two steps, that is, C -> eBPF -> native code.
622
623 Currently, the new format is being used for running user BPF programs, which
624 includes seccomp BPF, classic socket filters, cls_bpf traffic classifier,
625 team driver's classifier for its load-balancing mode, netfilter's xt_bpf
626 extension, PTP dissector/classifier, and much more. They are all internally
627 converted by the kernel into the new instruction set representation and run
628 in the eBPF interpreter. For in-kernel handlers, this all works transparently
629 by using bpf_prog_create() for setting up the filter, resp.
630 bpf_prog_destroy() for destroying it. The macro
631 BPF_PROG_RUN(filter, ctx) transparently invokes eBPF interpreter or JITed
632 code to run the filter. 'filter' is a pointer to struct bpf_prog that we
633 got from bpf_prog_create(), and 'ctx' the given context (e.g.
634 skb pointer). All constraints and restrictions from bpf_check_classic() apply
635 before a conversion to the new layout is being done behind the scenes!
636
637 Currently, the classic BPF format is being used for JITing on most
638 32-bit architectures, whereas x86-64, aarch64, s390x, powerpc64,
639 sparc64, arm32, riscv64, riscv32 perform JIT compilation from eBPF
640 instruction set.
641
642 Some core changes of the new internal format:
643
644 - Number of registers increase from 2 to 10:
645
646   The old format had two registers A and X, and a hidden frame pointer. The
647   new layout extends this to be 10 internal registers and a read-only frame
648   pointer. Since 64-bit CPUs are passing arguments to functions via registers
649   the number of args from eBPF program to in-kernel function is restricted
650   to 5 and one register is used to accept return value from an in-kernel
651   function. Natively, x86_64 passes first 6 arguments in registers, aarch64/
652   sparcv9/mips64 have 7 - 8 registers for arguments; x86_64 has 6 callee saved
653   registers, and aarch64/sparcv9/mips64 have 11 or more callee saved registers.
654
655   Therefore, eBPF calling convention is defined as:
656
657     * R0        - return value from in-kernel function, and exit value for eBPF program
658     * R1 - R5   - arguments from eBPF program to in-kernel function
659     * R6 - R9   - callee saved registers that in-kernel function will preserve
660     * R10       - read-only frame pointer to access stack
661
662   Thus, all eBPF registers map one to one to HW registers on x86_64, aarch64,
663   etc, and eBPF calling convention maps directly to ABIs used by the kernel on
664   64-bit architectures.
665
666   On 32-bit architectures JIT may map programs that use only 32-bit arithmetic
667   and may let more complex programs to be interpreted.
668
669   R0 - R5 are scratch registers and eBPF program needs spill/fill them if
670   necessary across calls. Note that there is only one eBPF program (== one
671   eBPF main routine) and it cannot call other eBPF functions, it can only
672   call predefined in-kernel functions, though.
673
674 - Register width increases from 32-bit to 64-bit:
675
676   Still, the semantics of the original 32-bit ALU operations are preserved
677   via 32-bit subregisters. All eBPF registers are 64-bit with 32-bit lower
678   subregisters that zero-extend into 64-bit if they are being written to.
679   That behavior maps directly to x86_64 and arm64 subregister definition, but
680   makes other JITs more difficult.
681
682   32-bit architectures run 64-bit internal BPF programs via interpreter.
683   Their JITs may convert BPF programs that only use 32-bit subregisters into
684   native instruction set and let the rest being interpreted.
685
686   Operation is 64-bit, because on 64-bit architectures, pointers are also
687   64-bit wide, and we want to pass 64-bit values in/out of kernel functions,
688   so 32-bit eBPF registers would otherwise require to define register-pair
689   ABI, thus, there won't be able to use a direct eBPF register to HW register
690   mapping and JIT would need to do combine/split/move operations for every
691   register in and out of the function, which is complex, bug prone and slow.
692   Another reason is the use of atomic 64-bit counters.
693
694 - Conditional jt/jf targets replaced with jt/fall-through:
695
696   While the original design has constructs such as ``if (cond) jump_true;
697   else jump_false;``, they are being replaced into alternative constructs like
698   ``if (cond) jump_true; /* else fall-through */``.
699
700 - Introduces bpf_call insn and register passing convention for zero overhead
701   calls from/to other kernel functions:
702
703   Before an in-kernel function call, the internal BPF program needs to
704   place function arguments into R1 to R5 registers to satisfy calling
705   convention, then the interpreter will take them from registers and pass
706   to in-kernel function. If R1 - R5 registers are mapped to CPU registers
707   that are used for argument passing on given architecture, the JIT compiler
708   doesn't need to emit extra moves. Function arguments will be in the correct
709   registers and BPF_CALL instruction will be JITed as single 'call' HW
710   instruction. This calling convention was picked to cover common call
711   situations without performance penalty.
712
713   After an in-kernel function call, R1 - R5 are reset to unreadable and R0 has
714   a return value of the function. Since R6 - R9 are callee saved, their state
715   is preserved across the call.
716
717   For example, consider three C functions::
718
719     u64 f1() { return (*_f2)(1); }
720     u64 f2(u64 a) { return f3(a + 1, a); }
721     u64 f3(u64 a, u64 b) { return a - b; }
722
723   GCC can compile f1, f3 into x86_64::
724
725     f1:
726         movl $1, %edi
727         movq _f2(%rip), %rax
728         jmp  *%rax
729     f3:
730         movq %rdi, %rax
731         subq %rsi, %rax
732         ret
733
734   Function f2 in eBPF may look like::
735
736     f2:
737         bpf_mov R2, R1
738         bpf_add R1, 1
739         bpf_call f3
740         bpf_exit
741
742   If f2 is JITed and the pointer stored to ``_f2``. The calls f1 -> f2 -> f3 and
743   returns will be seamless. Without JIT, __bpf_prog_run() interpreter needs to
744   be used to call into f2.
745
746   For practical reasons all eBPF programs have only one argument 'ctx' which is
747   already placed into R1 (e.g. on __bpf_prog_run() startup) and the programs
748   can call kernel functions with up to 5 arguments. Calls with 6 or more arguments
749   are currently not supported, but these restrictions can be lifted if necessary
750   in the future.
751
752   On 64-bit architectures all register map to HW registers one to one. For
753   example, x86_64 JIT compiler can map them as ...
754
755   ::
756
757     R0 - rax
758     R1 - rdi
759     R2 - rsi
760     R3 - rdx
761     R4 - rcx
762     R5 - r8
763     R6 - rbx
764     R7 - r13
765     R8 - r14
766     R9 - r15
767     R10 - rbp
768
769   ... since x86_64 ABI mandates rdi, rsi, rdx, rcx, r8, r9 for argument passing
770   and rbx, r12 - r15 are callee saved.
771
772   Then the following internal BPF pseudo-program::
773
774     bpf_mov R6, R1 /* save ctx */
775     bpf_mov R2, 2
776     bpf_mov R3, 3
777     bpf_mov R4, 4
778     bpf_mov R5, 5
779     bpf_call foo
780     bpf_mov R7, R0 /* save foo() return value */
781     bpf_mov R1, R6 /* restore ctx for next call */
782     bpf_mov R2, 6
783     bpf_mov R3, 7
784     bpf_mov R4, 8
785     bpf_mov R5, 9
786     bpf_call bar
787     bpf_add R0, R7
788     bpf_exit
789
790   After JIT to x86_64 may look like::
791
792     push %rbp
793     mov %rsp,%rbp
794     sub $0x228,%rsp
795     mov %rbx,-0x228(%rbp)
796     mov %r13,-0x220(%rbp)
797     mov %rdi,%rbx
798     mov $0x2,%esi
799     mov $0x3,%edx
800     mov $0x4,%ecx
801     mov $0x5,%r8d
802     callq foo
803     mov %rax,%r13
804     mov %rbx,%rdi
805     mov $0x6,%esi
806     mov $0x7,%edx
807     mov $0x8,%ecx
808     mov $0x9,%r8d
809     callq bar
810     add %r13,%rax
811     mov -0x228(%rbp),%rbx
812     mov -0x220(%rbp),%r13
813     leaveq
814     retq
815
816   Which is in this example equivalent in C to::
817
818     u64 bpf_filter(u64 ctx)
819     {
820         return foo(ctx, 2, 3, 4, 5) + bar(ctx, 6, 7, 8, 9);
821     }
822
823   In-kernel functions foo() and bar() with prototype: u64 (*)(u64 arg1, u64
824   arg2, u64 arg3, u64 arg4, u64 arg5); will receive arguments in proper
825   registers and place their return value into ``%rax`` which is R0 in eBPF.
826   Prologue and epilogue are emitted by JIT and are implicit in the
827   interpreter. R0-R5 are scratch registers, so eBPF program needs to preserve
828   them across the calls as defined by calling convention.
829
830   For example the following program is invalid::
831
832     bpf_mov R1, 1
833     bpf_call foo
834     bpf_mov R0, R1
835     bpf_exit
836
837   After the call the registers R1-R5 contain junk values and cannot be read.
838   An in-kernel eBPF verifier is used to validate internal BPF programs.
839
840 Also in the new design, eBPF is limited to 4096 insns, which means that any
841 program will terminate quickly and will only call a fixed number of kernel
842 functions. Original BPF and the new format are two operand instructions,
843 which helps to do one-to-one mapping between eBPF insn and x86 insn during JIT.
844
845 The input context pointer for invoking the interpreter function is generic,
846 its content is defined by a specific use case. For seccomp register R1 points
847 to seccomp_data, for converted BPF filters R1 points to a skb.
848
849 A program, that is translated internally consists of the following elements::
850
851   op:16, jt:8, jf:8, k:32    ==>    op:8, dst_reg:4, src_reg:4, off:16, imm:32
852
853 So far 87 internal BPF instructions were implemented. 8-bit 'op' opcode field
854 has room for new instructions. Some of them may use 16/24/32 byte encoding. New
855 instructions must be multiple of 8 bytes to preserve backward compatibility.
856
857 Internal BPF is a general purpose RISC instruction set. Not every register and
858 every instruction are used during translation from original BPF to new format.
859 For example, socket filters are not using ``exclusive add`` instruction, but
860 tracing filters may do to maintain counters of events, for example. Register R9
861 is not used by socket filters either, but more complex filters may be running
862 out of registers and would have to resort to spill/fill to stack.
863
864 Internal BPF can be used as a generic assembler for last step performance
865 optimizations, socket filters and seccomp are using it as assembler. Tracing
866 filters may use it as assembler to generate code from kernel. In kernel usage
867 may not be bounded by security considerations, since generated internal BPF code
868 may be optimizing internal code path and not being exposed to the user space.
869 Safety of internal BPF can come from a verifier (TBD). In such use cases as
870 described, it may be used as safe instruction set.
871
872 Just like the original BPF, the new format runs within a controlled environment,
873 is deterministic and the kernel can easily prove that. The safety of the program
874 can be determined in two steps: first step does depth-first-search to disallow
875 loops and other CFG validation; second step starts from the first insn and
876 descends all possible paths. It simulates execution of every insn and observes
877 the state change of registers and stack.
878
879 eBPF opcode encoding
880 --------------------
881
882 eBPF is reusing most of the opcode encoding from classic to simplify conversion
883 of classic BPF to eBPF. For arithmetic and jump instructions the 8-bit 'code'
884 field is divided into three parts::
885
886   +----------------+--------+--------------------+
887   |   4 bits       |  1 bit |   3 bits           |
888   | operation code | source | instruction class  |
889   +----------------+--------+--------------------+
890   (MSB)                                      (LSB)
891
892 Three LSB bits store instruction class which is one of:
893
894   ===================     ===============
895   Classic BPF classes     eBPF classes
896   ===================     ===============
897   BPF_LD    0x00          BPF_LD    0x00
898   BPF_LDX   0x01          BPF_LDX   0x01
899   BPF_ST    0x02          BPF_ST    0x02
900   BPF_STX   0x03          BPF_STX   0x03
901   BPF_ALU   0x04          BPF_ALU   0x04
902   BPF_JMP   0x05          BPF_JMP   0x05
903   BPF_RET   0x06          BPF_JMP32 0x06
904   BPF_MISC  0x07          BPF_ALU64 0x07
905   ===================     ===============
906
907 When BPF_CLASS(code) == BPF_ALU or BPF_JMP, 4th bit encodes source operand ...
908
909     ::
910
911         BPF_K     0x00
912         BPF_X     0x08
913
914  * in classic BPF, this means::
915
916         BPF_SRC(code) == BPF_X - use register X as source operand
917         BPF_SRC(code) == BPF_K - use 32-bit immediate as source operand
918
919  * in eBPF, this means::
920
921         BPF_SRC(code) == BPF_X - use 'src_reg' register as source operand
922         BPF_SRC(code) == BPF_K - use 32-bit immediate as source operand
923
924 ... and four MSB bits store operation code.
925
926 If BPF_CLASS(code) == BPF_ALU or BPF_ALU64 [ in eBPF ], BPF_OP(code) is one of::
927
928   BPF_ADD   0x00
929   BPF_SUB   0x10
930   BPF_MUL   0x20
931   BPF_DIV   0x30
932   BPF_OR    0x40
933   BPF_AND   0x50
934   BPF_LSH   0x60
935   BPF_RSH   0x70
936   BPF_NEG   0x80
937   BPF_MOD   0x90
938   BPF_XOR   0xa0
939   BPF_MOV   0xb0  /* eBPF only: mov reg to reg */
940   BPF_ARSH  0xc0  /* eBPF only: sign extending shift right */
941   BPF_END   0xd0  /* eBPF only: endianness conversion */
942
943 If BPF_CLASS(code) == BPF_JMP or BPF_JMP32 [ in eBPF ], BPF_OP(code) is one of::
944
945   BPF_JA    0x00  /* BPF_JMP only */
946   BPF_JEQ   0x10
947   BPF_JGT   0x20
948   BPF_JGE   0x30
949   BPF_JSET  0x40
950   BPF_JNE   0x50  /* eBPF only: jump != */
951   BPF_JSGT  0x60  /* eBPF only: signed '>' */
952   BPF_JSGE  0x70  /* eBPF only: signed '>=' */
953   BPF_CALL  0x80  /* eBPF BPF_JMP only: function call */
954   BPF_EXIT  0x90  /* eBPF BPF_JMP only: function return */
955   BPF_JLT   0xa0  /* eBPF only: unsigned '<' */
956   BPF_JLE   0xb0  /* eBPF only: unsigned '<=' */
957   BPF_JSLT  0xc0  /* eBPF only: signed '<' */
958   BPF_JSLE  0xd0  /* eBPF only: signed '<=' */
959
960 So BPF_ADD | BPF_X | BPF_ALU means 32-bit addition in both classic BPF
961 and eBPF. There are only two registers in classic BPF, so it means A += X.
962 In eBPF it means dst_reg = (u32) dst_reg + (u32) src_reg; similarly,
963 BPF_XOR | BPF_K | BPF_ALU means A ^= imm32 in classic BPF and analogous
964 src_reg = (u32) src_reg ^ (u32) imm32 in eBPF.
965
966 Classic BPF is using BPF_MISC class to represent A = X and X = A moves.
967 eBPF is using BPF_MOV | BPF_X | BPF_ALU code instead. Since there are no
968 BPF_MISC operations in eBPF, the class 7 is used as BPF_ALU64 to mean
969 exactly the same operations as BPF_ALU, but with 64-bit wide operands
970 instead. So BPF_ADD | BPF_X | BPF_ALU64 means 64-bit addition, i.e.:
971 dst_reg = dst_reg + src_reg
972
973 Classic BPF wastes the whole BPF_RET class to represent a single ``ret``
974 operation. Classic BPF_RET | BPF_K means copy imm32 into return register
975 and perform function exit. eBPF is modeled to match CPU, so BPF_JMP | BPF_EXIT
976 in eBPF means function exit only. The eBPF program needs to store return
977 value into register R0 before doing a BPF_EXIT. Class 6 in eBPF is used as
978 BPF_JMP32 to mean exactly the same operations as BPF_JMP, but with 32-bit wide
979 operands for the comparisons instead.
980
981 For load and store instructions the 8-bit 'code' field is divided as::
982
983   +--------+--------+-------------------+
984   | 3 bits | 2 bits |   3 bits          |
985   |  mode  |  size  | instruction class |
986   +--------+--------+-------------------+
987   (MSB)                             (LSB)
988
989 Size modifier is one of ...
990
991 ::
992
993   BPF_W   0x00    /* word */
994   BPF_H   0x08    /* half word */
995   BPF_B   0x10    /* byte */
996   BPF_DW  0x18    /* eBPF only, double word */
997
998 ... which encodes size of load/store operation::
999
1000  B  - 1 byte
1001  H  - 2 byte
1002  W  - 4 byte
1003  DW - 8 byte (eBPF only)
1004
1005 Mode modifier is one of::
1006
1007   BPF_IMM  0x00  /* used for 32-bit mov in classic BPF and 64-bit in eBPF */
1008   BPF_ABS  0x20
1009   BPF_IND  0x40
1010   BPF_MEM  0x60
1011   BPF_LEN  0x80  /* classic BPF only, reserved in eBPF */
1012   BPF_MSH  0xa0  /* classic BPF only, reserved in eBPF */
1013   BPF_XADD 0xc0  /* eBPF only, exclusive add */
1014
1015 eBPF has two non-generic instructions: (BPF_ABS | <size> | BPF_LD) and
1016 (BPF_IND | <size> | BPF_LD) which are used to access packet data.
1017
1018 They had to be carried over from classic to have strong performance of
1019 socket filters running in eBPF interpreter. These instructions can only
1020 be used when interpreter context is a pointer to ``struct sk_buff`` and
1021 have seven implicit operands. Register R6 is an implicit input that must
1022 contain pointer to sk_buff. Register R0 is an implicit output which contains
1023 the data fetched from the packet. Registers R1-R5 are scratch registers
1024 and must not be used to store the data across BPF_ABS | BPF_LD or
1025 BPF_IND | BPF_LD instructions.
1026
1027 These instructions have implicit program exit condition as well. When
1028 eBPF program is trying to access the data beyond the packet boundary,
1029 the interpreter will abort the execution of the program. JIT compilers
1030 therefore must preserve this property. src_reg and imm32 fields are
1031 explicit inputs to these instructions.
1032
1033 For example::
1034
1035   BPF_IND | BPF_W | BPF_LD means:
1036
1037     R0 = ntohl(*(u32 *) (((struct sk_buff *) R6)->data + src_reg + imm32))
1038     and R1 - R5 were scratched.
1039
1040 Unlike classic BPF instruction set, eBPF has generic load/store operations::
1041
1042     BPF_MEM | <size> | BPF_STX:  *(size *) (dst_reg + off) = src_reg
1043     BPF_MEM | <size> | BPF_ST:   *(size *) (dst_reg + off) = imm32
1044     BPF_MEM | <size> | BPF_LDX:  dst_reg = *(size *) (src_reg + off)
1045     BPF_XADD | BPF_W  | BPF_STX: lock xadd *(u32 *)(dst_reg + off16) += src_reg
1046     BPF_XADD | BPF_DW | BPF_STX: lock xadd *(u64 *)(dst_reg + off16) += src_reg
1047
1048 Where size is one of: BPF_B or BPF_H or BPF_W or BPF_DW. Note that 1 and
1049 2 byte atomic increments are not supported.
1050
1051 eBPF has one 16-byte instruction: BPF_LD | BPF_DW | BPF_IMM which consists
1052 of two consecutive ``struct bpf_insn`` 8-byte blocks and interpreted as single
1053 instruction that loads 64-bit immediate value into a dst_reg.
1054 Classic BPF has similar instruction: BPF_LD | BPF_W | BPF_IMM which loads
1055 32-bit immediate value into a register.
1056
1057 eBPF verifier
1058 -------------
1059 The safety of the eBPF program is determined in two steps.
1060
1061 First step does DAG check to disallow loops and other CFG validation.
1062 In particular it will detect programs that have unreachable instructions.
1063 (though classic BPF checker allows them)
1064
1065 Second step starts from the first insn and descends all possible paths.
1066 It simulates execution of every insn and observes the state change of
1067 registers and stack.
1068
1069 At the start of the program the register R1 contains a pointer to context
1070 and has type PTR_TO_CTX.
1071 If verifier sees an insn that does R2=R1, then R2 has now type
1072 PTR_TO_CTX as well and can be used on the right hand side of expression.
1073 If R1=PTR_TO_CTX and insn is R2=R1+R1, then R2=SCALAR_VALUE,
1074 since addition of two valid pointers makes invalid pointer.
1075 (In 'secure' mode verifier will reject any type of pointer arithmetic to make
1076 sure that kernel addresses don't leak to unprivileged users)
1077
1078 If register was never written to, it's not readable::
1079
1080   bpf_mov R0 = R2
1081   bpf_exit
1082
1083 will be rejected, since R2 is unreadable at the start of the program.
1084
1085 After kernel function call, R1-R5 are reset to unreadable and
1086 R0 has a return type of the function.
1087
1088 Since R6-R9 are callee saved, their state is preserved across the call.
1089
1090 ::
1091
1092   bpf_mov R6 = 1
1093   bpf_call foo
1094   bpf_mov R0 = R6
1095   bpf_exit
1096
1097 is a correct program. If there was R1 instead of R6, it would have
1098 been rejected.
1099
1100 load/store instructions are allowed only with registers of valid types, which
1101 are PTR_TO_CTX, PTR_TO_MAP, PTR_TO_STACK. They are bounds and alignment checked.
1102 For example::
1103
1104  bpf_mov R1 = 1
1105  bpf_mov R2 = 2
1106  bpf_xadd *(u32 *)(R1 + 3) += R2
1107  bpf_exit
1108
1109 will be rejected, since R1 doesn't have a valid pointer type at the time of
1110 execution of instruction bpf_xadd.
1111
1112 At the start R1 type is PTR_TO_CTX (a pointer to generic ``struct bpf_context``)
1113 A callback is used to customize verifier to restrict eBPF program access to only
1114 certain fields within ctx structure with specified size and alignment.
1115
1116 For example, the following insn::
1117
1118   bpf_ld R0 = *(u32 *)(R6 + 8)
1119
1120 intends to load a word from address R6 + 8 and store it into R0
1121 If R6=PTR_TO_CTX, via is_valid_access() callback the verifier will know
1122 that offset 8 of size 4 bytes can be accessed for reading, otherwise
1123 the verifier will reject the program.
1124 If R6=PTR_TO_STACK, then access should be aligned and be within
1125 stack bounds, which are [-MAX_BPF_STACK, 0). In this example offset is 8,
1126 so it will fail verification, since it's out of bounds.
1127
1128 The verifier will allow eBPF program to read data from stack only after
1129 it wrote into it.
1130
1131 Classic BPF verifier does similar check with M[0-15] memory slots.
1132 For example::
1133
1134   bpf_ld R0 = *(u32 *)(R10 - 4)
1135   bpf_exit
1136
1137 is invalid program.
1138 Though R10 is correct read-only register and has type PTR_TO_STACK
1139 and R10 - 4 is within stack bounds, there were no stores into that location.
1140
1141 Pointer register spill/fill is tracked as well, since four (R6-R9)
1142 callee saved registers may not be enough for some programs.
1143
1144 Allowed function calls are customized with bpf_verifier_ops->get_func_proto()
1145 The eBPF verifier will check that registers match argument constraints.
1146 After the call register R0 will be set to return type of the function.
1147
1148 Function calls is a main mechanism to extend functionality of eBPF programs.
1149 Socket filters may let programs to call one set of functions, whereas tracing
1150 filters may allow completely different set.
1151
1152 If a function made accessible to eBPF program, it needs to be thought through
1153 from safety point of view. The verifier will guarantee that the function is
1154 called with valid arguments.
1155
1156 seccomp vs socket filters have different security restrictions for classic BPF.
1157 Seccomp solves this by two stage verifier: classic BPF verifier is followed
1158 by seccomp verifier. In case of eBPF one configurable verifier is shared for
1159 all use cases.
1160
1161 See details of eBPF verifier in kernel/bpf/verifier.c
1162
1163 Register value tracking
1164 -----------------------
1165 In order to determine the safety of an eBPF program, the verifier must track
1166 the range of possible values in each register and also in each stack slot.
1167 This is done with ``struct bpf_reg_state``, defined in include/linux/
1168 bpf_verifier.h, which unifies tracking of scalar and pointer values.  Each
1169 register state has a type, which is either NOT_INIT (the register has not been
1170 written to), SCALAR_VALUE (some value which is not usable as a pointer), or a
1171 pointer type.  The types of pointers describe their base, as follows:
1172
1173
1174     PTR_TO_CTX
1175                         Pointer to bpf_context.
1176     CONST_PTR_TO_MAP
1177                         Pointer to struct bpf_map.  "Const" because arithmetic
1178                         on these pointers is forbidden.
1179     PTR_TO_MAP_VALUE
1180                         Pointer to the value stored in a map element.
1181     PTR_TO_MAP_VALUE_OR_NULL
1182                         Either a pointer to a map value, or NULL; map accesses
1183                         (see section 'eBPF maps', below) return this type,
1184                         which becomes a PTR_TO_MAP_VALUE when checked != NULL.
1185                         Arithmetic on these pointers is forbidden.
1186     PTR_TO_STACK
1187                         Frame pointer.
1188     PTR_TO_PACKET
1189                         skb->data.
1190     PTR_TO_PACKET_END
1191                         skb->data + headlen; arithmetic forbidden.
1192     PTR_TO_SOCKET
1193                         Pointer to struct bpf_sock_ops, implicitly refcounted.
1194     PTR_TO_SOCKET_OR_NULL
1195                         Either a pointer to a socket, or NULL; socket lookup
1196                         returns this type, which becomes a PTR_TO_SOCKET when
1197                         checked != NULL. PTR_TO_SOCKET is reference-counted,
1198                         so programs must release the reference through the
1199                         socket release function before the end of the program.
1200                         Arithmetic on these pointers is forbidden.
1201
1202 However, a pointer may be offset from this base (as a result of pointer
1203 arithmetic), and this is tracked in two parts: the 'fixed offset' and 'variable
1204 offset'.  The former is used when an exactly-known value (e.g. an immediate
1205 operand) is added to a pointer, while the latter is used for values which are
1206 not exactly known.  The variable offset is also used in SCALAR_VALUEs, to track
1207 the range of possible values in the register.
1208
1209 The verifier's knowledge about the variable offset consists of:
1210
1211 * minimum and maximum values as unsigned
1212 * minimum and maximum values as signed
1213
1214 * knowledge of the values of individual bits, in the form of a 'tnum': a u64
1215   'mask' and a u64 'value'.  1s in the mask represent bits whose value is unknown;
1216   1s in the value represent bits known to be 1.  Bits known to be 0 have 0 in both
1217   mask and value; no bit should ever be 1 in both.  For example, if a byte is read
1218   into a register from memory, the register's top 56 bits are known zero, while
1219   the low 8 are unknown - which is represented as the tnum (0x0; 0xff).  If we
1220   then OR this with 0x40, we get (0x40; 0xbf), then if we add 1 we get (0x0;
1221   0x1ff), because of potential carries.
1222
1223 Besides arithmetic, the register state can also be updated by conditional
1224 branches.  For instance, if a SCALAR_VALUE is compared > 8, in the 'true' branch
1225 it will have a umin_value (unsigned minimum value) of 9, whereas in the 'false'
1226 branch it will have a umax_value of 8.  A signed compare (with BPF_JSGT or
1227 BPF_JSGE) would instead update the signed minimum/maximum values.  Information
1228 from the signed and unsigned bounds can be combined; for instance if a value is
1229 first tested < 8 and then tested s> 4, the verifier will conclude that the value
1230 is also > 4 and s< 8, since the bounds prevent crossing the sign boundary.
1231
1232 PTR_TO_PACKETs with a variable offset part have an 'id', which is common to all
1233 pointers sharing that same variable offset.  This is important for packet range
1234 checks: after adding a variable to a packet pointer register A, if you then copy
1235 it to another register B and then add a constant 4 to A, both registers will
1236 share the same 'id' but the A will have a fixed offset of +4.  Then if A is
1237 bounds-checked and found to be less than a PTR_TO_PACKET_END, the register B is
1238 now known to have a safe range of at least 4 bytes.  See 'Direct packet access',
1239 below, for more on PTR_TO_PACKET ranges.
1240
1241 The 'id' field is also used on PTR_TO_MAP_VALUE_OR_NULL, common to all copies of
1242 the pointer returned from a map lookup.  This means that when one copy is
1243 checked and found to be non-NULL, all copies can become PTR_TO_MAP_VALUEs.
1244 As well as range-checking, the tracked information is also used for enforcing
1245 alignment of pointer accesses.  For instance, on most systems the packet pointer
1246 is 2 bytes after a 4-byte alignment.  If a program adds 14 bytes to that to jump
1247 over the Ethernet header, then reads IHL and addes (IHL * 4), the resulting
1248 pointer will have a variable offset known to be 4n+2 for some n, so adding the 2
1249 bytes (NET_IP_ALIGN) gives a 4-byte alignment and so word-sized accesses through
1250 that pointer are safe.
1251 The 'id' field is also used on PTR_TO_SOCKET and PTR_TO_SOCKET_OR_NULL, common
1252 to all copies of the pointer returned from a socket lookup. This has similar
1253 behaviour to the handling for PTR_TO_MAP_VALUE_OR_NULL->PTR_TO_MAP_VALUE, but
1254 it also handles reference tracking for the pointer. PTR_TO_SOCKET implicitly
1255 represents a reference to the corresponding ``struct sock``. To ensure that the
1256 reference is not leaked, it is imperative to NULL-check the reference and in
1257 the non-NULL case, and pass the valid reference to the socket release function.
1258
1259 Direct packet access
1260 --------------------
1261 In cls_bpf and act_bpf programs the verifier allows direct access to the packet
1262 data via skb->data and skb->data_end pointers.
1263 Ex::
1264
1265     1:  r4 = *(u32 *)(r1 +80)  /* load skb->data_end */
1266     2:  r3 = *(u32 *)(r1 +76)  /* load skb->data */
1267     3:  r5 = r3
1268     4:  r5 += 14
1269     5:  if r5 > r4 goto pc+16
1270     R1=ctx R3=pkt(id=0,off=0,r=14) R4=pkt_end R5=pkt(id=0,off=14,r=14) R10=fp
1271     6:  r0 = *(u16 *)(r3 +12) /* access 12 and 13 bytes of the packet */
1272
1273 this 2byte load from the packet is safe to do, since the program author
1274 did check ``if (skb->data + 14 > skb->data_end) goto err`` at insn #5 which
1275 means that in the fall-through case the register R3 (which points to skb->data)
1276 has at least 14 directly accessible bytes. The verifier marks it
1277 as R3=pkt(id=0,off=0,r=14).
1278 id=0 means that no additional variables were added to the register.
1279 off=0 means that no additional constants were added.
1280 r=14 is the range of safe access which means that bytes [R3, R3 + 14) are ok.
1281 Note that R5 is marked as R5=pkt(id=0,off=14,r=14). It also points
1282 to the packet data, but constant 14 was added to the register, so
1283 it now points to ``skb->data + 14`` and accessible range is [R5, R5 + 14 - 14)
1284 which is zero bytes.
1285
1286 More complex packet access may look like::
1287
1288
1289     R0=inv1 R1=ctx R3=pkt(id=0,off=0,r=14) R4=pkt_end R5=pkt(id=0,off=14,r=14) R10=fp
1290     6:  r0 = *(u8 *)(r3 +7) /* load 7th byte from the packet */
1291     7:  r4 = *(u8 *)(r3 +12)
1292     8:  r4 *= 14
1293     9:  r3 = *(u32 *)(r1 +76) /* load skb->data */
1294     10:  r3 += r4
1295     11:  r2 = r1
1296     12:  r2 <<= 48
1297     13:  r2 >>= 48
1298     14:  r3 += r2
1299     15:  r2 = r3
1300     16:  r2 += 8
1301     17:  r1 = *(u32 *)(r1 +80) /* load skb->data_end */
1302     18:  if r2 > r1 goto pc+2
1303     R0=inv(id=0,umax_value=255,var_off=(0x0; 0xff)) R1=pkt_end R2=pkt(id=2,off=8,r=8) R3=pkt(id=2,off=0,r=8) R4=inv(id=0,umax_value=3570,var_off=(0x0; 0xfffe)) R5=pkt(id=0,off=14,r=14) R10=fp
1304     19:  r1 = *(u8 *)(r3 +4)
1305
1306 The state of the register R3 is R3=pkt(id=2,off=0,r=8)
1307 id=2 means that two ``r3 += rX`` instructions were seen, so r3 points to some
1308 offset within a packet and since the program author did
1309 ``if (r3 + 8 > r1) goto err`` at insn #18, the safe range is [R3, R3 + 8).
1310 The verifier only allows 'add'/'sub' operations on packet registers. Any other
1311 operation will set the register state to 'SCALAR_VALUE' and it won't be
1312 available for direct packet access.
1313
1314 Operation ``r3 += rX`` may overflow and become less than original skb->data,
1315 therefore the verifier has to prevent that.  So when it sees ``r3 += rX``
1316 instruction and rX is more than 16-bit value, any subsequent bounds-check of r3
1317 against skb->data_end will not give us 'range' information, so attempts to read
1318 through the pointer will give "invalid access to packet" error.
1319
1320 Ex. after insn ``r4 = *(u8 *)(r3 +12)`` (insn #7 above) the state of r4 is
1321 R4=inv(id=0,umax_value=255,var_off=(0x0; 0xff)) which means that upper 56 bits
1322 of the register are guaranteed to be zero, and nothing is known about the lower
1323 8 bits. After insn ``r4 *= 14`` the state becomes
1324 R4=inv(id=0,umax_value=3570,var_off=(0x0; 0xfffe)), since multiplying an 8-bit
1325 value by constant 14 will keep upper 52 bits as zero, also the least significant
1326 bit will be zero as 14 is even.  Similarly ``r2 >>= 48`` will make
1327 R2=inv(id=0,umax_value=65535,var_off=(0x0; 0xffff)), since the shift is not sign
1328 extending.  This logic is implemented in adjust_reg_min_max_vals() function,
1329 which calls adjust_ptr_min_max_vals() for adding pointer to scalar (or vice
1330 versa) and adjust_scalar_min_max_vals() for operations on two scalars.
1331
1332 The end result is that bpf program author can access packet directly
1333 using normal C code as::
1334
1335   void *data = (void *)(long)skb->data;
1336   void *data_end = (void *)(long)skb->data_end;
1337   struct eth_hdr *eth = data;
1338   struct iphdr *iph = data + sizeof(*eth);
1339   struct udphdr *udp = data + sizeof(*eth) + sizeof(*iph);
1340
1341   if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) > data_end)
1342           return 0;
1343   if (eth->h_proto != htons(ETH_P_IP))
1344           return 0;
1345   if (iph->protocol != IPPROTO_UDP || iph->ihl != 5)
1346           return 0;
1347   if (udp->dest == 53 || udp->source == 9)
1348           ...;
1349
1350 which makes such programs easier to write comparing to LD_ABS insn
1351 and significantly faster.
1352
1353 eBPF maps
1354 ---------
1355 'maps' is a generic storage of different types for sharing data between kernel
1356 and userspace.
1357
1358 The maps are accessed from user space via BPF syscall, which has commands:
1359
1360 - create a map with given type and attributes
1361   ``map_fd = bpf(BPF_MAP_CREATE, union bpf_attr *attr, u32 size)``
1362   using attr->map_type, attr->key_size, attr->value_size, attr->max_entries
1363   returns process-local file descriptor or negative error
1364
1365 - lookup key in a given map
1366   ``err = bpf(BPF_MAP_LOOKUP_ELEM, union bpf_attr *attr, u32 size)``
1367   using attr->map_fd, attr->key, attr->value
1368   returns zero and stores found elem into value or negative error
1369
1370 - create or update key/value pair in a given map
1371   ``err = bpf(BPF_MAP_UPDATE_ELEM, union bpf_attr *attr, u32 size)``
1372   using attr->map_fd, attr->key, attr->value
1373   returns zero or negative error
1374
1375 - find and delete element by key in a given map
1376   ``err = bpf(BPF_MAP_DELETE_ELEM, union bpf_attr *attr, u32 size)``
1377   using attr->map_fd, attr->key
1378
1379 - to delete map: close(fd)
1380   Exiting process will delete maps automatically
1381
1382 userspace programs use this syscall to create/access maps that eBPF programs
1383 are concurrently updating.
1384
1385 maps can have different types: hash, array, bloom filter, radix-tree, etc.
1386
1387 The map is defined by:
1388
1389   - type
1390   - max number of elements
1391   - key size in bytes
1392   - value size in bytes
1393
1394 Pruning
1395 -------
1396 The verifier does not actually walk all possible paths through the program.  For
1397 each new branch to analyse, the verifier looks at all the states it's previously
1398 been in when at this instruction.  If any of them contain the current state as a
1399 subset, the branch is 'pruned' - that is, the fact that the previous state was
1400 accepted implies the current state would be as well.  For instance, if in the
1401 previous state, r1 held a packet-pointer, and in the current state, r1 holds a
1402 packet-pointer with a range as long or longer and at least as strict an
1403 alignment, then r1 is safe.  Similarly, if r2 was NOT_INIT before then it can't
1404 have been used by any path from that point, so any value in r2 (including
1405 another NOT_INIT) is safe.  The implementation is in the function regsafe().
1406 Pruning considers not only the registers but also the stack (and any spilled
1407 registers it may hold).  They must all be safe for the branch to be pruned.
1408 This is implemented in states_equal().
1409
1410 Understanding eBPF verifier messages
1411 ------------------------------------
1412
1413 The following are few examples of invalid eBPF programs and verifier error
1414 messages as seen in the log:
1415
1416 Program with unreachable instructions::
1417
1418   static struct bpf_insn prog[] = {
1419   BPF_EXIT_INSN(),
1420   BPF_EXIT_INSN(),
1421   };
1422
1423 Error:
1424
1425   unreachable insn 1
1426
1427 Program that reads uninitialized register::
1428
1429   BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
1430   BPF_EXIT_INSN(),
1431
1432 Error::
1433
1434   0: (bf) r0 = r2
1435   R2 !read_ok
1436
1437 Program that doesn't initialize R0 before exiting::
1438
1439   BPF_MOV64_REG(BPF_REG_2, BPF_REG_1),
1440   BPF_EXIT_INSN(),
1441
1442 Error::
1443
1444   0: (bf) r2 = r1
1445   1: (95) exit
1446   R0 !read_ok
1447
1448 Program that accesses stack out of bounds::
1449
1450     BPF_ST_MEM(BPF_DW, BPF_REG_10, 8, 0),
1451     BPF_EXIT_INSN(),
1452
1453 Error::
1454
1455     0: (7a) *(u64 *)(r10 +8) = 0
1456     invalid stack off=8 size=8
1457
1458 Program that doesn't initialize stack before passing its address into function::
1459
1460   BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
1461   BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
1462   BPF_LD_MAP_FD(BPF_REG_1, 0),
1463   BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
1464   BPF_EXIT_INSN(),
1465
1466 Error::
1467
1468   0: (bf) r2 = r10
1469   1: (07) r2 += -8
1470   2: (b7) r1 = 0x0
1471   3: (85) call 1
1472   invalid indirect read from stack off -8+0 size 8
1473
1474 Program that uses invalid map_fd=0 while calling to map_lookup_elem() function::
1475
1476   BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
1477   BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
1478   BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
1479   BPF_LD_MAP_FD(BPF_REG_1, 0),
1480   BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
1481   BPF_EXIT_INSN(),
1482
1483 Error::
1484
1485   0: (7a) *(u64 *)(r10 -8) = 0
1486   1: (bf) r2 = r10
1487   2: (07) r2 += -8
1488   3: (b7) r1 = 0x0
1489   4: (85) call 1
1490   fd 0 is not pointing to valid bpf_map
1491
1492 Program that doesn't check return value of map_lookup_elem() before accessing
1493 map element::
1494
1495   BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
1496   BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
1497   BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
1498   BPF_LD_MAP_FD(BPF_REG_1, 0),
1499   BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
1500   BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 0),
1501   BPF_EXIT_INSN(),
1502
1503 Error::
1504
1505   0: (7a) *(u64 *)(r10 -8) = 0
1506   1: (bf) r2 = r10
1507   2: (07) r2 += -8
1508   3: (b7) r1 = 0x0
1509   4: (85) call 1
1510   5: (7a) *(u64 *)(r0 +0) = 0
1511   R0 invalid mem access 'map_value_or_null'
1512
1513 Program that correctly checks map_lookup_elem() returned value for NULL, but
1514 accesses the memory with incorrect alignment::
1515
1516   BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
1517   BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
1518   BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
1519   BPF_LD_MAP_FD(BPF_REG_1, 0),
1520   BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
1521   BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 1),
1522   BPF_ST_MEM(BPF_DW, BPF_REG_0, 4, 0),
1523   BPF_EXIT_INSN(),
1524
1525 Error::
1526
1527   0: (7a) *(u64 *)(r10 -8) = 0
1528   1: (bf) r2 = r10
1529   2: (07) r2 += -8
1530   3: (b7) r1 = 1
1531   4: (85) call 1
1532   5: (15) if r0 == 0x0 goto pc+1
1533    R0=map_ptr R10=fp
1534   6: (7a) *(u64 *)(r0 +4) = 0
1535   misaligned access off 4 size 8
1536
1537 Program that correctly checks map_lookup_elem() returned value for NULL and
1538 accesses memory with correct alignment in one side of 'if' branch, but fails
1539 to do so in the other side of 'if' branch::
1540
1541   BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
1542   BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
1543   BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
1544   BPF_LD_MAP_FD(BPF_REG_1, 0),
1545   BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
1546   BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2),
1547   BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 0),
1548   BPF_EXIT_INSN(),
1549   BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 1),
1550   BPF_EXIT_INSN(),
1551
1552 Error::
1553
1554   0: (7a) *(u64 *)(r10 -8) = 0
1555   1: (bf) r2 = r10
1556   2: (07) r2 += -8
1557   3: (b7) r1 = 1
1558   4: (85) call 1
1559   5: (15) if r0 == 0x0 goto pc+2
1560    R0=map_ptr R10=fp
1561   6: (7a) *(u64 *)(r0 +0) = 0
1562   7: (95) exit
1563
1564   from 5 to 8: R0=imm0 R10=fp
1565   8: (7a) *(u64 *)(r0 +0) = 1
1566   R0 invalid mem access 'imm'
1567
1568 Program that performs a socket lookup then sets the pointer to NULL without
1569 checking it::
1570
1571   BPF_MOV64_IMM(BPF_REG_2, 0),
1572   BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_2, -8),
1573   BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
1574   BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
1575   BPF_MOV64_IMM(BPF_REG_3, 4),
1576   BPF_MOV64_IMM(BPF_REG_4, 0),
1577   BPF_MOV64_IMM(BPF_REG_5, 0),
1578   BPF_EMIT_CALL(BPF_FUNC_sk_lookup_tcp),
1579   BPF_MOV64_IMM(BPF_REG_0, 0),
1580   BPF_EXIT_INSN(),
1581
1582 Error::
1583
1584   0: (b7) r2 = 0
1585   1: (63) *(u32 *)(r10 -8) = r2
1586   2: (bf) r2 = r10
1587   3: (07) r2 += -8
1588   4: (b7) r3 = 4
1589   5: (b7) r4 = 0
1590   6: (b7) r5 = 0
1591   7: (85) call bpf_sk_lookup_tcp#65
1592   8: (b7) r0 = 0
1593   9: (95) exit
1594   Unreleased reference id=1, alloc_insn=7
1595
1596 Program that performs a socket lookup but does not NULL-check the returned
1597 value::
1598
1599   BPF_MOV64_IMM(BPF_REG_2, 0),
1600   BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_2, -8),
1601   BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
1602   BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
1603   BPF_MOV64_IMM(BPF_REG_3, 4),
1604   BPF_MOV64_IMM(BPF_REG_4, 0),
1605   BPF_MOV64_IMM(BPF_REG_5, 0),
1606   BPF_EMIT_CALL(BPF_FUNC_sk_lookup_tcp),
1607   BPF_EXIT_INSN(),
1608
1609 Error::
1610
1611   0: (b7) r2 = 0
1612   1: (63) *(u32 *)(r10 -8) = r2
1613   2: (bf) r2 = r10
1614   3: (07) r2 += -8
1615   4: (b7) r3 = 4
1616   5: (b7) r4 = 0
1617   6: (b7) r5 = 0
1618   7: (85) call bpf_sk_lookup_tcp#65
1619   8: (95) exit
1620   Unreleased reference id=1, alloc_insn=7
1621
1622 Testing
1623 -------
1624
1625 Next to the BPF toolchain, the kernel also ships a test module that contains
1626 various test cases for classic and internal BPF that can be executed against
1627 the BPF interpreter and JIT compiler. It can be found in lib/test_bpf.c and
1628 enabled via Kconfig::
1629
1630   CONFIG_TEST_BPF=m
1631
1632 After the module has been built and installed, the test suite can be executed
1633 via insmod or modprobe against 'test_bpf' module. Results of the test cases
1634 including timings in nsec can be found in the kernel log (dmesg).
1635
1636 Misc
1637 ----
1638
1639 Also trinity, the Linux syscall fuzzer, has built-in support for BPF and
1640 SECCOMP-BPF kernel fuzzing.
1641
1642 Written by
1643 ----------
1644
1645 The document was written in the hope that it is found useful and in order
1646 to give potential BPF hackers or security auditors a better overview of
1647 the underlying architecture.
1648
1649 - Jay Schulist <jschlst@samba.org>
1650 - Daniel Borkmann <daniel@iogearbox.net>
1651 - Alexei Starovoitov <ast@kernel.org>