Skip to content

Commit

Permalink
utils: Don't assume cmsg data is aligned suitably for struct ucred
Browse files Browse the repository at this point in the history
As documented in cmsg(3), the alignment of control messages is not
guaranteed, so for portability to architectures with strong alignment
requirements we should memcpy to and from a suitably aligned instance
of the desired data structure on the stack.

Helps: containers#637
Signed-off-by: Simon McVittie <[email protected]>
  • Loading branch information
smcv committed Oct 16, 2024
1 parent 50cdea6 commit a05614e
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -760,7 +760,7 @@ send_pid_on_socket (int sockfd)
const ssize_t control_len_snd = CMSG_SPACE(sizeof(struct ucred));
char control_buf_snd[control_len_snd];
struct cmsghdr *cmsg;
struct ucred *cred;
struct ucred cred;

msg.msg_iov = &iov;
msg.msg_iovlen = 1;
Expand All @@ -771,11 +771,11 @@ send_pid_on_socket (int sockfd)
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_CREDENTIALS;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
cred = (struct ucred *)CMSG_DATA(cmsg);

cred->pid = getpid ();
cred->uid = geteuid ();
cred->gid = getegid ();
cred.pid = getpid ();
cred.uid = geteuid ();
cred.gid = getegid ();
memcpy (CMSG_DATA (cmsg), &cred, sizeof (cred));

if (TEMP_FAILURE_RETRY (sendmsg (sockfd, &msg, 0)) < 0)
die_with_error ("Can't send pid");
Expand Down Expand Up @@ -821,8 +821,10 @@ read_pid_from_socket (int sockfd)
cmsg->cmsg_type == SCM_CREDENTIALS &&
payload_len == sizeof(struct ucred))
{
struct ucred *cred = (struct ucred *)CMSG_DATA(cmsg);
return cred->pid;
struct ucred cred;

memcpy (&cred, CMSG_DATA (cmsg), sizeof (cred));
return cred.pid;
}
}
die ("No pid returned on socket");
Expand Down

0 comments on commit a05614e

Please sign in to comment.