如何使用netlink套接字与内核模块通信?

时间:2021-10-27 22:24:39

I am trying to write a linux kernel module that communicates with user process using netlink. I am using netlink because the user program I want to communicate to communicates only using sockets and I cant change that to add ioctl() or anything.

我正在尝试编写一个linux内核模块,使用netlink与用户进程通信。我之所以使用netlink,是因为我想要与之通信的用户程序仅使用sockets进行通信,我无法更改它以添加ioctl()或其他任何东西。

Problem is that I cant figure out how to do that. I have googled but all examples I found are for old like this one and no longer valid for current kernel versions. I have also looked at this SO question but the sample here uses libnl for socket operations but I want to stick to standard socket functions (defined by sys/socket.h). So can some one plz guide me here to some tutorial or guide or some thing that can help me understand the interface and usage of netlink. I would highly appreciate a working example, nothing fancy, just a very basic example of how to establish a connection from a socket in user program to a socket in kernel and then send data from user process to kernel and receive back from kernel.

问题是我不知道怎么做。我已经用谷歌搜索过,但是我发现的所有示例都是旧的,比如这个,现在的内核版本不再有效。我也看过这个SO问题,但是这里的示例使用libnl进行套接字操作,但是我想坚持使用标准套接字函数(由sys/ socket.com .h定义)。因此,有人能在这里给我介绍一些教程或指南,或者一些能帮助我理解netlink的界面和用法的东西吗?我非常喜欢一个工作示例,没有什么特别的,只是一个非常基本的示例,说明如何从用户程序中的套接字建立连接到内核中的套接字,然后从用户进程向内核发送数据并从内核接收数据。

Also please do not tell me to look at kernel code. I am already doing it but it will take a lot of time and I dont have lot of it left.

另外,请不要告诉我查看内核代码。我已经在做了,但这需要很多时间,我没有很多剩余。

Update: After lot of trial and error I have following code which sends message from user program to kernel but the message from kernel to user program i.e using netlink_unicast() is not working. Its not only not working, the call hangs the systems and then I have to restart the machine. Can some one plz take a look and tell me what wrong I am doing. The netlink_unicast() call is commented in the following code. It should be uncommented for kernel to user program message.

更新:经过大量的尝试和错误后,我有如下代码:从用户程序发送消息到内核,但从内核发送消息到用户程序I。使用netlink_unicast()不工作。它不仅不起作用,还挂着系统,然后我就得重启机器。能不能让一个人看一看,告诉我我做错了什么。netlink_unicast()调用在以下代码中注释。内核对用户程序消息应该不加注释。

User Program

#include <sys/socket.h>  
#include <linux/netlink.h>  
#define NETLINK_USER 31  
#define MAX_PAYLOAD 1024  /* maximum payload size*/  

struct sockaddr_nl src_addr, dest_addr;  
struct nlmsghdr *nlh = NULL;  
struct iovec iov;  
int sock_fd;  
struct msghdr msg;  

void main()  
{  
    sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);  
    if(sock_fd<0)  
        return -1;  

    memset(&src_addr, 0, sizeof(src_addr));  
    src_addr.nl_family = AF_NETLINK;  
    src_addr.nl_pid = getpid();  /* self pid */  
    /* interested in group 1<<0 */  
    bind(sock_fd, (struct sockaddr*)&src_addr,  
      sizeof(src_addr));  

    memset(&dest_addr, 0, sizeof(dest_addr));  
    memset(&dest_addr, 0, sizeof(dest_addr));  
    dest_addr.nl_family = AF_NETLINK;  
    dest_addr.nl_pid = 0;   /* For Linux Kernel */  
    dest_addr.nl_groups = 0; /* unicast */  

    nlh = (struct nlmsghdr *)malloc(  
                          NLMSG_SPACE(MAX_PAYLOAD));  
    memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));  
    nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);  
    nlh->nlmsg_pid = getpid();  
    nlh->nlmsg_flags = 0;  

    strcpy(NLMSG_DATA(nlh), "Hello");  

    iov.iov_base = (void *)nlh;  
    iov.iov_len = nlh->nlmsg_len;  
    msg.msg_name = (void *)&dest_addr;  
    msg.msg_namelen = sizeof(dest_addr);  
    msg.msg_iov = &iov;  
    msg.msg_iovlen = 1;  

    printf("Sending message to kernel\n");  
    sendmsg(sock_fd,&msg,0);  
    printf("Waiting for message from kernel\n");  

    /* Read message from kernel */  
    recvmsg(sock_fd, &msg, 0);  
    printf(" Received message payload: %s\n",  
        NLMSG_DATA(nlh));  
    close(sock_fd);  
}

Kernel Code

#include <linux/module.h>  
#include <linux/kernel.h>  
#include <linux/init.h>  
#include <net/sock.h>  
#include <linux/socket.h>  
#include <linux/net.h>  
#include <asm/types.h>  
#include <linux/netlink.h>  
#include <linux/skbuff.h>  

#define NETLINK_USER 31  

struct sock *nl_sk = NULL;  

static void hello_nl_recv_msg(struct sk_buff *skb)  
{
        struct nlmsghdr *nlh;  
        int pid;  

        printk(KERN_INFO "Entering: %s\n", __FUNCTION__);  

        nlh=(struct nlmsghdr*)skb->data;  
        printk(KERN_INFO "Netlink received msg payload: %s\n",
            (char*)NLMSG_DATA(nlh));  
        pid = nlh->nlmsg_pid; /*pid of sending process */  
        NETLINK_CB(skb).dst_group = 0; /* not in mcast group */  
        NETLINK_CB(skb).pid = 0;      /* from kernel */  
        //NETLINK_CB(skb).groups = 0; /* not in mcast group */  
        //NETLINK_CB(skb).dst_pid = pid;  
        printk("About to send msg bak:\n");  
        //netlink_unicast(nl_sk,skb,pid,MSG_DONTWAIT);  

}  

static int __init hello_init(void)  
{  

        printk("Entering: %s\n",__FUNCTION__);  
        nl_sk=netlink_kernel_create(&init_net, NETLINK_USER, 0,
               hello_nl_recv_msg, NULL, THIS_MODULE);  
        if(!nl_sk)  
        {   
                printk(KERN_ALERT "Error creating socket.\n");  
                return -10;  
        }  
        return 0;  
}  

static void __exit hello_exit(void)  
{

        printk(KERN_INFO "exiting hello module\n");  
        netlink_kernel_release(nl_sk);  
}  

module_init(hello_init);  
module_exit(hello_exit);  

4 个解决方案

#1


46  

After reading kernel source I finally managed to make netlink sockets work for me. Below is an example of Netlink socket basics i.e opening a netlink socket, reading and writing to it and closing it.

在阅读了内核源代码之后,我终于成功地让netlink sockets为我工作。下面是Netlink socket基础i的一个例子。打开一个netlink插座,读写并关闭它。

Kernel Module

#include <linux/module.h>
#include <net/sock.h> 
#include <linux/netlink.h>
#include <linux/skbuff.h> 
#define NETLINK_USER 31

struct sock *nl_sk = NULL;

static void hello_nl_recv_msg(struct sk_buff *skb)
{

    struct nlmsghdr *nlh;
    int pid;
    struct sk_buff *skb_out;
    int msg_size;
    char *msg = "Hello from kernel";
    int res;

    printk(KERN_INFO "Entering: %s\n", __FUNCTION__);

    msg_size = strlen(msg);

    nlh = (struct nlmsghdr *)skb->data;
    printk(KERN_INFO "Netlink received msg payload:%s\n", (char *)nlmsg_data(nlh));
    pid = nlh->nlmsg_pid; /*pid of sending process */

    skb_out = nlmsg_new(msg_size, 0);
    if (!skb_out) {
        printk(KERN_ERR "Failed to allocate new skb\n");
        return;
    }

    nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, msg_size, 0);
    NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */
    strncpy(nlmsg_data(nlh), msg, msg_size);

    res = nlmsg_unicast(nl_sk, skb_out, pid);
    if (res < 0)
        printk(KERN_INFO "Error while sending bak to user\n");
}

static int __init hello_init(void)
{

    printk("Entering: %s\n", __FUNCTION__);
    //nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, 0, hello_nl_recv_msg, NULL, THIS_MODULE);
    struct netlink_kernel_cfg cfg = {
        .input = hello_nl_recv_msg,
    };

    nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);
    if (!nl_sk) {
        printk(KERN_ALERT "Error creating socket.\n");
        return -10;
    }

    return 0;
}

static void __exit hello_exit(void)
{

    printk(KERN_INFO "exiting hello module\n");
    netlink_kernel_release(nl_sk);
}

module_init(hello_init); module_exit(hello_exit);

MODULE_LICENSE("GPL");

User Program

#include <linux/netlink.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define NETLINK_USER 31

#define MAX_PAYLOAD 1024 /* maximum payload size*/
struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
int sock_fd;
struct msghdr msg;

int main()
{
    sock_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);
    if (sock_fd < 0)
        return -1;

    memset(&src_addr, 0, sizeof(src_addr));
    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid(); /* self pid */

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

    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.nl_family = AF_NETLINK;
    dest_addr.nl_pid = 0; /* For Linux Kernel */
    dest_addr.nl_groups = 0; /* unicast */

    nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
    memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
    nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
    nlh->nlmsg_pid = getpid();
    nlh->nlmsg_flags = 0;

    strcpy(NLMSG_DATA(nlh), "Hello");

    iov.iov_base = (void *)nlh;
    iov.iov_len = nlh->nlmsg_len;
    msg.msg_name = (void *)&dest_addr;
    msg.msg_namelen = sizeof(dest_addr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    printf("Sending message to kernel\n");
    sendmsg(sock_fd, &msg, 0);
    printf("Waiting for message from kernel\n");

    /* Read message from kernel */
    recvmsg(sock_fd, &msg, 0);
    printf("Received message payload: %s\n", NLMSG_DATA(nlh));
    close(sock_fd);
}

Related thread about the magic constant NETLINK_USER 31: Can I have more than 32 netlink sockets in kernelspace?

关于神奇常量NETLINK_USER的相关线程31:我可以在内核空间中拥有超过32个netlink套接字吗?

#2


7  

Just in case anybody doesn't know how to compile, google "how to compile and load kernel module"

以防有人不知道如何编译谷歌"如何编译和加载内核模块"

refer to http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

指的是http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Grab kernel source code to which you'll compile module against http://kernel.org

获取内核源代码,您将在http://kernel.org上编译模块。

Or simply update your headers if you are running intended kernel

或者,如果您正在运行预期的内核,只需更新您的头文件

# apt-get install kernel-headers-$(uname -r)

Create a makefile, for example

例如,创建一个makefile

obj-m = hello.o
KVERSION = $(shell uname -r)
all:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean

Make and you'll get bunch of files. *.ko is the one you'll load into your kernel, run

你会得到一堆文件。*。ko是你要加载到内核的,运行

# insmod hello.ko

if you us lsmod to check all loaded modules, you'll find yours, most likely you will see:

如果你去lsmod检查所有已加载的模块,你会发现你的模块,很可能你会看到:

hello       12575  0 

In our case, compile and run user code:

在我们的例子中,编译并运行用户代码:

gcc hello.c -o hello.o
./hello.o

If everything is OK, you'll get following message using binW's code:

如果一切顺利,您将得到以下信息使用binW的代码:

Sending message to kernel
Waiting for message from kernel
 Received message payload: Hello from kernel

Finally, remove the module using:

最后,使用以下方法删除模块:

# rmmod hello

#3


5  

It works for me with kernel 3.2. For kernel 3.6 & above, it needs a bit of a change at the netlink_kernel_create function.

对于内核3.2,它是适用的。对于内核3.6 &以上,它需要对netlink_kernel_create函数进行一点修改。

 struct netlink_kernel_cfg cfg = {
                .groups = 1,
                .input = hello_nl_recv_msg,
        };
        printk("Entering: %s\n", __FUNCTION__);
        nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);

#4


0  

you need include following header file into client_side code:

您需要在client_side代码中包含以下头文件:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#1


46  

After reading kernel source I finally managed to make netlink sockets work for me. Below is an example of Netlink socket basics i.e opening a netlink socket, reading and writing to it and closing it.

在阅读了内核源代码之后,我终于成功地让netlink sockets为我工作。下面是Netlink socket基础i的一个例子。打开一个netlink插座,读写并关闭它。

Kernel Module

#include <linux/module.h>
#include <net/sock.h> 
#include <linux/netlink.h>
#include <linux/skbuff.h> 
#define NETLINK_USER 31

struct sock *nl_sk = NULL;

static void hello_nl_recv_msg(struct sk_buff *skb)
{

    struct nlmsghdr *nlh;
    int pid;
    struct sk_buff *skb_out;
    int msg_size;
    char *msg = "Hello from kernel";
    int res;

    printk(KERN_INFO "Entering: %s\n", __FUNCTION__);

    msg_size = strlen(msg);

    nlh = (struct nlmsghdr *)skb->data;
    printk(KERN_INFO "Netlink received msg payload:%s\n", (char *)nlmsg_data(nlh));
    pid = nlh->nlmsg_pid; /*pid of sending process */

    skb_out = nlmsg_new(msg_size, 0);
    if (!skb_out) {
        printk(KERN_ERR "Failed to allocate new skb\n");
        return;
    }

    nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, msg_size, 0);
    NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */
    strncpy(nlmsg_data(nlh), msg, msg_size);

    res = nlmsg_unicast(nl_sk, skb_out, pid);
    if (res < 0)
        printk(KERN_INFO "Error while sending bak to user\n");
}

static int __init hello_init(void)
{

    printk("Entering: %s\n", __FUNCTION__);
    //nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, 0, hello_nl_recv_msg, NULL, THIS_MODULE);
    struct netlink_kernel_cfg cfg = {
        .input = hello_nl_recv_msg,
    };

    nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);
    if (!nl_sk) {
        printk(KERN_ALERT "Error creating socket.\n");
        return -10;
    }

    return 0;
}

static void __exit hello_exit(void)
{

    printk(KERN_INFO "exiting hello module\n");
    netlink_kernel_release(nl_sk);
}

module_init(hello_init); module_exit(hello_exit);

MODULE_LICENSE("GPL");

User Program

#include <linux/netlink.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define NETLINK_USER 31

#define MAX_PAYLOAD 1024 /* maximum payload size*/
struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
int sock_fd;
struct msghdr msg;

int main()
{
    sock_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);
    if (sock_fd < 0)
        return -1;

    memset(&src_addr, 0, sizeof(src_addr));
    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid(); /* self pid */

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

    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.nl_family = AF_NETLINK;
    dest_addr.nl_pid = 0; /* For Linux Kernel */
    dest_addr.nl_groups = 0; /* unicast */

    nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
    memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
    nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
    nlh->nlmsg_pid = getpid();
    nlh->nlmsg_flags = 0;

    strcpy(NLMSG_DATA(nlh), "Hello");

    iov.iov_base = (void *)nlh;
    iov.iov_len = nlh->nlmsg_len;
    msg.msg_name = (void *)&dest_addr;
    msg.msg_namelen = sizeof(dest_addr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    printf("Sending message to kernel\n");
    sendmsg(sock_fd, &msg, 0);
    printf("Waiting for message from kernel\n");

    /* Read message from kernel */
    recvmsg(sock_fd, &msg, 0);
    printf("Received message payload: %s\n", NLMSG_DATA(nlh));
    close(sock_fd);
}

Related thread about the magic constant NETLINK_USER 31: Can I have more than 32 netlink sockets in kernelspace?

关于神奇常量NETLINK_USER的相关线程31:我可以在内核空间中拥有超过32个netlink套接字吗?

#2


7  

Just in case anybody doesn't know how to compile, google "how to compile and load kernel module"

以防有人不知道如何编译谷歌"如何编译和加载内核模块"

refer to http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

指的是http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Grab kernel source code to which you'll compile module against http://kernel.org

获取内核源代码,您将在http://kernel.org上编译模块。

Or simply update your headers if you are running intended kernel

或者,如果您正在运行预期的内核,只需更新您的头文件

# apt-get install kernel-headers-$(uname -r)

Create a makefile, for example

例如,创建一个makefile

obj-m = hello.o
KVERSION = $(shell uname -r)
all:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean

Make and you'll get bunch of files. *.ko is the one you'll load into your kernel, run

你会得到一堆文件。*。ko是你要加载到内核的,运行

# insmod hello.ko

if you us lsmod to check all loaded modules, you'll find yours, most likely you will see:

如果你去lsmod检查所有已加载的模块,你会发现你的模块,很可能你会看到:

hello       12575  0 

In our case, compile and run user code:

在我们的例子中,编译并运行用户代码:

gcc hello.c -o hello.o
./hello.o

If everything is OK, you'll get following message using binW's code:

如果一切顺利,您将得到以下信息使用binW的代码:

Sending message to kernel
Waiting for message from kernel
 Received message payload: Hello from kernel

Finally, remove the module using:

最后,使用以下方法删除模块:

# rmmod hello

#3


5  

It works for me with kernel 3.2. For kernel 3.6 & above, it needs a bit of a change at the netlink_kernel_create function.

对于内核3.2,它是适用的。对于内核3.6 &以上,它需要对netlink_kernel_create函数进行一点修改。

 struct netlink_kernel_cfg cfg = {
                .groups = 1,
                .input = hello_nl_recv_msg,
        };
        printk("Entering: %s\n", __FUNCTION__);
        nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);

#4


0  

you need include following header file into client_side code:

您需要在client_side代码中包含以下头文件:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>