filter.txt 47 KB

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