linux tcp syncookie实现

原理及缺点

SYN Cookie是专门用来防范SYN Flood攻击的一种手段。它的原理是,在TCP服务器收到TCP SYN包并返回TCP SYN+ACK包时,不分配一个专门的数据区,而是根据这个SYN包计算出一个cookie值。
在收到TCP ACK包时,TCP服务器在根据那个cookie值检查这个TCP ACK包的合法性。如果合法,再分配专门的数据区进行处理未来的TCP连接。

syncookie只是验证了srcIp,srcPort,dstIp,dstPort,MSS,距离生成时间最大不超过两分钟
因为三次握手的时候syn包可能带了TCP扩展选项, 因为服务端不保存状态(比如支持sack,wscale等),因此就需要某种其他方式。
syncookie使用timestamp echo的方式在tcp timestamp中存储几个重要的扩张选项, 发送这个timestamp后,让客户端在ack中echo回来这个timestamp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* TCP Timestamp: 6 lowest bits of timestamp sent in the cookie SYN-ACK
* stores TCP options:
*
* MSB LSB
* | 31 ... 6 | 5 | 4 | 3 2 1 0 |
* | Timestamp | ECN | SACK | WScale |
*
* When we receive a valid cookie-ACK, we look at the echoed tsval (if
* any) to figure out which TCP options we should use for the rebuilt
* connection.
*
* A WScale setting of '0xf' (which is an invalid scaling value)
* means that original syn did not include the TCP window scaling option.
*/

这是内核中的一段注释, 显示了timestamp中存储的字段意义,因此其他不能存储在timestamp中的扩展项将不能在syncookie的方式中使用

也因此客户端syn包如果不带timestamp, 也就意味不能使用sack,wscale选项。
在windows上默认tcp timestamp不开启。。。
可以使以下命令查看和设置:

  • netsh int tcp show global
  • netsh int tcp show global timestamp=enabled

配置

net.ipv4.tcp_syncookies = 1 默认开启, 0为关闭
net.ipv4.tcp_syncookies = 2 表示无条件生成syncookie

实现

syn包的接收调用过程:tcp_v4_rcv->tcp_v4_do_rcv->tcp_rcv_state_process->tcp_v4_conn_request->tcp_conn_request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
int tcp_conn_request(struct request_sock_ops *rsk_ops, //tcp_request_sock_ops
const struct tcp_request_sock_ops *af_ops, //tcp_request_sock_ipv4_ops
struct sock *sk, struct sk_buff *skb)
{
__u32 isn = TCP_SKB_CB(skb)->tcp_tw_isn; // 非0表示发送到了timewait sock
if ((net->ipv4.sysctl_tcp_syncookies == 2 || //sysctl_tcp_syncookies=2无条件生成syncookie
inet_csk_reqsk_queue_is_full(sk)) && !isn) { //或者请求队列太长, 并且当前不是timewait sock
want_cookie = tcp_syn_flood_action(sk, skb, rsk_ops->slab_name); //sysctl_tcp_syncookies>0, 并未当前socket打印一次告警
if (!want_cookie) //want_cookie表示使用syncookie
goto drop; //队列满了,但不使用syncookie,则丢弃
}
req = inet_reqsk_alloc(rsk_ops, sk, !want_cookie); //分配request_sock, 进入TCP_NEW_SYN_RECV状态, want_cookie则不关联listen sock
tcp_parse_options(skb, &tmp_opt, 0, want_cookie ? NULL : &foc); //开启syncookie后则不用考虑fastopen, syncookie不允许使用tcp扩展
if (want_cookie && !tmp_opt.saw_tstamp) // 开启syncookie,但是请求不带timestamp的时候
tcp_clear_options(&tmp_opt); // 清楚wscale等选项
if (want_cookie) {
isn = cookie_init_sequence(af_ops, sk, skb, &req->mss); //cookie_v4_init_sequence生成syncookie,并作为ack的起始序号
req->cookie_ts = tmp_opt.tstamp_ok;
if (!tmp_opt.tstamp_ok)
inet_rsk(req)->ecn_ok = 0;
}
tcp_openreq_init_rwin(req, sk, dst); //设置初始化rwnd
if (!want_cookie)
inet_csk_reqsk_queue_hash_add(sk, req, TCP_TIMEOUT_INIT); //插入ehash,并设置定时器
af_ops->send_synack(sk, dst, &fl, req, &foc, //tcp_v4_send_synack
!want_cookie ? TCP_SYNACK_NORMAL :
TCP_SYNACK_COOKIE);
if (want_cookie) { //启用syncookie的话,可以直接释放req
reqsk_free(req);
return 0;
}
}
}

syncookie生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* MSS Values are chosen based on the 2011 paper
* 'An Analysis of TCP Maximum Segement Sizes' by S. Alcock and R. Nelson.
* Values ..
* .. lower than 536 are rare (< 0.2%)
* .. between 537 and 1299 account for less than < 1.5% of observed values
* .. in the 1300-1349 range account for about 15 to 20% of observed mss values
* .. exceeding 1460 are very rare (< 0.04%)
*
* 1460 is the single most frequently announced mss value (30 to 46% depending
* on monitor location). Table must be sorted.
*/
static __u16 const msstab[] = {
536,
1300,
1440, /* 1440, 1452: PPPoE */
1460,
};
#define TCP_SYNCOOKIE_PERIOD (60 * HZ)
static inline u32 tcp_cookie_time(void)
{
u64 val = get_jiffies_64();
do_div(val, TCP_SYNCOOKIE_PERIOD); //开机经过的分钟改数
return val;
}
__u32 cookie_v4_init_sequence(const struct sk_buff *skb, __u16 *mssp)
{
const struct iphdr *iph = ip_hdr(skb);
const struct tcphdr *th = tcp_hdr(skb);
return __cookie_v4_init_sequence(iph, th, mssp);
}
/*
* Generate a syncookie. mssp points to the mss, which is returned
* rounded down to the value encoded in the cookie.
*/
u32 __cookie_v4_init_sequence(const struct iphdr *iph, const struct tcphdr *th,
u16 *mssp)
{
int mssind;
const __u16 mss = *mssp;
for (mssind = ARRAY_SIZE(msstab) - 1; mssind ; mssind--) //概率从大到小,一般为1460,因此mssind=3
if (mss >= msstab[mssind])
break;
*mssp = msstab[mssind];
return secure_tcp_syn_cookie(iph->saddr, iph->daddr,
th->source, th->dest, ntohl(th->seq),
mssind);
}
static __u32 secure_tcp_syn_cookie(__be32 saddr, __be32 daddr, __be16 sport,
__be16 dport, __u32 sseq, __u32 data)
{
/*
* Compute the secure sequence number.
* The output should be:
* HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
* + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
* Where sseq is their sequence number and count increases every
* minute by 1.
* As an extra hack, we add a small "data" value that encodes the
* MSS into the second hash value.
*/
u32 count = tcp_cookie_time(); //开机经过的分钟数
return (cookie_hash(saddr, daddr, sport, dport, 0, 0) + //地址端口使用第一套密钥做hash
sseq + (count << COOKIEBITS) + //收到的tcp seq序号, 本机的时间
((cookie_hash(saddr, daddr, sport, dport, count, 1) + data)//地址端口增加时间参数使用第二套密钥做hash, 增加一个mss对应的参数
& COOKIEMASK));
}

内核随机生成了两个sha摘要的密钥,hash计算后并保存在percpu变量中,取其中部分作为结果
因此syncookie的开销主要是两次sha digest的开销

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
static u32 syncookie_secret[2][16-4+SHA_DIGEST_WORDS] __read_mostly;
static DEFINE_PER_CPU(__u32 [16 + 5 + SHA_WORKSPACE_WORDS], ipv4_cookie_scratch);
static u32 cookie_hash(__be32 saddr, __be32 daddr, __be16 sport, __be16 dport,
u32 count, int c)
{
__u32 *tmp;
net_get_random_once(syncookie_secret, sizeof(syncookie_secret));
tmp = this_cpu_ptr(ipv4_cookie_scratch);
memcpy(tmp + 4, syncookie_secret[c], sizeof(syncookie_secret[c]));
tmp[0] = (__force u32)saddr;
tmp[1] = (__force u32)daddr;
tmp[2] = ((__force u32)sport << 16) + (__force u32)dport;
tmp[3] = count;
sha_transform(tmp + 16, (__u8 *)tmp, tmp + 16 + 5);
return tmp[17];
}

syncookie验证

在服务端收到三次握手最后的ack后,tcp_v4_do_rcv调用tcp_v4_cookie_check来判断syncookie的有效性,有效则创建新家连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
static struct sock *tcp_v4_cookie_check(struct sock *sk, struct sk_buff *skb)
{
#ifdef CONFIG_SYN_COOKIES
const struct tcphdr *th = tcp_hdr(skb);
if (!th->syn)
sk = cookie_v4_check(sk, skb);
#endif
return sk;
}
struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
{
if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies || !th->ack || th->rst) //没开启syncookie
goto out;
if (tcp_synq_no_recent_overflow(sk)) //最近两分钟内没有使用syncookie,进入正常的握手完成
goto out;
mss = __cookie_v4_check(ip_hdr(skb), th, cookie); //syncookie验证
if (mss == 0) { //syncookie无效
__NET_INC_STATS(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED);
goto out;
}
__NET_INC_STATS(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV);
memset(&tcp_opt, 0, sizeof(tcp_opt));
tcp_parse_options(skb, &tcp_opt, 0, NULL);
if (!cookie_timestamp_decode(&tcp_opt))
goto out; //ehco回来的ts选项解析有问题, 进入正常的握手处理
ret = NULL;
req = inet_reqsk_alloc(&tcp_request_sock_ops, sk, false); /* for safety */ //syncookie验证成功, 创建req sock
if (!req)
goto out;
ireq = inet_rsk(req);
...
ireq->snd_wscale = tcp_opt.snd_wscale; //使用timestamp中解析出的扩展项
ireq->sack_ok = tcp_opt.sack_ok;
ireq->wscale_ok = tcp_opt.wscale_ok;
ireq->tstamp_ok = tcp_opt.saw_tstamp;
req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0;
treq->tfo_listener = false;
...
ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), &rt->dst);
ret = tcp_get_cookie_sock(sk, skb, req, &rt->dst);
/* ip_queue_xmit() depends on our flow being setup
* Normal sockets get it right from inet_csk_route_child_sock()
*/
if (ret)
inet_sk(ret)->cork.fl.u.ip4 = fl4;
out: return ret;
}
struct sock *tcp_get_cookie_sock(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct sock *child;
bool own_req;
child = icsk->icsk_af_ops->syn_recv_sock(sk, skb, req, dst, //tcp_v4_syn_recv_sock, 创建new sock(TCP_SYN_RECV), 并插入ehash中
NULL, &own_req);
if (child) {
atomic_set(&req->rsk_refcnt, 1);
sock_rps_save_rxhash(child, skb);
inet_csk_reqsk_queue_add(sk, req, child); //握手完成等待被accept
} else {
reqsk_free(req);
}
return child;
}

这时候newsock是TCP_SYN_RECV状态,然后继续在tcp_v4_do_rcv中调用tcp_child_process,最终在tcp_rcv_state_process中进入TCP_ESTABLISHED状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//返回syncookie计算时的data,也就是mssind,MSS=1460时为3
static __u32 check_tcp_syn_cookie(__u32 cookie, __be32 saddr, __be32 daddr,
__be16 sport, __be16 dport, __u32 sseq)
{
u32 diff, count = tcp_cookie_time();
/* Strip away the layers from the cookie */
cookie -= cookie_hash(saddr, daddr, sport, dport, 0, 0) + sseq;
/* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
diff = (count - (cookie >> COOKIEBITS)) & ((__u32) -1 >> COOKIEBITS);//距离上一次syncookie发送经历的分钟数
if (diff >= MAX_SYNCOOKIE_AGE) //超过2分钟,因为tcp_cookie_time()只是舍去秒数部分,可能经历了一分钟时间只过了不到1秒,因此最少需要2分钟
return (__u32)-1;
return (cookie -
cookie_hash(saddr, daddr, sport, dport, count - diff, 1))
& COOKIEMASK; /* Leaving the data behind */
}
//通过mssindx是否在有效返回内,来判断syncookie是否有效
int __cookie_v4_check(const struct iphdr *iph, const struct tcphdr *th,
u32 cookie)
{
__u32 seq = ntohl(th->seq) - 1; //syncookie的syn
__u32 mssind = check_tcp_syn_cookie(cookie, iph->saddr, iph->daddr,
th->source, th->dest, seq);
return mssind < ARRAY_SIZE(msstab) ? msstab[mssind] : 0;
}

syncookie相关告警日志及解决

  • “TCP Possible SYN flooding on port 80. ip. Check SNMP counters.”
    在tcp_syn_flood_action中被打印,这时候是当前listen socket中syn请求队列已经满了,第一次使用syncookie的时候被打印
    解决: 如果syn队列太小,并且内存足够,需要增加syn队列的长度:
    net.core.somaxconn=10000, 根据需要配置,默认128太小了, 先考虑增大该选项再考虑开启syncookie

  • net.ipv4.tcp_max_syn_backlog = 128
    当syn请求队列达到tcp_max_syn_backlog 3/4的时候, 需要调用tcp_peer_is_proven验证,主要在tcp_metric中检查连接的可靠历史信息,来确认对方的真实性。 验证不过则直接丢弃.
    当对应的tcp_metric,比如过去没连过或者tcp_metric表项满了以致过去的被淘汰等,都会验证失败。
    解决: 跟net.core.somaxconn一起调大, 再考虑syncookie

  • net.ipv4.tcp_synack_retries = 5
    实际上也就增加了syn状态数据的保存时间,在连接数较大的时候可以略微调小

  • net.ipv4.tcp_abort_on_overflow = 0
    默认值意味着当syn请求队列满了或内存不够,无法新建连接的时候, 只是丢弃包, 这样client就会后续重传
    开启则意味着发送RST, 不让client继续