How do I read kernel audit messages using NETLINK_AUDIT in user space

From: Bhat, Jayalakshmi Manjunath
Date: Tue Dec 08 2020 - 09:11:58 EST


Hi All,

I am trying to read kernel audit messages specially generated by XFRM in user space. I wrote Netlink client stub to read the audit message as below. But the call recvfrom gets blocked indefinite.
Can any one tell me what am I doing wrong?

Regards,
Jayalakshmi

#include <sys/socket.h>
#include <linux/netlink.h>
#include <stdio.h>
#include <malloc.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_AUDIT);

if (fd < 0) {
printf("Socket creation failed. try again\n");
}
else
{
struct sockaddr_nl src_addr;
struct sockaddr_nl dest_addr;
struct iovec iov;
struct msghdr msg;
struct nlmsghdr *nlh =(struct nlmsghdr *) malloc(NLMSG_SPACE(1024));

memset(nlh, 0, NLMSG_SPACE(1024));
memset(&iov, 0, sizeof(iov));

nlh->nlmsg_len = NLMSG_SPACE(1024);
nlh->nlmsg_pid = getpid();
nlh->nlmsg_flags = 0;

src_addr.nl_family = AF_NETLINK;
src_addr.nl_pid = getpid();
src_addr.nl_groups = 0;

bind(fd, (struct sockaddr *)&src_addr, sizeof(src_addr));

iov.iov_base = (void *)nlh;
iov.iov_len = nlh->nlmsg_len;

msg.msg_name = (void *)&src_addr;
msg.msg_namelen = sizeof(src_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;

recvfrom(fd, &msg,sizeof(msg),0,(struct sockaddr *) &dest_addr,sizeof(dest_addr));
printf("Received message: %s\n", (char *)NLMSG_DATA(nlh));
close(fd);
}