map_sockmap.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. .. SPDX-License-Identifier: GPL-2.0-only
  2. .. Copyright Red Hat
  3. ==============================================
  4. BPF_MAP_TYPE_SOCKMAP and BPF_MAP_TYPE_SOCKHASH
  5. ==============================================
  6. .. note::
  7. - ``BPF_MAP_TYPE_SOCKMAP`` was introduced in kernel version 4.14
  8. - ``BPF_MAP_TYPE_SOCKHASH`` was introduced in kernel version 4.18
  9. ``BPF_MAP_TYPE_SOCKMAP`` and ``BPF_MAP_TYPE_SOCKHASH`` maps can be used to
  10. redirect skbs between sockets or to apply policy at the socket level based on
  11. the result of a BPF (verdict) program with the help of the BPF helpers
  12. ``bpf_sk_redirect_map()``, ``bpf_sk_redirect_hash()``,
  13. ``bpf_msg_redirect_map()`` and ``bpf_msg_redirect_hash()``.
  14. ``BPF_MAP_TYPE_SOCKMAP`` is backed by an array that uses an integer key as the
  15. index to look up a reference to a ``struct sock``. The map values are socket
  16. descriptors. Similarly, ``BPF_MAP_TYPE_SOCKHASH`` is a hash backed BPF map that
  17. holds references to sockets via their socket descriptors.
  18. .. note::
  19. The value type is either __u32 or __u64; the latter (__u64) is to support
  20. returning socket cookies to userspace. Returning the ``struct sock *`` that
  21. the map holds to user-space is neither safe nor useful.
  22. These maps may have BPF programs attached to them, specifically a parser program
  23. and a verdict program. The parser program determines how much data has been
  24. parsed and therefore how much data needs to be queued to come to a verdict. The
  25. verdict program is essentially the redirect program and can return a verdict
  26. of ``__SK_DROP``, ``__SK_PASS``, or ``__SK_REDIRECT``.
  27. When a socket is inserted into one of these maps, its socket callbacks are
  28. replaced and a ``struct sk_psock`` is attached to it. Additionally, this
  29. ``sk_psock`` inherits the programs that are attached to the map.
  30. A sock object may be in multiple maps, but can only inherit a single
  31. parse or verdict program. If adding a sock object to a map would result
  32. in having multiple parser programs the update will return an EBUSY error.
  33. The supported programs to attach to these maps are:
  34. .. code-block:: c
  35. struct sk_psock_progs {
  36. struct bpf_prog *msg_parser;
  37. struct bpf_prog *stream_parser;
  38. struct bpf_prog *stream_verdict;
  39. struct bpf_prog *skb_verdict;
  40. };
  41. .. note::
  42. Users are not allowed to attach ``stream_verdict`` and ``skb_verdict``
  43. programs to the same map.
  44. The attach types for the map programs are:
  45. - ``msg_parser`` program - ``BPF_SK_MSG_VERDICT``.
  46. - ``stream_parser`` program - ``BPF_SK_SKB_STREAM_PARSER``.
  47. - ``stream_verdict`` program - ``BPF_SK_SKB_STREAM_VERDICT``.
  48. - ``skb_verdict`` program - ``BPF_SK_SKB_VERDICT``.
  49. There are additional helpers available to use with the parser and verdict
  50. programs: ``bpf_msg_apply_bytes()`` and ``bpf_msg_cork_bytes()``. With
  51. ``bpf_msg_apply_bytes()`` BPF programs can tell the infrastructure how many
  52. bytes the given verdict should apply to. The helper ``bpf_msg_cork_bytes()``
  53. handles a different case where a BPF program cannot reach a verdict on a msg
  54. until it receives more bytes AND the program doesn't want to forward the packet
  55. until it is known to be good.
  56. Finally, the helpers ``bpf_msg_pull_data()`` and ``bpf_msg_push_data()`` are
  57. available to ``BPF_PROG_TYPE_SK_MSG`` BPF programs to pull in data and set the
  58. start and end pointers to given values or to add metadata to the ``struct
  59. sk_msg_buff *msg``.
  60. All these helpers will be described in more detail below.
  61. Usage
  62. =====
  63. Kernel BPF
  64. ----------
  65. bpf_msg_redirect_map()
  66. ^^^^^^^^^^^^^^^^^^^^^^
  67. .. code-block:: c
  68. long bpf_msg_redirect_map(struct sk_msg_buff *msg, struct bpf_map *map, u32 key, u64 flags)
  69. This helper is used in programs implementing policies at the socket level. If
  70. the message ``msg`` is allowed to pass (i.e., if the verdict BPF program
  71. returns ``SK_PASS``), redirect it to the socket referenced by ``map`` (of type
  72. ``BPF_MAP_TYPE_SOCKMAP``) at index ``key``. Both ingress and egress interfaces
  73. can be used for redirection. The ``BPF_F_INGRESS`` value in ``flags`` is used
  74. to select the ingress path otherwise the egress path is selected. This is the
  75. only flag supported for now.
  76. Returns ``SK_PASS`` on success, or ``SK_DROP`` on error.
  77. bpf_sk_redirect_map()
  78. ^^^^^^^^^^^^^^^^^^^^^
  79. .. code-block:: c
  80. long bpf_sk_redirect_map(struct sk_buff *skb, struct bpf_map *map, u32 key u64 flags)
  81. Redirect the packet to the socket referenced by ``map`` (of type
  82. ``BPF_MAP_TYPE_SOCKMAP``) at index ``key``. Both ingress and egress interfaces
  83. can be used for redirection. The ``BPF_F_INGRESS`` value in ``flags`` is used
  84. to select the ingress path otherwise the egress path is selected. This is the
  85. only flag supported for now.
  86. Returns ``SK_PASS`` on success, or ``SK_DROP`` on error.
  87. bpf_map_lookup_elem()
  88. ^^^^^^^^^^^^^^^^^^^^^
  89. .. code-block:: c
  90. void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
  91. socket entries of type ``struct sock *`` can be retrieved using the
  92. ``bpf_map_lookup_elem()`` helper.
  93. bpf_sock_map_update()
  94. ^^^^^^^^^^^^^^^^^^^^^
  95. .. code-block:: c
  96. long bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags)
  97. Add an entry to, or update a ``map`` referencing sockets. The ``skops`` is used
  98. as a new value for the entry associated to ``key``. The ``flags`` argument can
  99. be one of the following:
  100. - ``BPF_ANY``: Create a new element or update an existing element.
  101. - ``BPF_NOEXIST``: Create a new element only if it did not exist.
  102. - ``BPF_EXIST``: Update an existing element.
  103. If the ``map`` has BPF programs (parser and verdict), those will be inherited
  104. by the socket being added. If the socket is already attached to BPF programs,
  105. this results in an error.
  106. Returns 0 on success, or a negative error in case of failure.
  107. bpf_sock_hash_update()
  108. ^^^^^^^^^^^^^^^^^^^^^^
  109. .. code-block:: c
  110. long bpf_sock_hash_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags)
  111. Add an entry to, or update a sockhash ``map`` referencing sockets. The ``skops``
  112. is used as a new value for the entry associated to ``key``.
  113. The ``flags`` argument can be one of the following:
  114. - ``BPF_ANY``: Create a new element or update an existing element.
  115. - ``BPF_NOEXIST``: Create a new element only if it did not exist.
  116. - ``BPF_EXIST``: Update an existing element.
  117. If the ``map`` has BPF programs (parser and verdict), those will be inherited
  118. by the socket being added. If the socket is already attached to BPF programs,
  119. this results in an error.
  120. Returns 0 on success, or a negative error in case of failure.
  121. bpf_msg_redirect_hash()
  122. ^^^^^^^^^^^^^^^^^^^^^^^
  123. .. code-block:: c
  124. long bpf_msg_redirect_hash(struct sk_msg_buff *msg, struct bpf_map *map, void *key, u64 flags)
  125. This helper is used in programs implementing policies at the socket level. If
  126. the message ``msg`` is allowed to pass (i.e., if the verdict BPF program returns
  127. ``SK_PASS``), redirect it to the socket referenced by ``map`` (of type
  128. ``BPF_MAP_TYPE_SOCKHASH``) using hash ``key``. Both ingress and egress
  129. interfaces can be used for redirection. The ``BPF_F_INGRESS`` value in
  130. ``flags`` is used to select the ingress path otherwise the egress path is
  131. selected. This is the only flag supported for now.
  132. Returns ``SK_PASS`` on success, or ``SK_DROP`` on error.
  133. bpf_sk_redirect_hash()
  134. ^^^^^^^^^^^^^^^^^^^^^^
  135. .. code-block:: c
  136. long bpf_sk_redirect_hash(struct sk_buff *skb, struct bpf_map *map, void *key, u64 flags)
  137. This helper is used in programs implementing policies at the skb socket level.
  138. If the sk_buff ``skb`` is allowed to pass (i.e., if the verdict BPF program
  139. returns ``SK_PASS``), redirect it to the socket referenced by ``map`` (of type
  140. ``BPF_MAP_TYPE_SOCKHASH``) using hash ``key``. Both ingress and egress
  141. interfaces can be used for redirection. The ``BPF_F_INGRESS`` value in
  142. ``flags`` is used to select the ingress path otherwise the egress path is
  143. selected. This is the only flag supported for now.
  144. Returns ``SK_PASS`` on success, or ``SK_DROP`` on error.
  145. bpf_msg_apply_bytes()
  146. ^^^^^^^^^^^^^^^^^^^^^^
  147. .. code-block:: c
  148. long bpf_msg_apply_bytes(struct sk_msg_buff *msg, u32 bytes)
  149. For socket policies, apply the verdict of the BPF program to the next (number
  150. of ``bytes``) of message ``msg``. For example, this helper can be used in the
  151. following cases:
  152. - A single ``sendmsg()`` or ``sendfile()`` system call contains multiple
  153. logical messages that the BPF program is supposed to read and for which it
  154. should apply a verdict.
  155. - A BPF program only cares to read the first ``bytes`` of a ``msg``. If the
  156. message has a large payload, then setting up and calling the BPF program
  157. repeatedly for all bytes, even though the verdict is already known, would
  158. create unnecessary overhead.
  159. Returns 0
  160. bpf_msg_cork_bytes()
  161. ^^^^^^^^^^^^^^^^^^^^^^
  162. .. code-block:: c
  163. long bpf_msg_cork_bytes(struct sk_msg_buff *msg, u32 bytes)
  164. For socket policies, prevent the execution of the verdict BPF program for
  165. message ``msg`` until the number of ``bytes`` have been accumulated.
  166. This can be used when one needs a specific number of bytes before a verdict can
  167. be assigned, even if the data spans multiple ``sendmsg()`` or ``sendfile()``
  168. calls.
  169. Returns 0
  170. bpf_msg_pull_data()
  171. ^^^^^^^^^^^^^^^^^^^^^^
  172. .. code-block:: c
  173. long bpf_msg_pull_data(struct sk_msg_buff *msg, u32 start, u32 end, u64 flags)
  174. For socket policies, pull in non-linear data from user space for ``msg`` and set
  175. pointers ``msg->data`` and ``msg->data_end`` to ``start`` and ``end`` bytes
  176. offsets into ``msg``, respectively.
  177. If a program of type ``BPF_PROG_TYPE_SK_MSG`` is run on a ``msg`` it can only
  178. parse data that the (``data``, ``data_end``) pointers have already consumed.
  179. For ``sendmsg()`` hooks this is likely the first scatterlist element. But for
  180. calls relying on MSG_SPLICE_PAGES (e.g., ``sendfile()``) this will be the
  181. range (**0**, **0**) because the data is shared with user space and by default
  182. the objective is to avoid allowing user space to modify data while (or after)
  183. BPF verdict is being decided. This helper can be used to pull in data and to
  184. set the start and end pointers to given values. Data will be copied if
  185. necessary (i.e., if data was not linear and if start and end pointers do not
  186. point to the same chunk).
  187. A call to this helper is susceptible to change the underlying packet buffer.
  188. Therefore, at load time, all checks on pointers previously done by the verifier
  189. are invalidated and must be performed again, if the helper is used in
  190. combination with direct packet access.
  191. All values for ``flags`` are reserved for future usage, and must be left at
  192. zero.
  193. Returns 0 on success, or a negative error in case of failure.
  194. bpf_map_lookup_elem()
  195. ^^^^^^^^^^^^^^^^^^^^^
  196. .. code-block:: c
  197. void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
  198. Look up a socket entry in the sockmap or sockhash map.
  199. Returns the socket entry associated to ``key``, or NULL if no entry was found.
  200. bpf_map_update_elem()
  201. ^^^^^^^^^^^^^^^^^^^^^
  202. .. code-block:: c
  203. long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags)
  204. Add or update a socket entry in a sockmap or sockhash.
  205. The flags argument can be one of the following:
  206. - BPF_ANY: Create a new element or update an existing element.
  207. - BPF_NOEXIST: Create a new element only if it did not exist.
  208. - BPF_EXIST: Update an existing element.
  209. Returns 0 on success, or a negative error in case of failure.
  210. bpf_map_delete_elem()
  211. ^^^^^^^^^^^^^^^^^^^^^^
  212. .. code-block:: c
  213. long bpf_map_delete_elem(struct bpf_map *map, const void *key)
  214. Delete a socket entry from a sockmap or a sockhash.
  215. Returns 0 on success, or a negative error in case of failure.
  216. User space
  217. ----------
  218. bpf_map_update_elem()
  219. ^^^^^^^^^^^^^^^^^^^^^
  220. .. code-block:: c
  221. int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags)
  222. Sockmap entries can be added or updated using the ``bpf_map_update_elem()``
  223. function. The ``key`` parameter is the index value of the sockmap array. And the
  224. ``value`` parameter is the FD value of that socket.
  225. Under the hood, the sockmap update function uses the socket FD value to
  226. retrieve the associated socket and its attached psock.
  227. The flags argument can be one of the following:
  228. - BPF_ANY: Create a new element or update an existing element.
  229. - BPF_NOEXIST: Create a new element only if it did not exist.
  230. - BPF_EXIST: Update an existing element.
  231. bpf_map_lookup_elem()
  232. ^^^^^^^^^^^^^^^^^^^^^
  233. .. code-block:: c
  234. int bpf_map_lookup_elem(int fd, const void *key, void *value)
  235. Sockmap entries can be retrieved using the ``bpf_map_lookup_elem()`` function.
  236. .. note::
  237. The entry returned is a socket cookie rather than a socket itself.
  238. bpf_map_delete_elem()
  239. ^^^^^^^^^^^^^^^^^^^^^
  240. .. code-block:: c
  241. int bpf_map_delete_elem(int fd, const void *key)
  242. Sockmap entries can be deleted using the ``bpf_map_delete_elem()``
  243. function.
  244. Returns 0 on success, or negative error in case of failure.
  245. Examples
  246. ========
  247. Kernel BPF
  248. ----------
  249. Several examples of the use of sockmap APIs can be found in:
  250. - `tools/testing/selftests/bpf/progs/test_sockmap_kern.h`_
  251. - `tools/testing/selftests/bpf/progs/sockmap_parse_prog.c`_
  252. - `tools/testing/selftests/bpf/progs/sockmap_verdict_prog.c`_
  253. - `tools/testing/selftests/bpf/progs/test_sockmap_listen.c`_
  254. - `tools/testing/selftests/bpf/progs/test_sockmap_update.c`_
  255. The following code snippet shows how to declare a sockmap.
  256. .. code-block:: c
  257. struct {
  258. __uint(type, BPF_MAP_TYPE_SOCKMAP);
  259. __uint(max_entries, 1);
  260. __type(key, __u32);
  261. __type(value, __u64);
  262. } sock_map_rx SEC(".maps");
  263. The following code snippet shows a sample parser program.
  264. .. code-block:: c
  265. SEC("sk_skb/stream_parser")
  266. int bpf_prog_parser(struct __sk_buff *skb)
  267. {
  268. return skb->len;
  269. }
  270. The following code snippet shows a simple verdict program that interacts with a
  271. sockmap to redirect traffic to another socket based on the local port.
  272. .. code-block:: c
  273. SEC("sk_skb/stream_verdict")
  274. int bpf_prog_verdict(struct __sk_buff *skb)
  275. {
  276. __u32 lport = skb->local_port;
  277. __u32 idx = 0;
  278. if (lport == 10000)
  279. return bpf_sk_redirect_map(skb, &sock_map_rx, idx, 0);
  280. return SK_PASS;
  281. }
  282. The following code snippet shows how to declare a sockhash map.
  283. .. code-block:: c
  284. struct socket_key {
  285. __u32 src_ip;
  286. __u32 dst_ip;
  287. __u32 src_port;
  288. __u32 dst_port;
  289. };
  290. struct {
  291. __uint(type, BPF_MAP_TYPE_SOCKHASH);
  292. __uint(max_entries, 1);
  293. __type(key, struct socket_key);
  294. __type(value, __u64);
  295. } sock_hash_rx SEC(".maps");
  296. The following code snippet shows a simple verdict program that interacts with a
  297. sockhash to redirect traffic to another socket based on a hash of some of the
  298. skb parameters.
  299. .. code-block:: c
  300. static inline
  301. void extract_socket_key(struct __sk_buff *skb, struct socket_key *key)
  302. {
  303. key->src_ip = skb->remote_ip4;
  304. key->dst_ip = skb->local_ip4;
  305. key->src_port = skb->remote_port >> 16;
  306. key->dst_port = (bpf_htonl(skb->local_port)) >> 16;
  307. }
  308. SEC("sk_skb/stream_verdict")
  309. int bpf_prog_verdict(struct __sk_buff *skb)
  310. {
  311. struct socket_key key;
  312. extract_socket_key(skb, &key);
  313. return bpf_sk_redirect_hash(skb, &sock_hash_rx, &key, 0);
  314. }
  315. User space
  316. ----------
  317. Several examples of the use of sockmap APIs can be found in:
  318. - `tools/testing/selftests/bpf/prog_tests/sockmap_basic.c`_
  319. - `tools/testing/selftests/bpf/test_sockmap.c`_
  320. - `tools/testing/selftests/bpf/test_maps.c`_
  321. The following code sample shows how to create a sockmap, attach a parser and
  322. verdict program, as well as add a socket entry.
  323. .. code-block:: c
  324. int create_sample_sockmap(int sock, int parse_prog_fd, int verdict_prog_fd)
  325. {
  326. int index = 0;
  327. int map, err;
  328. map = bpf_map_create(BPF_MAP_TYPE_SOCKMAP, NULL, sizeof(int), sizeof(int), 1, NULL);
  329. if (map < 0) {
  330. fprintf(stderr, "Failed to create sockmap: %s\n", strerror(errno));
  331. return -1;
  332. }
  333. err = bpf_prog_attach(parse_prog_fd, map, BPF_SK_SKB_STREAM_PARSER, 0);
  334. if (err){
  335. fprintf(stderr, "Failed to attach_parser_prog_to_map: %s\n", strerror(errno));
  336. goto out;
  337. }
  338. err = bpf_prog_attach(verdict_prog_fd, map, BPF_SK_SKB_STREAM_VERDICT, 0);
  339. if (err){
  340. fprintf(stderr, "Failed to attach_verdict_prog_to_map: %s\n", strerror(errno));
  341. goto out;
  342. }
  343. err = bpf_map_update_elem(map, &index, &sock, BPF_NOEXIST);
  344. if (err) {
  345. fprintf(stderr, "Failed to update sockmap: %s\n", strerror(errno));
  346. goto out;
  347. }
  348. out:
  349. close(map);
  350. return err;
  351. }
  352. References
  353. ===========
  354. - https://github.com/jrfastab/linux-kernel-xdp/commit/c89fd73cb9d2d7f3c716c3e00836f07b1aeb261f
  355. - https://lwn.net/Articles/731133/
  356. - http://vger.kernel.org/lpc_net2018_talks/ktls_bpf_paper.pdf
  357. - https://lwn.net/Articles/748628/
  358. - https://lore.kernel.org/bpf/20200218171023.844439-7-jakub@cloudflare.com/
  359. .. _`tools/testing/selftests/bpf/progs/test_sockmap_kern.h`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_kern.h
  360. .. _`tools/testing/selftests/bpf/progs/sockmap_parse_prog.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/sockmap_parse_prog.c
  361. .. _`tools/testing/selftests/bpf/progs/sockmap_verdict_prog.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/sockmap_verdict_prog.c
  362. .. _`tools/testing/selftests/bpf/prog_tests/sockmap_basic.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/prog_tests/sockmap_basic.c
  363. .. _`tools/testing/selftests/bpf/test_sockmap.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/test_sockmap.c
  364. .. _`tools/testing/selftests/bpf/test_maps.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/test_maps.c
  365. .. _`tools/testing/selftests/bpf/progs/test_sockmap_listen.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_listen.c
  366. .. _`tools/testing/selftests/bpf/progs/test_sockmap_update.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_update.c