/* eBPF example program: * * - Loads eBPF program * * The eBPF program sets the sk_bound_dev_if index in new AF_INET{6} * sockets opened by processes in the cgroup. * * - Attaches the new program to a cgroup using BPF_PROG_ATTACH */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include "libbpf.h" static int prog_load(int value) { struct bpf_insn prog[] = { BPF_MOV64_IMM(BPF_REG_0, value), /* r0 = verdict */ BPF_EXIT_INSN(), }; return bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, prog, sizeof(prog), "GPL", 0); } static int usage(const char *argv0) { printf("Usage: %s cg-path value\n", argv0); return EXIT_FAILURE; } int main(int argc, char **argv) { int cg_fd, prog_fd, value, ret; if (argc < 2) return usage(argv[0]); cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY); if (cg_fd < 0) { printf("Failed to open cgroup path: '%s'\n", strerror(errno)); return EXIT_FAILURE; } value = atoi(argv[2]); prog_fd = prog_load(value); /* printf("Output from kernel verifier:\n%s\n-------\n", bpf_log_buf); */ if (prog_fd < 0) { printf("Failed to load prog: '%s'\n", strerror(errno)); return EXIT_FAILURE; } ret = bpf_prog_attach(prog_fd, cg_fd, BPF_CGROUP_INET_SOCK_CREATE); if (ret < 0) { printf("Failed to attach prog to cgroup: '%s'\n", strerror(errno)); return EXIT_FAILURE; } return EXIT_SUCCESS; }