如何在我的自定义内核模块

时间:2017-06-26 04:10:28

标签: linux kernel

我构建了一个名为" xt_hello.ko"的新内核模块(2.6.32 CentOS6.5),我想将一些自定义数据发送到nflog,所以我更改了skb->cb in我的模块,nflog可以正确读取我的数据。

问题:我发现在{t} netlink等中使用了cb字段,我的模块可以对它们产生一些不良影响吗?

sk_buff的定义:

struct sk_buff {
    /* These two members must be first. */
    struct sk_buff      *next;
    struct sk_buff      *prev;
    struct sock     *sk;
    ktime_t         tstamp;
    struct net_device   *dev;
    unsigned long       _skb_dst;
 #ifdef CONFIG_XFRM
    struct  sec_path    *sp;
 #endif
     /*
     * This is the control buffer. It is free to use for every
     * layer. Please put your private variables there. If you
     * want to keep them across layers you have to do a skb_clone()
     * first. This is owned by whoever has the skb queued ATM.
     */
    char            cb[48];
    ... skip ...

netlink 中cb的定义:

 #define NETLINK_CB(skb)        (*(struct netlink_skb_parms*)&((skb)->cb))
 #define NETLINK_CREDS(skb) (&NETLINK_CB((skb)).creds)

我的内核模块中的核心代码:

我的定义:

struct xt_ndpi_cb {
  u_int16_t protocol_detected ;
  u_int16_t ndpi_proto;
 }xt_ndpi_cb_t;
 #define NDPI_CB(skb)            (*(struct xt_ndpi_cb*)&((skb)->cb))
 #define NDPI_CB_RECORD(skb,entry)    NDPI_CB(skb).ndpi_proto = entry.VALUEA; NDPI_CB(skb).protocol_detected = entry.VALUEB;

/*core func*/
 static bool ndpi_process_packet_tg(const struct sk_buff *_skb, const struct 
 xt_ndpi_tginfo *info, struct nf_conn *ct) {
    ...skip...
    if (/*condition*/)
       NDPI_CB_RECORD(_skb, entry)
}

内核模块.c:

static bool ndpi_match(const struct sk_buff *skb, struct xt_action_param *par){
   bool verdict;
   struct nf_conn * ct;
   enum ip_conntrack_info ctinfo;
   const struct xt_ndpi_protocols *info = par->matchinfo;
   ct = nf_ct_get(skb, &ctinfo);
   if((ct == NULL) || (skb == NULL)) {
     return(false); 
 #if LINUX_VERSION_CODE < KERNEL_VERSION(3,0,0)
   } else if (nf_ct_is_untracked(skb)) {
 #else
   } else if(nf_ct_is_untracked(ct)) {
 #endif
     return false; 
   }
   /*change cb in this func*/
   verdict = ndpi_process_packet(skb, info, ct );
   return(verdict);
}
static struct xt_match ndpi_regs[] __read_mostly = {
  {
    .name      = "ndpi",
    .revision  = 0,
    .family    = NFPROTO_IPV4,
    .match     = ndpi_match,
    .matchsize = sizeof(struct xt_ndpi_protocols),
    .me        = THIS_MODULE,
  }
};

在xt_NFLOG.c中使用:

static unsigned int
nflog_tg(struct sk_buff *skb, const struct xt_target_param *par)
{
    char buf[64+16]; /**my buf/
    const struct xt_nflog_info *info = par->targinfo;
    ...skip...
    sprintf(buf,"%s MYID=%u",info->prefix,NDPI_CB(_skb).ndpi_proto); /*NFLOG can get right cb value*/
    ...skip...
}

0 个答案:

没有答案