From c4956766c064f4f4f439939d2376fcd087b996ce Mon Sep 17 00:00:00 2001 From: Nick Kralevich Date: Mon, 18 Apr 2011 15:55:59 -0700 Subject: [PATCH] Validate sender credentials on netlink msg receive Verify that netlink messages are actually from the kernel, and not from a userspace program. Change-Id: I709c0efe9ba0258f6d79ebcde531d7f7bbe780b2 --- libsysutils/src/NetlinkListener.cpp | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/libsysutils/src/NetlinkListener.cpp b/libsysutils/src/NetlinkListener.cpp index e2a354e4f..fb088e1c3 100644 --- a/libsysutils/src/NetlinkListener.cpp +++ b/libsysutils/src/NetlinkListener.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #define LOG_TAG "NetlinkListener" @@ -32,10 +33,32 @@ NetlinkListener::NetlinkListener(int socket) : bool NetlinkListener::onDataAvailable(SocketClient *cli) { int socket = cli->getSocket(); - int count; + ssize_t count; + char cred_msg[CMSG_SPACE(sizeof(struct ucred))]; + struct sockaddr_nl snl; + struct iovec iov = {mBuffer, sizeof(mBuffer)}; + struct msghdr hdr = {&snl, sizeof(snl), &iov, 1, cred_msg, sizeof(cred_msg), 0}; - if ((count = recv(socket, mBuffer, sizeof(mBuffer), 0)) < 0) { - SLOGE("recv failed (%s)", strerror(errno)); + if ((count = recvmsg(socket, &hdr, 0)) < 0) { + SLOGE("recvmsg failed (%s)", strerror(errno)); + return false; + } + + if ((snl.nl_groups != 1) || (snl.nl_pid != 0)) { + SLOGE("ignoring non-kernel netlink multicast message"); + return false; + } + + struct cmsghdr * cmsg = CMSG_FIRSTHDR(&hdr); + + if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) { + SLOGE("ignoring message with no sender credentials"); + return false; + } + + struct ucred * cred = (struct ucred *)CMSG_DATA(cmsg); + if (cred->uid != 0) { + SLOGE("ignoring message from non-root UID %d", cred->uid); return false; }