您的位置:首页 > 理论基础 > 计算机网络

Libnids中tcp重组的实现

2016-06-22 12:52 471 查看
先熟悉相关结构体

struct tuple4 : tcp连接

struct half_stream: 半个tcp会话,也是一个方向上的tcp会话

struct tcp_stream: 一个完整的tcp会话

process_tcp函数处理tcp数据包,tcp会话重组就是在这个函数完成的。

//在哈希表中查找tcp会话,如果不存在则新建一个tcp会话
if (!(a_tcp = find_stream(this_tcphdr, this_iphdr, &from_client))) {
if ((this_tcphdr->th_flags & TH_SYN) &&
!(this_tcphdr->th_flags & TH_ACK) &&
!(this_tcphdr->th_flags & TH_RST))
add_new_tcp(this_tcphdr, this_iphdr);
return;
}
//根据数据流方向,将发送和接收设置好
if (from_client) {
snd = &a_tcp->client;
rcv = &a_tcp->server;
}
else {
rcv = &a_tcp->client;
snd = &a_tcp->server;
}

if ((this_tcphdr->th_flags & TH_SYN)) {
if (from_client || a_tcp->client.state != TCP_SYN_SENT ||
a_tcp->server.state != TCP_CLOSE || !(this_tcphdr->th_flags & TH_ACK))
return;

if (a_tcp->client.seq != ntohl(this_tcphdr->th_ack))
return;


find_stream函数的实现代码如下,功能是在哈希表中正向查找和反向查找tcp会话。

struct tcp_stream *
find_stream(struct tcphdr * this_tcphdr, struct ip * this_iphdr,
int *from_client)
{
struct tuple4 this_addr, reversed;
struct tcp_stream *a_tcp;

this_addr.source = ntohs(this_tcphdr->th_sport);
this_addr.dest = ntohs(this_tcphdr->th_dport);
this_addr.saddr = this_iphdr->ip_src.s_addr;
this_addr.daddr = this_iphdr->ip_dst.s_addr;
a_tcp = nids_find_tcp_stream(&this_addr);
if (a_tcp) {
*from_client = 1;
return a_tcp;
}
reversed.source = ntohs(this_tcphdr->th_dport);
reversed.dest = ntohs(this_tcphdr->th_sport);
reversed.saddr = this_iphdr->ip_dst.s_addr;
reversed.daddr = this_iphdr->ip_src.s_addr;
a_tcp = nids_find_tcp_stream(&reversed);
if (a_tcp) {
*from_client = 0;
return a_tcp;
}
return 0;
}


关键思路:

tcp会话哈希表 正向查找 反向查找 如果都没有则建立新的tcp会话节点加入到哈希表中

查找的key是四元组,srcip,dstip,srcport,dstport.

后续自己完成代码的编写功能。加油!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息