gpt4 book ai didi

sockets - LKM 从数据包中查找 tcp_sock

转载 作者:可可西里 更新时间:2023-11-01 02:54:38 25 4
gpt4 key购买 nike

我的目标是编写一个 LKM(Linux 内核模块)来拦截所有 TCP 数据包、查找 tcp_sock 结构并根据某些条件从 tcp_sock 结构(例如:tcpsock->snd_una)记录一些信息。

这就是我试图实现这一目标的方式:我在 ubunutu 上使用 netfilter 进行拦截(下面的代码)但是有没有办法访问 tcp_sock 结构(在代码中查找 NOTE)?

我对 netfilter 并不挑剔。请建议是否有任何其他编写 LKM 的方法来实现这一点。它必须是 LKM。

unsigned int ip_packets_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 *tcp_hdr;
struct tcp_sock *tcpsock;

if (!skb) {
return NF_ACCEPT;
}

if (ipp->protocol == IPPROTO_TCP ) { // Incomming packet is TCP
tcp_hdr = (struct tcphdr *) ((__u32 *)ipp + ipp->ihl);
tcpsock = (struct tcp_sock *) skb->sk;

if(ntohs(tcp_hdr->dest) != INTERESTED_PORT) {
return NF_ACCEPT;
}

printk("TCP ports: source: %d, dest: %d \n", ntohs(tcp_hdr->source),
ntohs(tcp_hdr->dest));

if(tcp_hdr->syn || tcp_hdr->fin || tcp_hdr->rst) {
printk("Flag: %s %s %s\n", tcp_hdr->syn? "SYN" : "",
tcp_hdr->fin? "FIN" : "",
tcp_hdr->rst? "RST" : "");
return NF_ACCEPT;
}

// **NOTE**
// skb->sk is NULL at this point.
// Get tcp_sock for this connection.
} else {
printk("Its not TCP\n");
}

return NF_ACCEPT;
}

最佳答案

我能够通过查找 inet 哈希表(下面的代码片段)来实现它。我是这个例子中的服务器。确保在 3 次握手完成后查找。

const struct iphdr *iph;
const struct tcphdr *th;
struct sock *sk = NULL;
struct tcp_sock *tp;

.
.
.
.

sk = __inet_lookup_established(dev_net(skb->dev), &tcp_hashinfo,
iph->saddr, th->source,
iph->daddr, ntohs(th->dest),
skb->skb_iif);

// Sanity checks here.

tp = tcp_sk(sk);

关于sockets - LKM 从数据包中查找 tcp_sock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20862967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com