test_cgrp2_sock.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* eBPF example program:
  2. *
  3. * - Loads eBPF program
  4. *
  5. * The eBPF program sets the sk_bound_dev_if index in new AF_INET{6}
  6. * sockets opened by processes in the cgroup.
  7. *
  8. * - Attaches the new program to a cgroup using BPF_PROG_ATTACH
  9. */
  10. #define _GNU_SOURCE
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <stddef.h>
  14. #include <string.h>
  15. #include <unistd.h>
  16. #include <assert.h>
  17. #include <errno.h>
  18. #include <fcntl.h>
  19. #include <net/if.h>
  20. #include <linux/bpf.h>
  21. #include "libbpf.h"
  22. char bpf_log_buf[BPF_LOG_BUF_SIZE];
  23. static int prog_load(int idx)
  24. {
  25. struct bpf_insn prog[] = {
  26. BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
  27. BPF_MOV64_IMM(BPF_REG_3, idx),
  28. BPF_MOV64_IMM(BPF_REG_2, offsetof(struct bpf_sock, bound_dev_if)),
  29. BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, offsetof(struct bpf_sock, bound_dev_if)),
  30. BPF_MOV64_IMM(BPF_REG_0, 1), /* r0 = verdict */
  31. BPF_EXIT_INSN(),
  32. };
  33. size_t insns_cnt = sizeof(prog) / sizeof(struct bpf_insn);
  34. return bpf_load_program(BPF_PROG_TYPE_CGROUP_SOCK, prog, insns_cnt,
  35. "GPL", 0, bpf_log_buf, BPF_LOG_BUF_SIZE);
  36. }
  37. static int usage(const char *argv0)
  38. {
  39. printf("Usage: %s cg-path device-index\n", argv0);
  40. return EXIT_FAILURE;
  41. }
  42. int main(int argc, char **argv)
  43. {
  44. int cg_fd, prog_fd, ret;
  45. unsigned int idx;
  46. if (argc < 2)
  47. return usage(argv[0]);
  48. idx = if_nametoindex(argv[2]);
  49. if (!idx) {
  50. printf("Invalid device name\n");
  51. return EXIT_FAILURE;
  52. }
  53. cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
  54. if (cg_fd < 0) {
  55. printf("Failed to open cgroup path: '%s'\n", strerror(errno));
  56. return EXIT_FAILURE;
  57. }
  58. prog_fd = prog_load(idx);
  59. printf("Output from kernel verifier:\n%s\n-------\n", bpf_log_buf);
  60. if (prog_fd < 0) {
  61. printf("Failed to load prog: '%s'\n", strerror(errno));
  62. return EXIT_FAILURE;
  63. }
  64. ret = bpf_prog_attach(prog_fd, cg_fd, BPF_CGROUP_INET_SOCK_CREATE);
  65. if (ret < 0) {
  66. printf("Failed to attach prog to cgroup: '%s'\n",
  67. strerror(errno));
  68. return EXIT_FAILURE;
  69. }
  70. return EXIT_SUCCESS;
  71. }