libnetlink: ignore netlink messages not from kernel
Subsystems (3)
PATCH 1/1 libnetlink: ignore netlink messages not from kernel
A process with CAP_NET_ADMIN in its own netns can send forged netlink messages to a monitor, by multicast to an all-nsid listener in another netns or by unicast to the monitor's port.
Filter on nl_pid in __rtnl_recvmsg() and use it in rtnl_listen(). Dequeue the datagram when peeking, and restore the value-result msg fields before retrying.
Reported-by Anthropic OSS scanner
Assisted-by Claude:claude-opus-5-5
Signed-off-by Stephen Hemminger <[email protected]>
--- lib/libnetlink.c | 51 ++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 23 deletions(-)
lib/libnetlink.c +28 -23
@@ -825,13 +825,21 @@ static int rtnl_dump_error(const struct rtnl_handle *rth,static int __rtnl_recvmsg (int fd,struct msghdr *msg,int flags) { +const struct sockaddr_nl *nladdr = msg->msg_name; +socklen_t namelen = msg->msg_namelen; +size_t controllen = msg->msg_controllen;int len; -do { - len =recvmsg (fd, msg, flags); - }while (len <0 && (errno ==EINTR || errno ==EAGAIN )); +retry: +/* value-result fields, restore if discarding a message */ + msg->msg_namelen = namelen; + msg->msg_controllen = controllen; + len =recvmsg (fd, msg, flags);if (len <0 ) { +if (errno ==EINTR || errno ==EAGAIN ) + goto retry; +fprintf (stderr,"netlink receive error %s (%d)\n" ,strerror (errno), errno);return -errno;
@@ -842,6 +850,19 @@ static int __rtnl_recvmsg(int fd, struct msghdr *msg, int flags)return -ENODATA ; } +if (msg->msg_namelen !=sizeof (*nladdr)) { +fprintf (stderr,"Sender address length == %u\n" , + msg->msg_namelen); +return -EINVAL ; + } + +/* Only accept messages from kernel, discard anything else */ +if (nladdr->nl_pid !=0 ) { +if (flags &MSG_PEEK ) +recv (fd,NULL ,0 ,0 ); + goto retry; + } +return len; }
@@ -1248,27 +1269,11 @@ int rtnl_listen(struct rtnl_handle *rtnl, } iov.iov_len =sizeof (buf); - status =recvmsg (rtnl->fd, &msg,0 ); - -if (status <0 ) { -if (errno ==EINTR || errno ==EAGAIN ) -continue ; -fprintf (stderr,"netlink receive error %s (%d)\n" , -strerror (errno), errno); -if (errno ==ENOBUFS ) -continue ; -return -1 ; - } -if (status ==0 ) { -fprintf (stderr,"EOF on netlink\n" ); + status =__rtnl_recvmsg (rtnl->fd, &msg,0 ); +if (status == -ENOBUFS ) +continue ; +if (status <0 )return -1 ; - } -if (msg.msg_namelen !=sizeof (nladdr)) { -fprintf (stderr, -"Sender address length == %d\n" , - msg.msg_namelen); -exit (1 ); - }if (rtnl->flags &RTNL_HANDLE_F_LISTEN_ALL_NSID ) {memset (&ctrl,0 ,sizeof (ctrl));
Signature · 1 line
2.53.0