Test checks that listen(2) doesn't wrongfully return -EACCES instead of -EINVAL when trying to listen for an incorrect socket state. Signed-off-by: Mikhail Ivanov <ivanov.mikhail1@xxxxxxxxxxxxxxxxxxx> --- tools/testing/selftests/landlock/net_test.c | 65 +++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/tools/testing/selftests/landlock/net_test.c b/tools/testing/selftests/landlock/net_test.c index b6fe9bde205f..a8385f1373f6 100644 --- a/tools/testing/selftests/landlock/net_test.c +++ b/tools/testing/selftests/landlock/net_test.c @@ -1644,6 +1644,71 @@ TEST_F(ipv4_tcp, with_fs) EXPECT_EQ(-EACCES, bind_variant(bind_fd, &self->srv1)); } +TEST_F(ipv4_tcp, listen_on_connected) +{ + const struct landlock_ruleset_attr ruleset_attr = { + .handled_access_net = ACCESS_ALL, + }; + const struct landlock_net_port_attr tcp_not_restricted_p0 = { + .allowed_access = ACCESS_ALL, + .port = self->srv0.port, + }; + const struct landlock_net_port_attr tcp_denied_listen_p1 = { + .allowed_access = ACCESS_ALL & ~LANDLOCK_ACCESS_NET_LISTEN_TCP, + .port = self->srv1.port, + }; + int ruleset_fd; + int bind_fd, status; + pid_t child; + + ruleset_fd = + landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0); + ASSERT_LE(0, ruleset_fd); + + /* Allows all actions for the first port. */ + ASSERT_EQ(0, landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, + &tcp_not_restricted_p0, 0)); + + /* Deny listen for the second port. */ + ASSERT_EQ(0, landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, + &tcp_denied_listen_p1, 0)); + + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); + + /* Init listening socket. */ + bind_fd = socket_variant(&self->srv0); + ASSERT_LE(0, bind_fd); + EXPECT_EQ(0, bind_variant(bind_fd, &self->srv0)); + EXPECT_EQ(0, listen_variant(bind_fd, backlog)); + + child = fork(); + ASSERT_LE(0, child); + if (child == 0) { + int connect_fd; + + /* Closes listening socket for the child. */ + EXPECT_EQ(0, close(bind_fd)); + + connect_fd = socket_variant(&self->srv1); + ASSERT_LE(0, connect_fd); + EXPECT_EQ(0, connect_variant(connect_fd, &self->srv0)); + + /* Tries to listen on connected socket. */ + EXPECT_EQ(-EINVAL, listen_variant(connect_fd, backlog)); + + EXPECT_EQ(0, close(connect_fd)); + _exit(_metadata->exit_code); + return; + } + + EXPECT_EQ(child, waitpid(child, &status, 0)); + EXPECT_EQ(1, WIFEXITED(status)); + EXPECT_EQ(EXIT_SUCCESS, WEXITSTATUS(status)); + + EXPECT_EQ(0, close(bind_fd)); +} + FIXTURE(port_specific) { struct service_fixture srv0; -- 2.34.1