aboutsummaryrefslogtreecommitdiffstats
path: root/tools/testing/selftests/bpf/prog_tests/bind_perm.c
blob: a1766a298bb77923bc5627b9a51f68fb736a45c5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <sched.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "test_progs.h"
#include "cap_helpers.h"
#include "bind_perm.skel.h"

static int duration;

static int create_netns(void)
{
	if (!ASSERT_OK(unshare(CLONE_NEWNET), "create netns"))
		return -1;

	return 0;
}

void try_bind(int family, int port, int expected_errno)
{
	struct sockaddr_storage addr = {};
	struct sockaddr_in6 *sin6;
	struct sockaddr_in *sin;
	int fd = -1;

	fd = socket(family, SOCK_STREAM, 0);
	if (CHECK(fd < 0, "fd", "errno %d", errno))
		goto close_socket;

	if (family == AF_INET) {
		sin = (struct sockaddr_in *)&addr;
		sin->sin_family = family;
		sin->sin_port = htons(port);
	} else {
		sin6 = (struct sockaddr_in6 *)&addr;
		sin6->sin6_family = family;
		sin6->sin6_port = htons(port);
	}

	errno = 0;
	bind(fd, (struct sockaddr *)&addr, sizeof(addr));
	ASSERT_EQ(errno, expected_errno, "bind");

close_socket:
	if (fd >= 0)
		close(fd);
}

void test_bind_perm(void)
{
	const __u64 net_bind_svc_cap = 1ULL << CAP_NET_BIND_SERVICE;
	struct bind_perm *skel;
	__u64 old_caps = 0;
	int cgroup_fd;

	if (create_netns())
		return;

	cgroup_fd = test__join_cgroup("/bind_perm");
	if (CHECK(cgroup_fd < 0, "cg-join", "errno %d", errno))
		return;

	skel = bind_perm__open_and_load();
	if (!ASSERT_OK_PTR(skel, "skel"))
		goto close_cgroup_fd;

	skel->links.bind_v4_prog = bpf_program__attach_cgroup(skel->progs.bind_v4_prog, cgroup_fd);
	if (!ASSERT_OK_PTR(skel, "bind_v4_prog"))
		goto close_skeleton;

	skel->links.bind_v6_prog = bpf_program__attach_cgroup(skel->progs.bind_v6_prog, cgroup_fd);
	if (!ASSERT_OK_PTR(skel, "bind_v6_prog"))
		goto close_skeleton;

	ASSERT_OK(cap_disable_effective(net_bind_svc_cap, &old_caps),
		  "cap_disable_effective");

	try_bind(AF_INET, 110, EACCES);
	try_bind(AF_INET6, 110, EACCES);

	try_bind(AF_INET, 111, 0);
	try_bind(AF_INET6, 111, 0);

	if (old_caps & net_bind_svc_cap)
		ASSERT_OK(cap_enable_effective(net_bind_svc_cap, NULL),
			  "cap_enable_effective");

close_skeleton:
	bind_perm__destroy(skel);
close_cgroup_fd:
	close(cgroup_fd);
}