From ddb1c6d1d44bec67a815b4f57b6733325f4de469 Mon Sep 17 00:00:00 2001 From: Jonathan Rajotte Date: Mon, 2 Mar 2020 14:21:33 -0500 Subject: [PATCH] Fix: set FD_CLOEXEC on incoming FDs. The stream shm FDs are allocated by the consumer process, and then passed to the applications over unix sockets. When opening those file descriptors on reception, the FD_CLOEXEC flag is not set. In a fork + exec scenario, parent process streams shm FDs and channel wake FDs are present in the resulting child process. Set FD_CLOEXEC on reception (ustcomm_recv_fds_unix_sock) to prevent such scenario. Change-Id: Id58077b272be9c1ab239846639ffd8103b3d50f1 Signed-off-by: Jonathan Rajotte Signed-off-by: Mathieu Desnoyers --- liblttng-ust-comm/lttng-ust-comm.c | 13 +++++++++++++ libringbuffer/shm.c | 5 ----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/liblttng-ust-comm/lttng-ust-comm.c b/liblttng-ust-comm/lttng-ust-comm.c index beeee60b..d80055e9 100644 --- a/liblttng-ust-comm/lttng-ust-comm.c +++ b/liblttng-ust-comm/lttng-ust-comm.c @@ -106,6 +106,7 @@ int ustcomm_connect_unix_sock(const char *pathname, long timeout) /* * libust threads require the close-on-exec flag for all * resources so it does not leak file descriptors upon exec. + * SOCK_CLOEXEC is not used since it is linux specific. */ fd = socket(PF_UNIX, SOCK_STREAM, 0); if (fd < 0) { @@ -451,6 +452,7 @@ ssize_t ustcomm_recv_fds_unix_sock(int sock, int *fds, size_t nb_fd) char recv_fd[CMSG_SPACE(sizeof_fds)]; struct msghdr msg; char dummy; + int i; memset(&msg, 0, sizeof(msg)); @@ -506,7 +508,18 @@ ssize_t ustcomm_recv_fds_unix_sock(int sock, int *fds, size_t nb_fd) ret = -1; goto end; } + memcpy(fds, CMSG_DATA(cmsg), sizeof_fds); + + /* Set FD_CLOEXEC */ + for (i = 0; i < nb_fd; i++) { + ret = fcntl(fds[i], F_SETFD, FD_CLOEXEC); + if (ret < 0) { + PERROR("fcntl failed to set FD_CLOEXEC on fd %d", + fds[i]); + } + } + ret = nb_fd; end: return ret; diff --git a/libringbuffer/shm.c b/libringbuffer/shm.c index ea946ea3..7991d06f 100644 --- a/libringbuffer/shm.c +++ b/libringbuffer/shm.c @@ -279,11 +279,6 @@ struct shm_object *shm_object_table_append_shm(struct shm_object_table *table, obj->shm_fd = shm_fd; obj->shm_fd_ownership = 1; - ret = fcntl(obj->wait_fd[1], F_SETFD, FD_CLOEXEC); - if (ret < 0) { - PERROR("fcntl"); - goto error_fcntl; - } /* The write end of the pipe needs to be non-blocking */ ret = fcntl(obj->wait_fd[1], F_SETFL, O_NONBLOCK); if (ret < 0) { -- 2.34.1