1 // SPDX-License-Identifier: GPL-2.0 2 3 #include <test_progs.h> 4 5 #include "connect4_dropper.skel.h" 6 7 #include "cgroup_helpers.h" 8 #include "network_helpers.h" 9 10 static int run_test(int cgroup_fd, int server_fd, bool classid) 11 { 12 struct connect4_dropper *skel; 13 int fd, err = 0; 14 15 skel = connect4_dropper__open_and_load(); 16 if (!ASSERT_OK_PTR(skel, "skel_open")) 17 return -1; 18 19 skel->links.connect_v4_dropper = 20 bpf_program__attach_cgroup(skel->progs.connect_v4_dropper, 21 cgroup_fd); 22 if (!ASSERT_OK_PTR(skel->links.connect_v4_dropper, "prog_attach")) { 23 err = -1; 24 goto out; 25 } 26 27 if (classid && !ASSERT_OK(join_classid(), "join_classid")) { 28 err = -1; 29 goto out; 30 } 31 32 errno = 0; 33 fd = connect_to_fd_opts(server_fd, NULL); 34 if (fd >= 0) { 35 log_err("Unexpected success to connect to server"); 36 err = -1; 37 close(fd); 38 } else if (errno != EPERM) { 39 log_err("Unexpected errno from connect to server"); 40 err = -1; 41 } 42 out: 43 connect4_dropper__destroy(skel); 44 return err; 45 } 46 47 void test_cgroup_v1v2(void) 48 { 49 struct network_helper_opts opts = {}; 50 int server_fd, client_fd, cgroup_fd; 51 static const int port = 60120; 52 53 /* Step 1: Check base connectivity works without any BPF. */ 54 server_fd = start_server(AF_INET, SOCK_STREAM, NULL, port, 0); 55 if (!ASSERT_GE(server_fd, 0, "server_fd")) 56 return; 57 client_fd = connect_to_fd_opts(server_fd, &opts); 58 if (!ASSERT_GE(client_fd, 0, "client_fd")) { 59 close(server_fd); 60 return; 61 } 62 close(client_fd); 63 close(server_fd); 64 65 /* Step 2: Check BPF policy prog attached to cgroups drops connectivity. */ 66 cgroup_fd = test__join_cgroup("/connect_dropper"); 67 if (!ASSERT_GE(cgroup_fd, 0, "cgroup_fd")) 68 return; 69 server_fd = start_server(AF_INET, SOCK_STREAM, NULL, port, 0); 70 if (!ASSERT_GE(server_fd, 0, "server_fd")) { 71 close(cgroup_fd); 72 return; 73 } 74 ASSERT_OK(run_test(cgroup_fd, server_fd, false), "cgroup-v2-only"); 75 setup_classid_environment(); 76 set_classid(); 77 ASSERT_OK(run_test(cgroup_fd, server_fd, true), "cgroup-v1v2"); 78 cleanup_classid_environment(); 79 close(server_fd); 80 close(cgroup_fd); 81 } 82