簡體   English   中英

C - Linux - 內核模塊 - TCP頭

[英]C - Linux - kernel module - TCP header

我正在嘗試創建linux內核模塊,它將檢查傳入的數據包。 目前,我正在提取數據包的TCP頭並讀取源和目標端口 - >但是我得到的值不正確。 我有鈎功能:

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 *)) 
{
    struct iphdr *ipp = (struct iphdr *)skb_network_header(skb);
    struct tcphdr *hdr;
    /* Using this to filter data from another machine */
    unsigned long ok_ip = 2396891328;

    /* Some problem, empty network packet. Stop it now. */
    if (!skb)
        return NF_ACCEPT;

    /* Just to track only packets coming from 1 IP */
    if (ipp->saddr != ok_ip)
        return NF_ACCEPT;

    /* Incomming packet is TCP */
    if (ipp->protocol == IPPROTO_TCP) {
        hdr = (struct tcphdr *) skb_transport_header(skb);
        printk(" TCP ports: source: %d, dest: %d .\n", ntohs(hdr->source), 
                                                       ntohs(hdr->dest));
    }
}

現在,當我嘗試telnet端口21 (我沒有收聽):

[ 4252.961912]  TCP ports: source: 17664, dest: 52 .
[ 4253.453978]  TCP ports: source: 17664, dest: 52 .
[ 4253.953204]  TCP ports: source: 17664, dest: 48 .

當我telnet端口22 - SSH deamon在那里聽:

[ 4299.239940]  TCP ports: source: 17664, dest: 52 .
[ 4299.240527]  TCP ports: source: 17664, dest: 40 .
[ 4299.552566]  TCP ports: source: 17664, dest: 40 .

從輸出可見我得到了非常奇怪的結果,任何人都知道問題來自哪里? 當我編譯模塊時,我沒有錯誤/警告。 內核版本(標題):3.7.10。 不使用SELinux或類似的。

我遇到了為網絡類編寫小型防火牆的同樣問題,我剛剛發現了我遇到的問題。 我正在強制轉換tcp標頭。 嘗試轉換為tcp然后訪問端口。

這是它的代碼片段

struct iphdr *ip_header;       // ip header struct
struct tcphdr *tcp_header;     // tcp header struct
struct udphdr *udp_header;     // udp header struct
struct sk_buff *sock_buff;

unsigned int sport ,
             dport;


sock_buff = skb;

if (!sock_buff)
    return NF_ACCEPT;

ip_header = (struct iphdr *)skb_network_header(sock_buff);
if (!ip_header)
    return NF_ACCEPT;


//if TCP PACKET
if(ip_header->protocol==IPPROTO_TCP)
{
    //tcp_header = (struct tcphdr *)skb_transport_header(sock_buff); //doing the cast this way gave me the same problem

    tcp_header= (struct tcphdr *)((__u32 *)ip_header+ ip_header->ihl); //this fixed the problem

    sport = htons((unsigned short int) tcp_header->source); //sport now has the source port
    dport = htons((unsigned short int) tcp_header->dest);   //dport now has the dest port
}

要從套接字緩沖區( skb )獲取IP頭或TCP頭,只需應用函數ip_hdr(skb)tcp_hdr(skb)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM