在内核的数据包头中插入数据

时间:2014-07-17 08:46:21

标签: c linux-kernel kernel-module netfilter

我想在数据包的标题中插入一些数据,但请指导我如何操作

#define __KERNEL__
#define MODULE
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <net/ip.h>
struct my_head_struct {
int a;
};


/* This is the structure we shall use to register our function */
static struct nf_hook_ops nfho;

/* Name of the interface we want to drop packets from */
static char *drop_if = "eth0";

/* This is the hook function itself */
unsigned int hook_func(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{

unsigned int length,truesize;
printk("Inside the hook function\n");

if (strcmp(in->name, drop_if) == 0) {
struct iphdr *iph = NULL;

struct tcphdr *tcph = NULL;
length = skb->len;
truesize=skb->truesize;

iph = ip_hdr((skb));
tcph = (struct tcphdr *)(skb_network_header((skb)) + ip_hdrlen((skb))); // access tcp header.

printk(KERN_ALERT "INFO: Source IP Address: %pI4\n",&iph->saddr);

printk(KERN_ALERT "INFO: Destination IP Address: %pI4\n",&iph->daddr);

printk(KERN_ALERT "INFO: Source Port: %u.\n",tcph->source);

printk(KERN_ALERT "INFO: Destination Port: %u.\n",tcph->dest);
printk("length is %d\n",length);
printk("truesize is %d\n",truesize);
struct my_head_struct * my_head= NULL;

struct sk_buff *newskb;
newskb = skb_copy_expand(skb, sizeof(struct my_head_struct), 0, GFP_ATOMIC);
if(newskb==NULL)
{
printk("Failed to allocate mem\n");
//return SEND_FAIL_MEMORY;
}
else
{
// /* need add check of newskb value for error control */
my_head->a = 21; //want to push this in new skb

}
printk("Dropped packet on %s...\n", drop_if);
return NF_ACCEPT;
} else {
return NF_ACCEPT;
}
}

/* Initialisation routine */
int init_module()
{

printk("netfilter interface module inserted\n");
/* Fill in our hook structure */
nfho.hook = hook_func; /* Handler function */
nfho.hooknum = 0;// NF_IP_PRE_ROUTING; /* First hook for IPv4 */
nfho.pf = PF_INET;
nfho.priority = NF_IP_PRI_FIRST; /* Make our function first */

nf_register_hook(&nfho);

return 0;
}

/* Cleanup routine */
void cleanup_module()
{
printk("Netfilter interface module removed\n");
nf_unregister_hook(&nfho);
}

我在内核netfilter钩子中获取数据包,并且hooki想要将21值放在数据包的标头中并打印该值。 我该怎么办呢。

1 个答案:

答案 0 :(得分:1)

您可以使用skb的控制块(skb-> cb)来存储您的数据,它有40个字节供您处理(但不保证数据在网络层中有效)。

你可以这样做:
(struct my_head_struct *)(skb->cb)->a = 21;