filter.txt 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  1. Linux Socket Filtering aka Berkeley Packet Filter (BPF)
  2. =======================================================
  3. Introduction
  4. ------------
  5. Linux Socket Filtering (LSF) is derived from the Berkeley Packet Filter.
  6. Though there are some distinct differences between the BSD and Linux
  7. Kernel filtering, but when we speak of BPF or LSF in Linux context, we
  8. mean the very same mechanism of filtering in the Linux kernel.
  9. BPF allows a user-space program to attach a filter onto any socket and
  10. allow or disallow certain types of data to come through the socket. LSF
  11. follows exactly the same filter code structure as BSD's BPF, so referring
  12. to the BSD bpf.4 manpage is very helpful in creating filters.
  13. On Linux, BPF is much simpler than on BSD. One does not have to worry
  14. about devices or anything like that. You simply create your filter code,
  15. send it to the kernel via the SO_ATTACH_FILTER option and if your filter
  16. code passes the kernel check on it, you then immediately begin filtering
  17. data on that socket.
  18. You can also detach filters from your socket via the SO_DETACH_FILTER
  19. option. This will probably not be used much since when you close a socket
  20. that has a filter on it the filter is automagically removed. The other
  21. less common case may be adding a different filter on the same socket where
  22. you had another filter that is still running: the kernel takes care of
  23. removing the old one and placing your new one in its place, assuming your
  24. filter has passed the checks, otherwise if it fails the old filter will
  25. remain on that socket.
  26. SO_LOCK_FILTER option allows to lock the filter attached to a socket. Once
  27. set, a filter cannot be removed or changed. This allows one process to
  28. setup a socket, attach a filter, lock it then drop privileges and be
  29. assured that the filter will be kept until the socket is closed.
  30. The biggest user of this construct might be libpcap. Issuing a high-level
  31. filter command like `tcpdump -i em1 port 22` passes through the libpcap
  32. internal compiler that generates a structure that can eventually be loaded
  33. via SO_ATTACH_FILTER to the kernel. `tcpdump -i em1 port 22 -ddd`
  34. displays what is being placed into this structure.
  35. Although we were only speaking about sockets here, BPF in Linux is used
  36. in many more places. There's xt_bpf for netfilter, cls_bpf in the kernel
  37. qdisc layer, SECCOMP-BPF (SECure COMPuting [1]), and lots of other places
  38. such as team driver, PTP code, etc where BPF is being used.
  39. [1] Documentation/prctl/seccomp_filter.txt
  40. Original BPF paper:
  41. Steven McCanne and Van Jacobson. 1993. The BSD packet filter: a new
  42. architecture for user-level packet capture. In Proceedings of the
  43. USENIX Winter 1993 Conference Proceedings on USENIX Winter 1993
  44. Conference Proceedings (USENIX'93). USENIX Association, Berkeley,
  45. CA, USA, 2-2. [http://www.tcpdump.org/papers/bpf-usenix93.pdf]
  46. Structure
  47. ---------
  48. User space applications include <linux/filter.h> which contains the
  49. following relevant structures:
  50. struct sock_filter { /* Filter block */
  51. __u16 code; /* Actual filter code */
  52. __u8 jt; /* Jump true */
  53. __u8 jf; /* Jump false */
  54. __u32 k; /* Generic multiuse field */
  55. };
  56. Such a structure is assembled as an array of 4-tuples, that contains
  57. a code, jt, jf and k value. jt and jf are jump offsets and k a generic
  58. value to be used for a provided code.
  59. struct sock_fprog { /* Required for SO_ATTACH_FILTER. */
  60. unsigned short len; /* Number of filter blocks */
  61. struct sock_filter __user *filter;
  62. };
  63. For socket filtering, a pointer to this structure (as shown in
  64. follow-up example) is being passed to the kernel through setsockopt(2).
  65. Example
  66. -------
  67. #include <sys/socket.h>
  68. #include <sys/types.h>
  69. #include <arpa/inet.h>
  70. #include <linux/if_ether.h>
  71. /* ... */
  72. /* From the example above: tcpdump -i em1 port 22 -dd */
  73. struct sock_filter code[] = {
  74. { 0x28, 0, 0, 0x0000000c },
  75. { 0x15, 0, 8, 0x000086dd },
  76. { 0x30, 0, 0, 0x00000014 },
  77. { 0x15, 2, 0, 0x00000084 },
  78. { 0x15, 1, 0, 0x00000006 },
  79. { 0x15, 0, 17, 0x00000011 },
  80. { 0x28, 0, 0, 0x00000036 },
  81. { 0x15, 14, 0, 0x00000016 },
  82. { 0x28, 0, 0, 0x00000038 },
  83. { 0x15, 12, 13, 0x00000016 },
  84. { 0x15, 0, 12, 0x00000800 },
  85. { 0x30, 0, 0, 0x00000017 },
  86. { 0x15, 2, 0, 0x00000084 },
  87. { 0x15, 1, 0, 0x00000006 },
  88. { 0x15, 0, 8, 0x00000011 },
  89. { 0x28, 0, 0, 0x00000014 },
  90. { 0x45, 6, 0, 0x00001fff },
  91. { 0xb1, 0, 0, 0x0000000e },
  92. { 0x48, 0, 0, 0x0000000e },
  93. { 0x15, 2, 0, 0x00000016 },
  94. { 0x48, 0, 0, 0x00000010 },
  95. { 0x15, 0, 1, 0x00000016 },
  96. { 0x06, 0, 0, 0x0000ffff },
  97. { 0x06, 0, 0, 0x00000000 },
  98. };
  99. struct sock_fprog bpf = {
  100. .len = ARRAY_SIZE(code),
  101. .filter = code,
  102. };
  103. sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
  104. if (sock < 0)
  105. /* ... bail out ... */
  106. ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
  107. if (ret < 0)
  108. /* ... bail out ... */
  109. /* ... */
  110. close(sock);
  111. The above example code attaches a socket filter for a PF_PACKET socket
  112. in order to let all IPv4/IPv6 packets with port 22 pass. The rest will
  113. be dropped for this socket.
  114. The setsockopt(2) call to SO_DETACH_FILTER doesn't need any arguments
  115. and SO_LOCK_FILTER for preventing the filter to be detached, takes an
  116. integer value with 0 or 1.
  117. Note that socket filters are not restricted to PF_PACKET sockets only,
  118. but can also be used on other socket families.
  119. Summary of system calls:
  120. * setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &val, sizeof(val));
  121. * setsockopt(sockfd, SOL_SOCKET, SO_DETACH_FILTER, &val, sizeof(val));
  122. * setsockopt(sockfd, SOL_SOCKET, SO_LOCK_FILTER, &val, sizeof(val));
  123. Normally, most use cases for socket filtering on packet sockets will be
  124. covered by libpcap in high-level syntax, so as an application developer
  125. you should stick to that. libpcap wraps its own layer around all that.
  126. Unless i) using/linking to libpcap is not an option, ii) the required BPF
  127. filters use Linux extensions that are not supported by libpcap's compiler,
  128. iii) a filter might be more complex and not cleanly implementable with
  129. libpcap's compiler, or iv) particular filter codes should be optimized
  130. differently than libpcap's internal compiler does; then in such cases
  131. writing such a filter "by hand" can be of an alternative. For example,
  132. xt_bpf and cls_bpf users might have requirements that could result in
  133. more complex filter code, or one that cannot be expressed with libpcap
  134. (e.g. different return codes for various code paths). Moreover, BPF JIT
  135. implementors may wish to manually write test cases and thus need low-level
  136. access to BPF code as well.
  137. BPF engine and instruction set
  138. ------------------------------
  139. Under tools/net/ there's a small helper tool called bpf_asm which can
  140. be used to write low-level filters for example scenarios mentioned in the
  141. previous section. Asm-like syntax mentioned here has been implemented in
  142. bpf_asm and will be used for further explanations (instead of dealing with
  143. less readable opcodes directly, principles are the same). The syntax is
  144. closely modelled after Steven McCanne's and Van Jacobson's BPF paper.
  145. The BPF architecture consists of the following basic elements:
  146. Element Description
  147. A 32 bit wide accumulator
  148. X 32 bit wide X register
  149. M[] 16 x 32 bit wide misc registers aka "scratch memory
  150. store", addressable from 0 to 15
  151. A program, that is translated by bpf_asm into "opcodes" is an array that
  152. consists of the following elements (as already mentioned):
  153. op:16, jt:8, jf:8, k:32
  154. The element op is a 16 bit wide opcode that has a particular instruction
  155. encoded. jt and jf are two 8 bit wide jump targets, one for condition
  156. "jump if true", the other one "jump if false". Eventually, element k
  157. contains a miscellaneous argument that can be interpreted in different
  158. ways depending on the given instruction in op.
  159. The instruction set consists of load, store, branch, alu, miscellaneous
  160. and return instructions that are also represented in bpf_asm syntax. This
  161. table lists all bpf_asm instructions available resp. what their underlying
  162. opcodes as defined in linux/filter.h stand for:
  163. Instruction Addressing mode Description
  164. ld 1, 2, 3, 4, 10 Load word into A
  165. ldi 4 Load word into A
  166. ldh 1, 2 Load half-word into A
  167. ldb 1, 2 Load byte into A
  168. ldx 3, 4, 5, 10 Load word into X
  169. ldxi 4 Load word into X
  170. ldxb 5 Load byte into X
  171. st 3 Store A into M[]
  172. stx 3 Store X into M[]
  173. jmp 6 Jump to label
  174. ja 6 Jump to label
  175. jeq 7, 8 Jump on k == A
  176. jneq 8 Jump on k != A
  177. jne 8 Jump on k != A
  178. jlt 8 Jump on k < A
  179. jle 8 Jump on k <= A
  180. jgt 7, 8 Jump on k > A
  181. jge 7, 8 Jump on k >= A
  182. jset 7, 8 Jump on k & A
  183. add 0, 4 A + <x>
  184. sub 0, 4 A - <x>
  185. mul 0, 4 A * <x>
  186. div 0, 4 A / <x>
  187. mod 0, 4 A % <x>
  188. neg 0, 4 !A
  189. and 0, 4 A & <x>
  190. or 0, 4 A | <x>
  191. xor 0, 4 A ^ <x>
  192. lsh 0, 4 A << <x>
  193. rsh 0, 4 A >> <x>
  194. tax Copy A into X
  195. txa Copy X into A
  196. ret 4, 9 Return
  197. The next table shows addressing formats from the 2nd column:
  198. Addressing mode Syntax Description
  199. 0 x/%x Register X
  200. 1 [k] BHW at byte offset k in the packet
  201. 2 [x + k] BHW at the offset X + k in the packet
  202. 3 M[k] Word at offset k in M[]
  203. 4 #k Literal value stored in k
  204. 5 4*([k]&0xf) Lower nibble * 4 at byte offset k in the packet
  205. 6 L Jump label L
  206. 7 #k,Lt,Lf Jump to Lt if true, otherwise jump to Lf
  207. 8 #k,Lt Jump to Lt if predicate is true
  208. 9 a/%a Accumulator A
  209. 10 extension BPF extension
  210. The Linux kernel also has a couple of BPF extensions that are used along
  211. with the class of load instructions by "overloading" the k argument with
  212. a negative offset + a particular extension offset. The result of such BPF
  213. extensions are loaded into A.
  214. Possible BPF extensions are shown in the following table:
  215. Extension Description
  216. len skb->len
  217. proto skb->protocol
  218. type skb->pkt_type
  219. poff Payload start offset
  220. ifidx skb->dev->ifindex
  221. nla Netlink attribute of type X with offset A
  222. nlan Nested Netlink attribute of type X with offset A
  223. mark skb->mark
  224. queue skb->queue_mapping
  225. hatype skb->dev->type
  226. rxhash skb->hash
  227. cpu raw_smp_processor_id()
  228. vlan_tci vlan_tx_tag_get(skb)
  229. vlan_pr vlan_tx_tag_present(skb)
  230. rand prandom_u32()
  231. These extensions can also be prefixed with '#'.
  232. Examples for low-level BPF:
  233. ** ARP packets:
  234. ldh [12]
  235. jne #0x806, drop
  236. ret #-1
  237. drop: ret #0
  238. ** IPv4 TCP packets:
  239. ldh [12]
  240. jne #0x800, drop
  241. ldb [23]
  242. jneq #6, drop
  243. ret #-1
  244. drop: ret #0
  245. ** (Accelerated) VLAN w/ id 10:
  246. ld vlan_tci
  247. jneq #10, drop
  248. ret #-1
  249. drop: ret #0
  250. ** icmp random packet sampling, 1 in 4
  251. ldh [12]
  252. jne #0x800, drop
  253. ldb [23]
  254. jneq #1, drop
  255. # get a random uint32 number
  256. ld rand
  257. mod #4
  258. jneq #1, drop
  259. ret #-1
  260. drop: ret #0
  261. ** SECCOMP filter example:
  262. ld [4] /* offsetof(struct seccomp_data, arch) */
  263. jne #0xc000003e, bad /* AUDIT_ARCH_X86_64 */
  264. ld [0] /* offsetof(struct seccomp_data, nr) */
  265. jeq #15, good /* __NR_rt_sigreturn */
  266. jeq #231, good /* __NR_exit_group */
  267. jeq #60, good /* __NR_exit */
  268. jeq #0, good /* __NR_read */
  269. jeq #1, good /* __NR_write */
  270. jeq #5, good /* __NR_fstat */
  271. jeq #9, good /* __NR_mmap */
  272. jeq #14, good /* __NR_rt_sigprocmask */
  273. jeq #13, good /* __NR_rt_sigaction */
  274. jeq #35, good /* __NR_nanosleep */
  275. bad: ret #0 /* SECCOMP_RET_KILL */
  276. good: ret #0x7fff0000 /* SECCOMP_RET_ALLOW */
  277. The above example code can be placed into a file (here called "foo"), and
  278. then be passed to the bpf_asm tool for generating opcodes, output that xt_bpf
  279. and cls_bpf understands and can directly be loaded with. Example with above
  280. ARP code:
  281. $ ./bpf_asm foo
  282. 4,40 0 0 12,21 0 1 2054,6 0 0 4294967295,6 0 0 0,
  283. In copy and paste C-like output:
  284. $ ./bpf_asm -c foo
  285. { 0x28, 0, 0, 0x0000000c },
  286. { 0x15, 0, 1, 0x00000806 },
  287. { 0x06, 0, 0, 0xffffffff },
  288. { 0x06, 0, 0, 0000000000 },
  289. In particular, as usage with xt_bpf or cls_bpf can result in more complex BPF
  290. filters that might not be obvious at first, it's good to test filters before
  291. attaching to a live system. For that purpose, there's a small tool called
  292. bpf_dbg under tools/net/ in the kernel source directory. This debugger allows
  293. for testing BPF filters against given pcap files, single stepping through the
  294. BPF code on the pcap's packets and to do BPF machine register dumps.
  295. Starting bpf_dbg is trivial and just requires issuing:
  296. # ./bpf_dbg
  297. In case input and output do not equal stdin/stdout, bpf_dbg takes an
  298. alternative stdin source as a first argument, and an alternative stdout
  299. sink as a second one, e.g. `./bpf_dbg test_in.txt test_out.txt`.
  300. Other than that, a particular libreadline configuration can be set via
  301. file "~/.bpf_dbg_init" and the command history is stored in the file
  302. "~/.bpf_dbg_history".
  303. Interaction in bpf_dbg happens through a shell that also has auto-completion
  304. support (follow-up example commands starting with '>' denote bpf_dbg shell).
  305. The usual workflow would be to ...
  306. > 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
  307. Loads a BPF filter from standard output of bpf_asm, or transformed via
  308. e.g. `tcpdump -iem1 -ddd port 22 | tr '\n' ','`. Note that for JIT
  309. debugging (next section), this command creates a temporary socket and
  310. loads the BPF code into the kernel. Thus, this will also be useful for
  311. JIT developers.
  312. > load pcap foo.pcap
  313. Loads standard tcpdump pcap file.
  314. > run [<n>]
  315. bpf passes:1 fails:9
  316. Runs through all packets from a pcap to account how many passes and fails
  317. the filter will generate. A limit of packets to traverse can be given.
  318. > disassemble
  319. l0: ldh [12]
  320. l1: jeq #0x800, l2, l5
  321. l2: ldb [23]
  322. l3: jeq #0x1, l4, l5
  323. l4: ret #0xffff
  324. l5: ret #0
  325. Prints out BPF code disassembly.
  326. > dump
  327. /* { op, jt, jf, k }, */
  328. { 0x28, 0, 0, 0x0000000c },
  329. { 0x15, 0, 3, 0x00000800 },
  330. { 0x30, 0, 0, 0x00000017 },
  331. { 0x15, 0, 1, 0x00000001 },
  332. { 0x06, 0, 0, 0x0000ffff },
  333. { 0x06, 0, 0, 0000000000 },
  334. Prints out C-style BPF code dump.
  335. > breakpoint 0
  336. breakpoint at: l0: ldh [12]
  337. > breakpoint 1
  338. breakpoint at: l1: jeq #0x800, l2, l5
  339. ...
  340. Sets breakpoints at particular BPF instructions. Issuing a `run` command
  341. will walk through the pcap file continuing from the current packet and
  342. break when a breakpoint is being hit (another `run` will continue from
  343. the currently active breakpoint executing next instructions):
  344. > run
  345. -- register dump --
  346. pc: [0] <-- program counter
  347. code: [40] jt[0] jf[0] k[12] <-- plain BPF code of current instruction
  348. curr: l0: ldh [12] <-- disassembly of current instruction
  349. A: [00000000][0] <-- content of A (hex, decimal)
  350. X: [00000000][0] <-- content of X (hex, decimal)
  351. M[0,15]: [00000000][0] <-- folded content of M (hex, decimal)
  352. -- packet dump -- <-- Current packet from pcap (hex)
  353. len: 42
  354. 0: 00 19 cb 55 55 a4 00 14 a4 43 78 69 08 06 00 01
  355. 16: 08 00 06 04 00 01 00 14 a4 43 78 69 0a 3b 01 26
  356. 32: 00 00 00 00 00 00 0a 3b 01 01
  357. (breakpoint)
  358. >
  359. > breakpoint
  360. breakpoints: 0 1
  361. Prints currently set breakpoints.
  362. > step [-<n>, +<n>]
  363. Performs single stepping through the BPF program from the current pc
  364. offset. Thus, on each step invocation, above register dump is issued.
  365. This can go forwards and backwards in time, a plain `step` will break
  366. on the next BPF instruction, thus +1. (No `run` needs to be issued here.)
  367. > select <n>
  368. Selects a given packet from the pcap file to continue from. Thus, on
  369. the next `run` or `step`, the BPF program is being evaluated against
  370. the user pre-selected packet. Numbering starts just as in Wireshark
  371. with index 1.
  372. > quit
  373. #
  374. Exits bpf_dbg.
  375. JIT compiler
  376. ------------
  377. The Linux kernel has a built-in BPF JIT compiler for x86_64, SPARC, PowerPC,
  378. ARM, ARM64, MIPS and s390 and can be enabled through CONFIG_BPF_JIT. The JIT
  379. compiler is transparently invoked for each attached filter from user space
  380. or for internal kernel users if it has been previously enabled by root:
  381. echo 1 > /proc/sys/net/core/bpf_jit_enable
  382. For JIT developers, doing audits etc, each compile run can output the generated
  383. opcode image into the kernel log via:
  384. echo 2 > /proc/sys/net/core/bpf_jit_enable
  385. Example output from dmesg:
  386. [ 3389.935842] flen=6 proglen=70 pass=3 image=ffffffffa0069c8f
  387. [ 3389.935847] JIT code: 00000000: 55 48 89 e5 48 83 ec 60 48 89 5d f8 44 8b 4f 68
  388. [ 3389.935849] JIT code: 00000010: 44 2b 4f 6c 4c 8b 87 d8 00 00 00 be 0c 00 00 00
  389. [ 3389.935850] JIT code: 00000020: e8 1d 94 ff e0 3d 00 08 00 00 75 16 be 17 00 00
  390. [ 3389.935851] JIT code: 00000030: 00 e8 28 94 ff e0 83 f8 01 75 07 b8 ff ff 00 00
  391. [ 3389.935852] JIT code: 00000040: eb 02 31 c0 c9 c3
  392. In the kernel source tree under tools/net/, there's bpf_jit_disasm for
  393. generating disassembly out of the kernel log's hexdump:
  394. # ./bpf_jit_disasm
  395. 70 bytes emitted from JIT compiler (pass:3, flen:6)
  396. ffffffffa0069c8f + <x>:
  397. 0: push %rbp
  398. 1: mov %rsp,%rbp
  399. 4: sub $0x60,%rsp
  400. 8: mov %rbx,-0x8(%rbp)
  401. c: mov 0x68(%rdi),%r9d
  402. 10: sub 0x6c(%rdi),%r9d
  403. 14: mov 0xd8(%rdi),%r8
  404. 1b: mov $0xc,%esi
  405. 20: callq 0xffffffffe0ff9442
  406. 25: cmp $0x800,%eax
  407. 2a: jne 0x0000000000000042
  408. 2c: mov $0x17,%esi
  409. 31: callq 0xffffffffe0ff945e
  410. 36: cmp $0x1,%eax
  411. 39: jne 0x0000000000000042
  412. 3b: mov $0xffff,%eax
  413. 40: jmp 0x0000000000000044
  414. 42: xor %eax,%eax
  415. 44: leaveq
  416. 45: retq
  417. Issuing option `-o` will "annotate" opcodes to resulting assembler
  418. instructions, which can be very useful for JIT developers:
  419. # ./bpf_jit_disasm -o
  420. 70 bytes emitted from JIT compiler (pass:3, flen:6)
  421. ffffffffa0069c8f + <x>:
  422. 0: push %rbp
  423. 55
  424. 1: mov %rsp,%rbp
  425. 48 89 e5
  426. 4: sub $0x60,%rsp
  427. 48 83 ec 60
  428. 8: mov %rbx,-0x8(%rbp)
  429. 48 89 5d f8
  430. c: mov 0x68(%rdi),%r9d
  431. 44 8b 4f 68
  432. 10: sub 0x6c(%rdi),%r9d
  433. 44 2b 4f 6c
  434. 14: mov 0xd8(%rdi),%r8
  435. 4c 8b 87 d8 00 00 00
  436. 1b: mov $0xc,%esi
  437. be 0c 00 00 00
  438. 20: callq 0xffffffffe0ff9442
  439. e8 1d 94 ff e0
  440. 25: cmp $0x800,%eax
  441. 3d 00 08 00 00
  442. 2a: jne 0x0000000000000042
  443. 75 16
  444. 2c: mov $0x17,%esi
  445. be 17 00 00 00
  446. 31: callq 0xffffffffe0ff945e
  447. e8 28 94 ff e0
  448. 36: cmp $0x1,%eax
  449. 83 f8 01
  450. 39: jne 0x0000000000000042
  451. 75 07
  452. 3b: mov $0xffff,%eax
  453. b8 ff ff 00 00
  454. 40: jmp 0x0000000000000044
  455. eb 02
  456. 42: xor %eax,%eax
  457. 31 c0
  458. 44: leaveq
  459. c9
  460. 45: retq
  461. c3
  462. For BPF JIT developers, bpf_jit_disasm, bpf_asm and bpf_dbg provides a useful
  463. toolchain for developing and testing the kernel's JIT compiler.
  464. BPF kernel internals
  465. --------------------
  466. Internally, for the kernel interpreter, a different instruction set
  467. format with similar underlying principles from BPF described in previous
  468. paragraphs is being used. However, the instruction set format is modelled
  469. closer to the underlying architecture to mimic native instruction sets, so
  470. that a better performance can be achieved (more details later). This new
  471. ISA is called 'eBPF' or 'internal BPF' interchangeably. (Note: eBPF which
  472. originates from [e]xtended BPF is not the same as BPF extensions! While
  473. eBPF is an ISA, BPF extensions date back to classic BPF's 'overloading'
  474. of BPF_LD | BPF_{B,H,W} | BPF_ABS instruction.)
  475. It is designed to be JITed with one to one mapping, which can also open up
  476. the possibility for GCC/LLVM compilers to generate optimized eBPF code through
  477. an eBPF backend that performs almost as fast as natively compiled code.
  478. The new instruction set was originally designed with the possible goal in
  479. mind to write programs in "restricted C" and compile into eBPF with a optional
  480. GCC/LLVM backend, so that it can just-in-time map to modern 64-bit CPUs with
  481. minimal performance overhead over two steps, that is, C -> eBPF -> native code.
  482. Currently, the new format is being used for running user BPF programs, which
  483. includes seccomp BPF, classic socket filters, cls_bpf traffic classifier,
  484. team driver's classifier for its load-balancing mode, netfilter's xt_bpf
  485. extension, PTP dissector/classifier, and much more. They are all internally
  486. converted by the kernel into the new instruction set representation and run
  487. in the eBPF interpreter. For in-kernel handlers, this all works transparently
  488. by using bpf_prog_create() for setting up the filter, resp.
  489. bpf_prog_destroy() for destroying it. The macro
  490. BPF_PROG_RUN(filter, ctx) transparently invokes eBPF interpreter or JITed
  491. code to run the filter. 'filter' is a pointer to struct bpf_prog that we
  492. got from bpf_prog_create(), and 'ctx' the given context (e.g.
  493. skb pointer). All constraints and restrictions from bpf_check_classic() apply
  494. before a conversion to the new layout is being done behind the scenes!
  495. Currently, the classic BPF format is being used for JITing on most of the
  496. architectures. Only x86-64 performs JIT compilation from eBPF instruction set,
  497. however, future work will migrate other JIT compilers as well, so that they
  498. will profit from the very same benefits.
  499. Some core changes of the new internal format:
  500. - Number of registers increase from 2 to 10:
  501. The old format had two registers A and X, and a hidden frame pointer. The
  502. new layout extends this to be 10 internal registers and a read-only frame
  503. pointer. Since 64-bit CPUs are passing arguments to functions via registers
  504. the number of args from eBPF program to in-kernel function is restricted
  505. to 5 and one register is used to accept return value from an in-kernel
  506. function. Natively, x86_64 passes first 6 arguments in registers, aarch64/
  507. sparcv9/mips64 have 7 - 8 registers for arguments; x86_64 has 6 callee saved
  508. registers, and aarch64/sparcv9/mips64 have 11 or more callee saved registers.
  509. Therefore, eBPF calling convention is defined as:
  510. * R0 - return value from in-kernel function, and exit value for eBPF program
  511. * R1 - R5 - arguments from eBPF program to in-kernel function
  512. * R6 - R9 - callee saved registers that in-kernel function will preserve
  513. * R10 - read-only frame pointer to access stack
  514. Thus, all eBPF registers map one to one to HW registers on x86_64, aarch64,
  515. etc, and eBPF calling convention maps directly to ABIs used by the kernel on
  516. 64-bit architectures.
  517. On 32-bit architectures JIT may map programs that use only 32-bit arithmetic
  518. and may let more complex programs to be interpreted.
  519. R0 - R5 are scratch registers and eBPF program needs spill/fill them if
  520. necessary across calls. Note that there is only one eBPF program (== one
  521. eBPF main routine) and it cannot call other eBPF functions, it can only
  522. call predefined in-kernel functions, though.
  523. - Register width increases from 32-bit to 64-bit:
  524. Still, the semantics of the original 32-bit ALU operations are preserved
  525. via 32-bit subregisters. All eBPF registers are 64-bit with 32-bit lower
  526. subregisters that zero-extend into 64-bit if they are being written to.
  527. That behavior maps directly to x86_64 and arm64 subregister definition, but
  528. makes other JITs more difficult.
  529. 32-bit architectures run 64-bit internal BPF programs via interpreter.
  530. Their JITs may convert BPF programs that only use 32-bit subregisters into
  531. native instruction set and let the rest being interpreted.
  532. Operation is 64-bit, because on 64-bit architectures, pointers are also
  533. 64-bit wide, and we want to pass 64-bit values in/out of kernel functions,
  534. so 32-bit eBPF registers would otherwise require to define register-pair
  535. ABI, thus, there won't be able to use a direct eBPF register to HW register
  536. mapping and JIT would need to do combine/split/move operations for every
  537. register in and out of the function, which is complex, bug prone and slow.
  538. Another reason is the use of atomic 64-bit counters.
  539. - Conditional jt/jf targets replaced with jt/fall-through:
  540. While the original design has constructs such as "if (cond) jump_true;
  541. else jump_false;", they are being replaced into alternative constructs like
  542. "if (cond) jump_true; /* else fall-through */".
  543. - Introduces bpf_call insn and register passing convention for zero overhead
  544. calls from/to other kernel functions:
  545. Before an in-kernel function call, the internal BPF program needs to
  546. place function arguments into R1 to R5 registers to satisfy calling
  547. convention, then the interpreter will take them from registers and pass
  548. to in-kernel function. If R1 - R5 registers are mapped to CPU registers
  549. that are used for argument passing on given architecture, the JIT compiler
  550. doesn't need to emit extra moves. Function arguments will be in the correct
  551. registers and BPF_CALL instruction will be JITed as single 'call' HW
  552. instruction. This calling convention was picked to cover common call
  553. situations without performance penalty.
  554. After an in-kernel function call, R1 - R5 are reset to unreadable and R0 has
  555. a return value of the function. Since R6 - R9 are callee saved, their state
  556. is preserved across the call.
  557. For example, consider three C functions:
  558. u64 f1() { return (*_f2)(1); }
  559. u64 f2(u64 a) { return f3(a + 1, a); }
  560. u64 f3(u64 a, u64 b) { return a - b; }
  561. GCC can compile f1, f3 into x86_64:
  562. f1:
  563. movl $1, %edi
  564. movq _f2(%rip), %rax
  565. jmp *%rax
  566. f3:
  567. movq %rdi, %rax
  568. subq %rsi, %rax
  569. ret
  570. Function f2 in eBPF may look like:
  571. f2:
  572. bpf_mov R2, R1
  573. bpf_add R1, 1
  574. bpf_call f3
  575. bpf_exit
  576. If f2 is JITed and the pointer stored to '_f2'. The calls f1 -> f2 -> f3 and
  577. returns will be seamless. Without JIT, __bpf_prog_run() interpreter needs to
  578. be used to call into f2.
  579. For practical reasons all eBPF programs have only one argument 'ctx' which is
  580. already placed into R1 (e.g. on __bpf_prog_run() startup) and the programs
  581. can call kernel functions with up to 5 arguments. Calls with 6 or more arguments
  582. are currently not supported, but these restrictions can be lifted if necessary
  583. in the future.
  584. On 64-bit architectures all register map to HW registers one to one. For
  585. example, x86_64 JIT compiler can map them as ...
  586. R0 - rax
  587. R1 - rdi
  588. R2 - rsi
  589. R3 - rdx
  590. R4 - rcx
  591. R5 - r8
  592. R6 - rbx
  593. R7 - r13
  594. R8 - r14
  595. R9 - r15
  596. R10 - rbp
  597. ... since x86_64 ABI mandates rdi, rsi, rdx, rcx, r8, r9 for argument passing
  598. and rbx, r12 - r15 are callee saved.
  599. Then the following internal BPF pseudo-program:
  600. bpf_mov R6, R1 /* save ctx */
  601. bpf_mov R2, 2
  602. bpf_mov R3, 3
  603. bpf_mov R4, 4
  604. bpf_mov R5, 5
  605. bpf_call foo
  606. bpf_mov R7, R0 /* save foo() return value */
  607. bpf_mov R1, R6 /* restore ctx for next call */
  608. bpf_mov R2, 6
  609. bpf_mov R3, 7
  610. bpf_mov R4, 8
  611. bpf_mov R5, 9
  612. bpf_call bar
  613. bpf_add R0, R7
  614. bpf_exit
  615. After JIT to x86_64 may look like:
  616. push %rbp
  617. mov %rsp,%rbp
  618. sub $0x228,%rsp
  619. mov %rbx,-0x228(%rbp)
  620. mov %r13,-0x220(%rbp)
  621. mov %rdi,%rbx
  622. mov $0x2,%esi
  623. mov $0x3,%edx
  624. mov $0x4,%ecx
  625. mov $0x5,%r8d
  626. callq foo
  627. mov %rax,%r13
  628. mov %rbx,%rdi
  629. mov $0x2,%esi
  630. mov $0x3,%edx
  631. mov $0x4,%ecx
  632. mov $0x5,%r8d
  633. callq bar
  634. add %r13,%rax
  635. mov -0x228(%rbp),%rbx
  636. mov -0x220(%rbp),%r13
  637. leaveq
  638. retq
  639. Which is in this example equivalent in C to:
  640. u64 bpf_filter(u64 ctx)
  641. {
  642. return foo(ctx, 2, 3, 4, 5) + bar(ctx, 6, 7, 8, 9);
  643. }
  644. In-kernel functions foo() and bar() with prototype: u64 (*)(u64 arg1, u64
  645. arg2, u64 arg3, u64 arg4, u64 arg5); will receive arguments in proper
  646. registers and place their return value into '%rax' which is R0 in eBPF.
  647. Prologue and epilogue are emitted by JIT and are implicit in the
  648. interpreter. R0-R5 are scratch registers, so eBPF program needs to preserve
  649. them across the calls as defined by calling convention.
  650. For example the following program is invalid:
  651. bpf_mov R1, 1
  652. bpf_call foo
  653. bpf_mov R0, R1
  654. bpf_exit
  655. After the call the registers R1-R5 contain junk values and cannot be read.
  656. In the future an eBPF verifier can be used to validate internal BPF programs.
  657. Also in the new design, eBPF is limited to 4096 insns, which means that any
  658. program will terminate quickly and will only call a fixed number of kernel
  659. functions. Original BPF and the new format are two operand instructions,
  660. which helps to do one-to-one mapping between eBPF insn and x86 insn during JIT.
  661. The input context pointer for invoking the interpreter function is generic,
  662. its content is defined by a specific use case. For seccomp register R1 points
  663. to seccomp_data, for converted BPF filters R1 points to a skb.
  664. A program, that is translated internally consists of the following elements:
  665. op:16, jt:8, jf:8, k:32 ==> op:8, dst_reg:4, src_reg:4, off:16, imm:32
  666. So far 87 internal BPF instructions were implemented. 8-bit 'op' opcode field
  667. has room for new instructions. Some of them may use 16/24/32 byte encoding. New
  668. instructions must be multiple of 8 bytes to preserve backward compatibility.
  669. Internal BPF is a general purpose RISC instruction set. Not every register and
  670. every instruction are used during translation from original BPF to new format.
  671. For example, socket filters are not using 'exclusive add' instruction, but
  672. tracing filters may do to maintain counters of events, for example. Register R9
  673. is not used by socket filters either, but more complex filters may be running
  674. out of registers and would have to resort to spill/fill to stack.
  675. Internal BPF can used as generic assembler for last step performance
  676. optimizations, socket filters and seccomp are using it as assembler. Tracing
  677. filters may use it as assembler to generate code from kernel. In kernel usage
  678. may not be bounded by security considerations, since generated internal BPF code
  679. may be optimizing internal code path and not being exposed to the user space.
  680. Safety of internal BPF can come from a verifier (TBD). In such use cases as
  681. described, it may be used as safe instruction set.
  682. Just like the original BPF, the new format runs within a controlled environment,
  683. is deterministic and the kernel can easily prove that. The safety of the program
  684. can be determined in two steps: first step does depth-first-search to disallow
  685. loops and other CFG validation; second step starts from the first insn and
  686. descends all possible paths. It simulates execution of every insn and observes
  687. the state change of registers and stack.
  688. eBPF opcode encoding
  689. --------------------
  690. eBPF is reusing most of the opcode encoding from classic to simplify conversion
  691. of classic BPF to eBPF. For arithmetic and jump instructions the 8-bit 'code'
  692. field is divided into three parts:
  693. +----------------+--------+--------------------+
  694. | 4 bits | 1 bit | 3 bits |
  695. | operation code | source | instruction class |
  696. +----------------+--------+--------------------+
  697. (MSB) (LSB)
  698. Three LSB bits store instruction class which is one of:
  699. Classic BPF classes: eBPF classes:
  700. BPF_LD 0x00 BPF_LD 0x00
  701. BPF_LDX 0x01 BPF_LDX 0x01
  702. BPF_ST 0x02 BPF_ST 0x02
  703. BPF_STX 0x03 BPF_STX 0x03
  704. BPF_ALU 0x04 BPF_ALU 0x04
  705. BPF_JMP 0x05 BPF_JMP 0x05
  706. BPF_RET 0x06 [ class 6 unused, for future if needed ]
  707. BPF_MISC 0x07 BPF_ALU64 0x07
  708. When BPF_CLASS(code) == BPF_ALU or BPF_JMP, 4th bit encodes source operand ...
  709. BPF_K 0x00
  710. BPF_X 0x08
  711. * in classic BPF, this means:
  712. BPF_SRC(code) == BPF_X - use register X as source operand
  713. BPF_SRC(code) == BPF_K - use 32-bit immediate as source operand
  714. * in eBPF, this means:
  715. BPF_SRC(code) == BPF_X - use 'src_reg' register as source operand
  716. BPF_SRC(code) == BPF_K - use 32-bit immediate as source operand
  717. ... and four MSB bits store operation code.
  718. If BPF_CLASS(code) == BPF_ALU or BPF_ALU64 [ in eBPF ], BPF_OP(code) is one of:
  719. BPF_ADD 0x00
  720. BPF_SUB 0x10
  721. BPF_MUL 0x20
  722. BPF_DIV 0x30
  723. BPF_OR 0x40
  724. BPF_AND 0x50
  725. BPF_LSH 0x60
  726. BPF_RSH 0x70
  727. BPF_NEG 0x80
  728. BPF_MOD 0x90
  729. BPF_XOR 0xa0
  730. BPF_MOV 0xb0 /* eBPF only: mov reg to reg */
  731. BPF_ARSH 0xc0 /* eBPF only: sign extending shift right */
  732. BPF_END 0xd0 /* eBPF only: endianness conversion */
  733. If BPF_CLASS(code) == BPF_JMP, BPF_OP(code) is one of:
  734. BPF_JA 0x00
  735. BPF_JEQ 0x10
  736. BPF_JGT 0x20
  737. BPF_JGE 0x30
  738. BPF_JSET 0x40
  739. BPF_JNE 0x50 /* eBPF only: jump != */
  740. BPF_JSGT 0x60 /* eBPF only: signed '>' */
  741. BPF_JSGE 0x70 /* eBPF only: signed '>=' */
  742. BPF_CALL 0x80 /* eBPF only: function call */
  743. BPF_EXIT 0x90 /* eBPF only: function return */
  744. So BPF_ADD | BPF_X | BPF_ALU means 32-bit addition in both classic BPF
  745. and eBPF. There are only two registers in classic BPF, so it means A += X.
  746. In eBPF it means dst_reg = (u32) dst_reg + (u32) src_reg; similarly,
  747. BPF_XOR | BPF_K | BPF_ALU means A ^= imm32 in classic BPF and analogous
  748. src_reg = (u32) src_reg ^ (u32) imm32 in eBPF.
  749. Classic BPF is using BPF_MISC class to represent A = X and X = A moves.
  750. eBPF is using BPF_MOV | BPF_X | BPF_ALU code instead. Since there are no
  751. BPF_MISC operations in eBPF, the class 7 is used as BPF_ALU64 to mean
  752. exactly the same operations as BPF_ALU, but with 64-bit wide operands
  753. instead. So BPF_ADD | BPF_X | BPF_ALU64 means 64-bit addition, i.e.:
  754. dst_reg = dst_reg + src_reg
  755. Classic BPF wastes the whole BPF_RET class to represent a single 'ret'
  756. operation. Classic BPF_RET | BPF_K means copy imm32 into return register
  757. and perform function exit. eBPF is modeled to match CPU, so BPF_JMP | BPF_EXIT
  758. in eBPF means function exit only. The eBPF program needs to store return
  759. value into register R0 before doing a BPF_EXIT. Class 6 in eBPF is currently
  760. unused and reserved for future use.
  761. For load and store instructions the 8-bit 'code' field is divided as:
  762. +--------+--------+-------------------+
  763. | 3 bits | 2 bits | 3 bits |
  764. | mode | size | instruction class |
  765. +--------+--------+-------------------+
  766. (MSB) (LSB)
  767. Size modifier is one of ...
  768. BPF_W 0x00 /* word */
  769. BPF_H 0x08 /* half word */
  770. BPF_B 0x10 /* byte */
  771. BPF_DW 0x18 /* eBPF only, double word */
  772. ... which encodes size of load/store operation:
  773. B - 1 byte
  774. H - 2 byte
  775. W - 4 byte
  776. DW - 8 byte (eBPF only)
  777. Mode modifier is one of:
  778. BPF_IMM 0x00 /* used for 32-bit mov in classic BPF and 64-bit in eBPF */
  779. BPF_ABS 0x20
  780. BPF_IND 0x40
  781. BPF_MEM 0x60
  782. BPF_LEN 0x80 /* classic BPF only, reserved in eBPF */
  783. BPF_MSH 0xa0 /* classic BPF only, reserved in eBPF */
  784. BPF_XADD 0xc0 /* eBPF only, exclusive add */
  785. eBPF has two non-generic instructions: (BPF_ABS | <size> | BPF_LD) and
  786. (BPF_IND | <size> | BPF_LD) which are used to access packet data.
  787. They had to be carried over from classic to have strong performance of
  788. socket filters running in eBPF interpreter. These instructions can only
  789. be used when interpreter context is a pointer to 'struct sk_buff' and
  790. have seven implicit operands. Register R6 is an implicit input that must
  791. contain pointer to sk_buff. Register R0 is an implicit output which contains
  792. the data fetched from the packet. Registers R1-R5 are scratch registers
  793. and must not be used to store the data across BPF_ABS | BPF_LD or
  794. BPF_IND | BPF_LD instructions.
  795. These instructions have implicit program exit condition as well. When
  796. eBPF program is trying to access the data beyond the packet boundary,
  797. the interpreter will abort the execution of the program. JIT compilers
  798. therefore must preserve this property. src_reg and imm32 fields are
  799. explicit inputs to these instructions.
  800. For example:
  801. BPF_IND | BPF_W | BPF_LD means:
  802. R0 = ntohl(*(u32 *) (((struct sk_buff *) R6)->data + src_reg + imm32))
  803. and R1 - R5 were scratched.
  804. Unlike classic BPF instruction set, eBPF has generic load/store operations:
  805. BPF_MEM | <size> | BPF_STX: *(size *) (dst_reg + off) = src_reg
  806. BPF_MEM | <size> | BPF_ST: *(size *) (dst_reg + off) = imm32
  807. BPF_MEM | <size> | BPF_LDX: dst_reg = *(size *) (src_reg + off)
  808. BPF_XADD | BPF_W | BPF_STX: lock xadd *(u32 *)(dst_reg + off16) += src_reg
  809. BPF_XADD | BPF_DW | BPF_STX: lock xadd *(u64 *)(dst_reg + off16) += src_reg
  810. Where size is one of: BPF_B or BPF_H or BPF_W or BPF_DW. Note that 1 and
  811. 2 byte atomic increments are not supported.
  812. eBPF has one 16-byte instruction: BPF_LD | BPF_DW | BPF_IMM which consists
  813. of two consecutive 'struct bpf_insn' 8-byte blocks and interpreted as single
  814. instruction that loads 64-bit immediate value into a dst_reg.
  815. Classic BPF has similar instruction: BPF_LD | BPF_W | BPF_IMM which loads
  816. 32-bit immediate value into a register.
  817. eBPF verifier
  818. -------------
  819. The safety of the eBPF program is determined in two steps.
  820. First step does DAG check to disallow loops and other CFG validation.
  821. In particular it will detect programs that have unreachable instructions.
  822. (though classic BPF checker allows them)
  823. Second step starts from the first insn and descends all possible paths.
  824. It simulates execution of every insn and observes the state change of
  825. registers and stack.
  826. At the start of the program the register R1 contains a pointer to context
  827. and has type PTR_TO_CTX.
  828. If verifier sees an insn that does R2=R1, then R2 has now type
  829. PTR_TO_CTX as well and can be used on the right hand side of expression.
  830. If R1=PTR_TO_CTX and insn is R2=R1+R1, then R2=UNKNOWN_VALUE,
  831. since addition of two valid pointers makes invalid pointer.
  832. (In 'secure' mode verifier will reject any type of pointer arithmetic to make
  833. sure that kernel addresses don't leak to unprivileged users)
  834. If register was never written to, it's not readable:
  835. bpf_mov R0 = R2
  836. bpf_exit
  837. will be rejected, since R2 is unreadable at the start of the program.
  838. After kernel function call, R1-R5 are reset to unreadable and
  839. R0 has a return type of the function.
  840. Since R6-R9 are callee saved, their state is preserved across the call.
  841. bpf_mov R6 = 1
  842. bpf_call foo
  843. bpf_mov R0 = R6
  844. bpf_exit
  845. is a correct program. If there was R1 instead of R6, it would have
  846. been rejected.
  847. load/store instructions are allowed only with registers of valid types, which
  848. are PTR_TO_CTX, PTR_TO_MAP, FRAME_PTR. They are bounds and alignment checked.
  849. For example:
  850. bpf_mov R1 = 1
  851. bpf_mov R2 = 2
  852. bpf_xadd *(u32 *)(R1 + 3) += R2
  853. bpf_exit
  854. will be rejected, since R1 doesn't have a valid pointer type at the time of
  855. execution of instruction bpf_xadd.
  856. At the start R1 type is PTR_TO_CTX (a pointer to generic 'struct bpf_context')
  857. A callback is used to customize verifier to restrict eBPF program access to only
  858. certain fields within ctx structure with specified size and alignment.
  859. For example, the following insn:
  860. bpf_ld R0 = *(u32 *)(R6 + 8)
  861. intends to load a word from address R6 + 8 and store it into R0
  862. If R6=PTR_TO_CTX, via is_valid_access() callback the verifier will know
  863. that offset 8 of size 4 bytes can be accessed for reading, otherwise
  864. the verifier will reject the program.
  865. If R6=FRAME_PTR, then access should be aligned and be within
  866. stack bounds, which are [-MAX_BPF_STACK, 0). In this example offset is 8,
  867. so it will fail verification, since it's out of bounds.
  868. The verifier will allow eBPF program to read data from stack only after
  869. it wrote into it.
  870. Classic BPF verifier does similar check with M[0-15] memory slots.
  871. For example:
  872. bpf_ld R0 = *(u32 *)(R10 - 4)
  873. bpf_exit
  874. is invalid program.
  875. Though R10 is correct read-only register and has type FRAME_PTR
  876. and R10 - 4 is within stack bounds, there were no stores into that location.
  877. Pointer register spill/fill is tracked as well, since four (R6-R9)
  878. callee saved registers may not be enough for some programs.
  879. Allowed function calls are customized with bpf_verifier_ops->get_func_proto()
  880. The eBPF verifier will check that registers match argument constraints.
  881. After the call register R0 will be set to return type of the function.
  882. Function calls is a main mechanism to extend functionality of eBPF programs.
  883. Socket filters may let programs to call one set of functions, whereas tracing
  884. filters may allow completely different set.
  885. If a function made accessible to eBPF program, it needs to be thought through
  886. from safety point of view. The verifier will guarantee that the function is
  887. called with valid arguments.
  888. seccomp vs socket filters have different security restrictions for classic BPF.
  889. Seccomp solves this by two stage verifier: classic BPF verifier is followed
  890. by seccomp verifier. In case of eBPF one configurable verifier is shared for
  891. all use cases.
  892. See details of eBPF verifier in kernel/bpf/verifier.c
  893. eBPF maps
  894. ---------
  895. 'maps' is a generic storage of different types for sharing data between kernel
  896. and userspace.
  897. The maps are accessed from user space via BPF syscall, which has commands:
  898. - create a map with given type and attributes
  899. map_fd = bpf(BPF_MAP_CREATE, union bpf_attr *attr, u32 size)
  900. using attr->map_type, attr->key_size, attr->value_size, attr->max_entries
  901. returns process-local file descriptor or negative error
  902. - lookup key in a given map
  903. err = bpf(BPF_MAP_LOOKUP_ELEM, union bpf_attr *attr, u32 size)
  904. using attr->map_fd, attr->key, attr->value
  905. returns zero and stores found elem into value or negative error
  906. - create or update key/value pair in a given map
  907. err = bpf(BPF_MAP_UPDATE_ELEM, union bpf_attr *attr, u32 size)
  908. using attr->map_fd, attr->key, attr->value
  909. returns zero or negative error
  910. - find and delete element by key in a given map
  911. err = bpf(BPF_MAP_DELETE_ELEM, union bpf_attr *attr, u32 size)
  912. using attr->map_fd, attr->key
  913. - to delete map: close(fd)
  914. Exiting process will delete maps automatically
  915. userspace programs use this syscall to create/access maps that eBPF programs
  916. are concurrently updating.
  917. maps can have different types: hash, array, bloom filter, radix-tree, etc.
  918. The map is defined by:
  919. . type
  920. . max number of elements
  921. . key size in bytes
  922. . value size in bytes
  923. Understanding eBPF verifier messages
  924. ------------------------------------
  925. The following are few examples of invalid eBPF programs and verifier error
  926. messages as seen in the log:
  927. Program with unreachable instructions:
  928. static struct bpf_insn prog[] = {
  929. BPF_EXIT_INSN(),
  930. BPF_EXIT_INSN(),
  931. };
  932. Error:
  933. unreachable insn 1
  934. Program that reads uninitialized register:
  935. BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
  936. BPF_EXIT_INSN(),
  937. Error:
  938. 0: (bf) r0 = r2
  939. R2 !read_ok
  940. Program that doesn't initialize R0 before exiting:
  941. BPF_MOV64_REG(BPF_REG_2, BPF_REG_1),
  942. BPF_EXIT_INSN(),
  943. Error:
  944. 0: (bf) r2 = r1
  945. 1: (95) exit
  946. R0 !read_ok
  947. Program that accesses stack out of bounds:
  948. BPF_ST_MEM(BPF_DW, BPF_REG_10, 8, 0),
  949. BPF_EXIT_INSN(),
  950. Error:
  951. 0: (7a) *(u64 *)(r10 +8) = 0
  952. invalid stack off=8 size=8
  953. Program that doesn't initialize stack before passing its address into function:
  954. BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
  955. BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
  956. BPF_LD_MAP_FD(BPF_REG_1, 0),
  957. BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  958. BPF_EXIT_INSN(),
  959. Error:
  960. 0: (bf) r2 = r10
  961. 1: (07) r2 += -8
  962. 2: (b7) r1 = 0x0
  963. 3: (85) call 1
  964. invalid indirect read from stack off -8+0 size 8
  965. Program that uses invalid map_fd=0 while calling to map_lookup_elem() function:
  966. BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
  967. BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
  968. BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
  969. BPF_LD_MAP_FD(BPF_REG_1, 0),
  970. BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  971. BPF_EXIT_INSN(),
  972. Error:
  973. 0: (7a) *(u64 *)(r10 -8) = 0
  974. 1: (bf) r2 = r10
  975. 2: (07) r2 += -8
  976. 3: (b7) r1 = 0x0
  977. 4: (85) call 1
  978. fd 0 is not pointing to valid bpf_map
  979. Program that doesn't check return value of map_lookup_elem() before accessing
  980. map element:
  981. BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
  982. BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
  983. BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
  984. BPF_LD_MAP_FD(BPF_REG_1, 0),
  985. BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  986. BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 0),
  987. BPF_EXIT_INSN(),
  988. Error:
  989. 0: (7a) *(u64 *)(r10 -8) = 0
  990. 1: (bf) r2 = r10
  991. 2: (07) r2 += -8
  992. 3: (b7) r1 = 0x0
  993. 4: (85) call 1
  994. 5: (7a) *(u64 *)(r0 +0) = 0
  995. R0 invalid mem access 'map_value_or_null'
  996. Program that correctly checks map_lookup_elem() returned value for NULL, but
  997. accesses the memory with incorrect alignment:
  998. BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
  999. BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
  1000. BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
  1001. BPF_LD_MAP_FD(BPF_REG_1, 0),
  1002. BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  1003. BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 1),
  1004. BPF_ST_MEM(BPF_DW, BPF_REG_0, 4, 0),
  1005. BPF_EXIT_INSN(),
  1006. Error:
  1007. 0: (7a) *(u64 *)(r10 -8) = 0
  1008. 1: (bf) r2 = r10
  1009. 2: (07) r2 += -8
  1010. 3: (b7) r1 = 1
  1011. 4: (85) call 1
  1012. 5: (15) if r0 == 0x0 goto pc+1
  1013. R0=map_ptr R10=fp
  1014. 6: (7a) *(u64 *)(r0 +4) = 0
  1015. misaligned access off 4 size 8
  1016. Program that correctly checks map_lookup_elem() returned value for NULL and
  1017. accesses memory with correct alignment in one side of 'if' branch, but fails
  1018. to do so in the other side of 'if' branch:
  1019. BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
  1020. BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
  1021. BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
  1022. BPF_LD_MAP_FD(BPF_REG_1, 0),
  1023. BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  1024. BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2),
  1025. BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 0),
  1026. BPF_EXIT_INSN(),
  1027. BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 1),
  1028. BPF_EXIT_INSN(),
  1029. Error:
  1030. 0: (7a) *(u64 *)(r10 -8) = 0
  1031. 1: (bf) r2 = r10
  1032. 2: (07) r2 += -8
  1033. 3: (b7) r1 = 1
  1034. 4: (85) call 1
  1035. 5: (15) if r0 == 0x0 goto pc+2
  1036. R0=map_ptr R10=fp
  1037. 6: (7a) *(u64 *)(r0 +0) = 0
  1038. 7: (95) exit
  1039. from 5 to 8: R0=imm0 R10=fp
  1040. 8: (7a) *(u64 *)(r0 +0) = 1
  1041. R0 invalid mem access 'imm'
  1042. Testing
  1043. -------
  1044. Next to the BPF toolchain, the kernel also ships a test module that contains
  1045. various test cases for classic and internal BPF that can be executed against
  1046. the BPF interpreter and JIT compiler. It can be found in lib/test_bpf.c and
  1047. enabled via Kconfig:
  1048. CONFIG_TEST_BPF=m
  1049. After the module has been built and installed, the test suite can be executed
  1050. via insmod or modprobe against 'test_bpf' module. Results of the test cases
  1051. including timings in nsec can be found in the kernel log (dmesg).
  1052. Misc
  1053. ----
  1054. Also trinity, the Linux syscall fuzzer, has built-in support for BPF and
  1055. SECCOMP-BPF kernel fuzzing.
  1056. Written by
  1057. ----------
  1058. The document was written in the hope that it is found useful and in order
  1059. to give potential BPF hackers or security auditors a better overview of
  1060. the underlying architecture.
  1061. Jay Schulist <jschlst@samba.org>
  1062. Daniel Borkmann <dborkman@redhat.com>
  1063. Alexei Starovoitov <ast@plumgrid.com>