1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Syncookies implementation for the Linux kernel
4 *
5 * Copyright (C) 1997 Andi Kleen
6 * Based on ideas by D.J.Bernstein and Eric Schenk.
7 */
8
9 #include <linux/tcp.h>
10 #include <linux/siphash.h>
11 #include <linux/kernel.h>
12 #include <linux/export.h>
13 #include <net/secure_seq.h>
14 #include <net/tcp.h>
15 #include <net/route.h>
16
17 static siphash_aligned_key_t syncookie_secret[2];
18
19 #define COOKIEBITS 24 /* Upper bits store count */
20 #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
21
22 /* TCP Timestamp: 6 lowest bits of timestamp sent in the cookie SYN-ACK
23 * stores TCP options:
24 *
25 * MSB LSB
26 * | 31 ... 6 | 5 | 4 | 3 2 1 0 |
27 * | Timestamp | ECN | SACK | WScale |
28 *
29 * When we receive a valid cookie-ACK, we look at the echoed tsval (if
30 * any) to figure out which TCP options we should use for the rebuilt
31 * connection.
32 *
33 * A WScale setting of '0xf' (which is an invalid scaling value)
34 * means that original syn did not include the TCP window scaling option.
35 */
36 #define TS_OPT_WSCALE_MASK 0xf
37 #define TS_OPT_SACK BIT(4)
38 #define TS_OPT_ECN BIT(5)
39 /* There is no TS_OPT_TIMESTAMP:
40 * if ACK contains timestamp option, we already know it was
41 * requested/supported by the syn/synack exchange.
42 */
43 #define TSBITS 6
44
cookie_hash(__be32 saddr,__be32 daddr,__be16 sport,__be16 dport,u32 count,int c)45 static u32 cookie_hash(__be32 saddr, __be32 daddr, __be16 sport, __be16 dport,
46 u32 count, int c)
47 {
48 net_get_random_once(syncookie_secret, sizeof(syncookie_secret));
49 return siphash_4u32((__force u32)saddr, (__force u32)daddr,
50 (__force u32)sport << 16 | (__force u32)dport,
51 count, &syncookie_secret[c]);
52 }
53
54
55 /*
56 * when syncookies are in effect and tcp timestamps are enabled we encode
57 * tcp options in the lower bits of the timestamp value that will be
58 * sent in the syn-ack.
59 * Since subsequent timestamps use the normal tcp_time_stamp value, we
60 * must make sure that the resulting initial timestamp is <= tcp_time_stamp.
61 */
cookie_init_timestamp(struct request_sock * req,u64 now)62 u64 cookie_init_timestamp(struct request_sock *req, u64 now)
63 {
64 const struct inet_request_sock *ireq = inet_rsk(req);
65 u64 ts, ts_now = tcp_ns_to_ts(now);
66 u32 options = 0;
67
68 options = ireq->wscale_ok ? ireq->snd_wscale : TS_OPT_WSCALE_MASK;
69 if (ireq->sack_ok)
70 options |= TS_OPT_SACK;
71 if (ireq->ecn_ok)
72 options |= TS_OPT_ECN;
73
74 ts = (ts_now >> TSBITS) << TSBITS;
75 ts |= options;
76 if (ts > ts_now)
77 ts -= (1UL << TSBITS);
78
79 return ts * (NSEC_PER_SEC / TCP_TS_HZ);
80 }
81
82
secure_tcp_syn_cookie(__be32 saddr,__be32 daddr,__be16 sport,__be16 dport,__u32 sseq,__u32 data)83 static __u32 secure_tcp_syn_cookie(__be32 saddr, __be32 daddr, __be16 sport,
84 __be16 dport, __u32 sseq, __u32 data)
85 {
86 /*
87 * Compute the secure sequence number.
88 * The output should be:
89 * HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
90 * + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
91 * Where sseq is their sequence number and count increases every
92 * minute by 1.
93 * As an extra hack, we add a small "data" value that encodes the
94 * MSS into the second hash value.
95 */
96 u32 count = tcp_cookie_time();
97 return (cookie_hash(saddr, daddr, sport, dport, 0, 0) +
98 sseq + (count << COOKIEBITS) +
99 ((cookie_hash(saddr, daddr, sport, dport, count, 1) + data)
100 & COOKIEMASK));
101 }
102
103 /*
104 * This retrieves the small "data" value from the syncookie.
105 * If the syncookie is bad, the data returned will be out of
106 * range. This must be checked by the caller.
107 *
108 * The count value used to generate the cookie must be less than
109 * MAX_SYNCOOKIE_AGE minutes in the past.
110 * The return value (__u32)-1 if this test fails.
111 */
check_tcp_syn_cookie(__u32 cookie,__be32 saddr,__be32 daddr,__be16 sport,__be16 dport,__u32 sseq)112 static __u32 check_tcp_syn_cookie(__u32 cookie, __be32 saddr, __be32 daddr,
113 __be16 sport, __be16 dport, __u32 sseq)
114 {
115 u32 diff, count = tcp_cookie_time();
116
117 /* Strip away the layers from the cookie */
118 cookie -= cookie_hash(saddr, daddr, sport, dport, 0, 0) + sseq;
119
120 /* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
121 diff = (count - (cookie >> COOKIEBITS)) & ((__u32) -1 >> COOKIEBITS);
122 if (diff >= MAX_SYNCOOKIE_AGE)
123 return (__u32)-1;
124
125 return (cookie -
126 cookie_hash(saddr, daddr, sport, dport, count - diff, 1))
127 & COOKIEMASK; /* Leaving the data behind */
128 }
129
130 /*
131 * MSS Values are chosen based on the 2011 paper
132 * 'An Analysis of TCP Maximum Segement Sizes' by S. Alcock and R. Nelson.
133 * Values ..
134 * .. lower than 536 are rare (< 0.2%)
135 * .. between 537 and 1299 account for less than < 1.5% of observed values
136 * .. in the 1300-1349 range account for about 15 to 20% of observed mss values
137 * .. exceeding 1460 are very rare (< 0.04%)
138 *
139 * 1460 is the single most frequently announced mss value (30 to 46% depending
140 * on monitor location). Table must be sorted.
141 */
142 static __u16 const msstab[] = {
143 536,
144 1300,
145 1440, /* 1440, 1452: PPPoE */
146 1460,
147 };
148
149 /*
150 * Generate a syncookie. mssp points to the mss, which is returned
151 * rounded down to the value encoded in the cookie.
152 */
__cookie_v4_init_sequence(const struct iphdr * iph,const struct tcphdr * th,u16 * mssp)153 u32 __cookie_v4_init_sequence(const struct iphdr *iph, const struct tcphdr *th,
154 u16 *mssp)
155 {
156 int mssind;
157 const __u16 mss = *mssp;
158
159 for (mssind = ARRAY_SIZE(msstab) - 1; mssind ; mssind--)
160 if (mss >= msstab[mssind])
161 break;
162 *mssp = msstab[mssind];
163
164 return secure_tcp_syn_cookie(iph->saddr, iph->daddr,
165 th->source, th->dest, ntohl(th->seq),
166 mssind);
167 }
168 EXPORT_SYMBOL_GPL(__cookie_v4_init_sequence);
169
cookie_v4_init_sequence(const struct sk_buff * skb,__u16 * mssp)170 __u32 cookie_v4_init_sequence(const struct sk_buff *skb, __u16 *mssp)
171 {
172 const struct iphdr *iph = ip_hdr(skb);
173 const struct tcphdr *th = tcp_hdr(skb);
174
175 return __cookie_v4_init_sequence(iph, th, mssp);
176 }
177
178 /*
179 * Check if a ack sequence number is a valid syncookie.
180 * Return the decoded mss if it is, or 0 if not.
181 */
__cookie_v4_check(const struct iphdr * iph,const struct tcphdr * th,u32 cookie)182 int __cookie_v4_check(const struct iphdr *iph, const struct tcphdr *th,
183 u32 cookie)
184 {
185 __u32 seq = ntohl(th->seq) - 1;
186 __u32 mssind = check_tcp_syn_cookie(cookie, iph->saddr, iph->daddr,
187 th->source, th->dest, seq);
188
189 return mssind < ARRAY_SIZE(msstab) ? msstab[mssind] : 0;
190 }
191 EXPORT_SYMBOL_GPL(__cookie_v4_check);
192
tcp_get_cookie_sock(struct sock * sk,struct sk_buff * skb,struct request_sock * req,struct dst_entry * dst,u32 tsoff)193 struct sock *tcp_get_cookie_sock(struct sock *sk, struct sk_buff *skb,
194 struct request_sock *req,
195 struct dst_entry *dst, u32 tsoff)
196 {
197 struct inet_connection_sock *icsk = inet_csk(sk);
198 struct sock *child;
199 bool own_req;
200
201 child = icsk->icsk_af_ops->syn_recv_sock(sk, skb, req, dst,
202 NULL, &own_req);
203 if (child) {
204 refcount_set(&req->rsk_refcnt, 1);
205 tcp_sk(child)->tsoffset = tsoff;
206 sock_rps_save_rxhash(child, skb);
207
208 if (rsk_drop_req(req)) {
209 reqsk_put(req);
210 return child;
211 }
212
213 if (inet_csk_reqsk_queue_add(sk, req, child))
214 return child;
215
216 bh_unlock_sock(child);
217 sock_put(child);
218 }
219 __reqsk_free(req);
220
221 return NULL;
222 }
223 EXPORT_SYMBOL(tcp_get_cookie_sock);
224
225 /*
226 * when syncookies are in effect and tcp timestamps are enabled we stored
227 * additional tcp options in the timestamp.
228 * This extracts these options from the timestamp echo.
229 *
230 * return false if we decode a tcp option that is disabled
231 * on the host.
232 */
cookie_timestamp_decode(const struct net * net,struct tcp_options_received * tcp_opt)233 bool cookie_timestamp_decode(const struct net *net,
234 struct tcp_options_received *tcp_opt)
235 {
236 /* echoed timestamp, lowest bits contain options */
237 u32 options = tcp_opt->rcv_tsecr;
238
239 if (!tcp_opt->saw_tstamp) {
240 tcp_clear_options(tcp_opt);
241 return true;
242 }
243
244 if (!READ_ONCE(net->ipv4.sysctl_tcp_timestamps))
245 return false;
246
247 tcp_opt->sack_ok = (options & TS_OPT_SACK) ? TCP_SACK_SEEN : 0;
248
249 if (tcp_opt->sack_ok && !READ_ONCE(net->ipv4.sysctl_tcp_sack))
250 return false;
251
252 if ((options & TS_OPT_WSCALE_MASK) == TS_OPT_WSCALE_MASK)
253 return true; /* no window scaling */
254
255 tcp_opt->wscale_ok = 1;
256 tcp_opt->snd_wscale = options & TS_OPT_WSCALE_MASK;
257
258 return READ_ONCE(net->ipv4.sysctl_tcp_window_scaling) != 0;
259 }
260 EXPORT_SYMBOL(cookie_timestamp_decode);
261
cookie_ecn_ok(const struct tcp_options_received * tcp_opt,const struct net * net,const struct dst_entry * dst)262 bool cookie_ecn_ok(const struct tcp_options_received *tcp_opt,
263 const struct net *net, const struct dst_entry *dst)
264 {
265 bool ecn_ok = tcp_opt->rcv_tsecr & TS_OPT_ECN;
266
267 if (!ecn_ok)
268 return false;
269
270 if (READ_ONCE(net->ipv4.sysctl_tcp_ecn))
271 return true;
272
273 return dst_feature(dst, RTAX_FEATURE_ECN);
274 }
275 EXPORT_SYMBOL(cookie_ecn_ok);
276
cookie_tcp_reqsk_alloc(const struct request_sock_ops * ops,const struct tcp_request_sock_ops * af_ops,struct sock * sk,struct sk_buff * skb)277 struct request_sock *cookie_tcp_reqsk_alloc(const struct request_sock_ops *ops,
278 const struct tcp_request_sock_ops *af_ops,
279 struct sock *sk,
280 struct sk_buff *skb)
281 {
282 struct tcp_request_sock *treq;
283 struct request_sock *req;
284
285 if (sk_is_mptcp(sk))
286 req = mptcp_subflow_reqsk_alloc(ops, sk, false);
287 else
288 req = inet_reqsk_alloc(ops, sk, false);
289
290 if (!req)
291 return NULL;
292
293 treq = tcp_rsk(req);
294
295 /* treq->af_specific might be used to perform TCP_MD5 lookup */
296 treq->af_specific = af_ops;
297
298 treq->syn_tos = TCP_SKB_CB(skb)->ip_dsfield;
299 #if IS_ENABLED(CONFIG_MPTCP)
300 treq->is_mptcp = sk_is_mptcp(sk);
301 if (treq->is_mptcp) {
302 int err = mptcp_subflow_init_cookie_req(req, sk, skb);
303
304 if (err) {
305 reqsk_free(req);
306 return NULL;
307 }
308 }
309 #endif
310
311 return req;
312 }
313 EXPORT_SYMBOL_GPL(cookie_tcp_reqsk_alloc);
314
315 /* On input, sk is a listener.
316 * Output is listener if incoming packet would not create a child
317 * NULL if memory could not be allocated.
318 */
cookie_v4_check(struct sock * sk,struct sk_buff * skb)319 struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
320 {
321 struct ip_options *opt = &TCP_SKB_CB(skb)->header.h4.opt;
322 struct tcp_options_received tcp_opt;
323 struct inet_request_sock *ireq;
324 struct tcp_request_sock *treq;
325 struct tcp_sock *tp = tcp_sk(sk);
326 const struct tcphdr *th = tcp_hdr(skb);
327 __u32 cookie = ntohl(th->ack_seq) - 1;
328 struct sock *ret = sk;
329 struct request_sock *req;
330 int full_space, mss;
331 struct rtable *rt;
332 __u8 rcv_wscale;
333 struct flowi4 fl4;
334 u32 tsoff = 0;
335
336 if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies) ||
337 !th->ack || th->rst)
338 goto out;
339
340 if (tcp_synq_no_recent_overflow(sk))
341 goto out;
342
343 mss = __cookie_v4_check(ip_hdr(skb), th, cookie);
344 if (mss == 0) {
345 __NET_INC_STATS(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED);
346 goto out;
347 }
348
349 __NET_INC_STATS(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV);
350
351 /* check for timestamp cookie support */
352 memset(&tcp_opt, 0, sizeof(tcp_opt));
353 tcp_parse_options(sock_net(sk), skb, &tcp_opt, 0, NULL);
354
355 if (tcp_opt.saw_tstamp && tcp_opt.rcv_tsecr) {
356 tsoff = secure_tcp_ts_off(sock_net(sk),
357 ip_hdr(skb)->daddr,
358 ip_hdr(skb)->saddr);
359 tcp_opt.rcv_tsecr -= tsoff;
360 }
361
362 if (!cookie_timestamp_decode(sock_net(sk), &tcp_opt))
363 goto out;
364
365 ret = NULL;
366 req = cookie_tcp_reqsk_alloc(&tcp_request_sock_ops,
367 &tcp_request_sock_ipv4_ops, sk, skb);
368 if (!req)
369 goto out;
370
371 ireq = inet_rsk(req);
372 treq = tcp_rsk(req);
373 treq->rcv_isn = ntohl(th->seq) - 1;
374 treq->snt_isn = cookie;
375 treq->ts_off = 0;
376 treq->txhash = net_tx_rndhash();
377 req->mss = mss;
378 ireq->ir_num = ntohs(th->dest);
379 ireq->ir_rmt_port = th->source;
380 sk_rcv_saddr_set(req_to_sk(req), ip_hdr(skb)->daddr);
381 sk_daddr_set(req_to_sk(req), ip_hdr(skb)->saddr);
382 ireq->ir_mark = inet_request_mark(sk, skb);
383 ireq->snd_wscale = tcp_opt.snd_wscale;
384 ireq->sack_ok = tcp_opt.sack_ok;
385 ireq->wscale_ok = tcp_opt.wscale_ok;
386 ireq->tstamp_ok = tcp_opt.saw_tstamp;
387 req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0;
388 treq->snt_synack = 0;
389 treq->tfo_listener = false;
390
391 if (IS_ENABLED(CONFIG_SMC))
392 ireq->smc_ok = 0;
393
394 ireq->ir_iif = inet_request_bound_dev_if(sk, skb);
395
396 /* We throwed the options of the initial SYN away, so we hope
397 * the ACK carries the same options again (see RFC1122 4.2.3.8)
398 */
399 RCU_INIT_POINTER(ireq->ireq_opt, tcp_v4_save_options(sock_net(sk), skb));
400
401 if (security_inet_conn_request(sk, skb, req)) {
402 reqsk_free(req);
403 goto out;
404 }
405
406 req->num_retrans = 0;
407
408 /*
409 * We need to lookup the route here to get at the correct
410 * window size. We should better make sure that the window size
411 * hasn't changed since we received the original syn, but I see
412 * no easy way to do this.
413 */
414 flowi4_init_output(&fl4, ireq->ir_iif, ireq->ir_mark,
415 RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, IPPROTO_TCP,
416 inet_sk_flowi_flags(sk),
417 opt->srr ? opt->faddr : ireq->ir_rmt_addr,
418 ireq->ir_loc_addr, th->source, th->dest, sk->sk_uid);
419 security_req_classify_flow(req, flowi4_to_flowi_common(&fl4));
420 rt = ip_route_output_key(sock_net(sk), &fl4);
421 if (IS_ERR(rt)) {
422 reqsk_free(req);
423 goto out;
424 }
425
426 /* Try to redo what tcp_v4_send_synack did. */
427 req->rsk_window_clamp = tp->window_clamp ? :dst_metric(&rt->dst, RTAX_WINDOW);
428 /* limit the window selection if the user enforce a smaller rx buffer */
429 full_space = tcp_full_space(sk);
430 if (sk->sk_userlocks & SOCK_RCVBUF_LOCK &&
431 (req->rsk_window_clamp > full_space || req->rsk_window_clamp == 0))
432 req->rsk_window_clamp = full_space;
433
434 tcp_select_initial_window(sk, full_space, req->mss,
435 &req->rsk_rcv_wnd, &req->rsk_window_clamp,
436 ireq->wscale_ok, &rcv_wscale,
437 dst_metric(&rt->dst, RTAX_INITRWND));
438
439 ireq->rcv_wscale = rcv_wscale;
440 ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), &rt->dst);
441
442 ret = tcp_get_cookie_sock(sk, skb, req, &rt->dst, tsoff);
443 /* ip_queue_xmit() depends on our flow being setup
444 * Normal sockets get it right from inet_csk_route_child_sock()
445 */
446 if (ret)
447 inet_sk(ret)->cork.fl.u.ip4 = fl4;
448 out: return ret;
449 }
450