xref: /freebsd/sys/netinet/tcp_syncache.c (revision ee2ea5ceafed78a5bd9810beb9e3ca927180c226)
1 /*-
2  * Copyright (c) 2001 Networks Associates Technology, Inc.
3  * All rights reserved.
4  *
5  * This software was developed for the FreeBSD Project by Jonathan Lemon
6  * and NAI Labs, the Security Research Division of Network Associates, Inc.
7  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
8  * DARPA CHATS research program.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. The name of the author may not be used to endorse or promote
19  *    products derived from this software without specific prior written
20  *    permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * $FreeBSD$
35  */
36 
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/sysctl.h>
44 #include <sys/malloc.h>
45 #include <sys/mbuf.h>
46 #include <sys/md5.h>
47 #include <sys/proc.h>		/* for proc0 declaration */
48 #include <sys/random.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 
52 #include <net/if.h>
53 #include <net/route.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
58 #include <netinet/in_var.h>
59 #include <netinet/in_pcb.h>
60 #include <netinet/ip_var.h>
61 #ifdef INET6
62 #include <netinet/ip6.h>
63 #include <netinet/icmp6.h>
64 #include <netinet6/nd6.h>
65 #include <netinet6/ip6_var.h>
66 #include <netinet6/in6_pcb.h>
67 #endif
68 #include <netinet/tcp.h>
69 #include <netinet/tcp_fsm.h>
70 #include <netinet/tcp_seq.h>
71 #include <netinet/tcp_timer.h>
72 #include <netinet/tcp_var.h>
73 #ifdef INET6
74 #include <netinet6/tcp6_var.h>
75 #endif
76 
77 #ifdef IPSEC
78 #include <netinet6/ipsec.h>
79 #ifdef INET6
80 #include <netinet6/ipsec6.h>
81 #endif
82 #include <netkey/key.h>
83 #endif /*IPSEC*/
84 
85 #include <machine/in_cksum.h>
86 #include <vm/uma.h>
87 
88 static int tcp_syncookies = 1;
89 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
90     &tcp_syncookies, 0,
91     "Use TCP SYN cookies if the syncache overflows");
92 
93 static void	 syncache_drop(struct syncache *, struct syncache_head *);
94 static void	 syncache_free(struct syncache *);
95 static void	 syncache_insert(struct syncache *, struct syncache_head *);
96 struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
97 static int	 syncache_respond(struct syncache *, struct mbuf *);
98 static struct 	 socket *syncache_socket(struct syncache *, struct socket *);
99 static void	 syncache_timer(void *);
100 static u_int32_t syncookie_generate(struct syncache *);
101 static struct syncache *syncookie_lookup(struct in_conninfo *,
102 		    struct tcphdr *, struct socket *);
103 
104 /*
105  * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
106  * 3 retransmits corresponds to a timeout of (1 + 2 + 4 + 8 == 15) seconds,
107  * the odds are that the user has given up attempting to connect by then.
108  */
109 #define SYNCACHE_MAXREXMTS		3
110 
111 /* Arbitrary values */
112 #define TCP_SYNCACHE_HASHSIZE		512
113 #define TCP_SYNCACHE_BUCKETLIMIT	30
114 
115 struct tcp_syncache {
116 	struct	syncache_head *hashbase;
117 	uma_zone_t zone;
118 	u_int	hashsize;
119 	u_int	hashmask;
120 	u_int	bucket_limit;
121 	u_int	cache_count;
122 	u_int	cache_limit;
123 	u_int	rexmt_limit;
124 	u_int	hash_secret;
125 	u_int	next_reseed;
126 	TAILQ_HEAD(, syncache) timerq[SYNCACHE_MAXREXMTS + 1];
127 	struct	callout tt_timerq[SYNCACHE_MAXREXMTS + 1];
128 };
129 static struct tcp_syncache tcp_syncache;
130 
131 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
132 
133 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RD,
134      &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
135 
136 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RD,
137      &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
138 
139 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
140      &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
141 
142 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RD,
143      &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
144 
145 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
146      &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
147 
148 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
149 
150 #define SYNCACHE_HASH(inc, mask) 					\
151 	((tcp_syncache.hash_secret ^					\
152 	  (inc)->inc_faddr.s_addr ^					\
153 	  ((inc)->inc_faddr.s_addr >> 16) ^ 				\
154 	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
155 
156 #define SYNCACHE_HASH6(inc, mask) 					\
157 	((tcp_syncache.hash_secret ^					\
158 	  (inc)->inc6_faddr.s6_addr32[0] ^ 				\
159 	  (inc)->inc6_faddr.s6_addr32[3] ^ 				\
160 	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
161 
162 #define ENDPTS_EQ(a, b) (						\
163 	(a)->ie_fport == (b)->ie_fport &&				\
164 	(a)->ie_lport == (b)->ie_lport &&				\
165 	(a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&			\
166 	(a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr			\
167 )
168 
169 #define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
170 
171 #define SYNCACHE_TIMEOUT(sc, slot) do {					\
172 	sc->sc_rxtslot = slot;						\
173 	sc->sc_rxttime = ticks + TCPTV_RTOBASE * tcp_backoff[slot];	\
174 	TAILQ_INSERT_TAIL(&tcp_syncache.timerq[slot], sc, sc_timerq);	\
175 	if (!callout_active(&tcp_syncache.tt_timerq[slot]))		\
176 		callout_reset(&tcp_syncache.tt_timerq[slot],		\
177 		    TCPTV_RTOBASE * tcp_backoff[slot],			\
178 		    syncache_timer, (void *)((intptr_t)slot));		\
179 } while (0)
180 
181 static void
182 syncache_free(struct syncache *sc)
183 {
184 	struct rtentry *rt;
185 
186 	if (sc->sc_ipopts)
187 		(void) m_free(sc->sc_ipopts);
188 #ifdef INET6
189 	if (sc->sc_inc.inc_isipv6)
190 		rt = sc->sc_route6.ro_rt;
191 	else
192 #endif
193 		rt = sc->sc_route.ro_rt;
194 	if (rt != NULL) {
195 		/*
196 		 * If this is the only reference to a protocol cloned
197 		 * route, remove it immediately.
198 		 */
199 		if (rt->rt_flags & RTF_WASCLONED &&
200 		    (sc->sc_flags & SCF_KEEPROUTE) == 0 &&
201 		    rt->rt_refcnt == 1)
202 			rtrequest(RTM_DELETE, rt_key(rt),
203 			    rt->rt_gateway, rt_mask(rt),
204 			    rt->rt_flags, NULL);
205 		RTFREE(rt);
206 	}
207 	uma_zfree(tcp_syncache.zone, sc);
208 }
209 
210 void
211 syncache_init(void)
212 {
213 	int i;
214 
215 	tcp_syncache.cache_count = 0;
216 	tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
217 	tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
218 	tcp_syncache.cache_limit =
219 	    tcp_syncache.hashsize * tcp_syncache.bucket_limit;
220 	tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
221 	tcp_syncache.next_reseed = 0;
222 	tcp_syncache.hash_secret = arc4random();
223 
224         TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
225 	    &tcp_syncache.hashsize);
226         TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
227 	    &tcp_syncache.cache_limit);
228         TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
229 	    &tcp_syncache.bucket_limit);
230 	if (!powerof2(tcp_syncache.hashsize)) {
231                 printf("WARNING: syncache hash size is not a power of 2.\n");
232 		tcp_syncache.hashsize = 512;	/* safe default */
233         }
234 	tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
235 
236 	/* Allocate the hash table. */
237 	MALLOC(tcp_syncache.hashbase, struct syncache_head *,
238 	    tcp_syncache.hashsize * sizeof(struct syncache_head),
239 	    M_SYNCACHE, M_WAITOK | M_ZERO);
240 
241 	/* Initialize the hash buckets. */
242 	for (i = 0; i < tcp_syncache.hashsize; i++) {
243 		TAILQ_INIT(&tcp_syncache.hashbase[i].sch_bucket);
244 		tcp_syncache.hashbase[i].sch_length = 0;
245 	}
246 
247 	/* Initialize the timer queues. */
248 	for (i = 0; i <= SYNCACHE_MAXREXMTS; i++) {
249 		TAILQ_INIT(&tcp_syncache.timerq[i]);
250 		callout_init(&tcp_syncache.tt_timerq[i], 0);
251 	}
252 
253 	/*
254 	 * Allocate the syncache entries.  Allow the zone to allocate one
255 	 * more entry than cache limit, so a new entry can bump out an
256 	 * older one.
257 	 */
258 	tcp_syncache.cache_limit -= 1;
259 	tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
260 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
261 	uma_zone_set_max(tcp_syncache.zone, tcp_syncache.cache_limit);
262 }
263 
264 static void
265 syncache_insert(sc, sch)
266 	struct syncache *sc;
267 	struct syncache_head *sch;
268 {
269 	struct syncache *sc2;
270 	int s, i;
271 
272 	/*
273 	 * Make sure that we don't overflow the per-bucket
274 	 * limit or the total cache size limit.
275 	 */
276 	s = splnet();
277 	if (sch->sch_length >= tcp_syncache.bucket_limit) {
278 		/*
279 		 * The bucket is full, toss the oldest element.
280 		 */
281 		sc2 = TAILQ_FIRST(&sch->sch_bucket);
282 		sc2->sc_tp->ts_recent = ticks;
283 		syncache_drop(sc2, sch);
284 		tcpstat.tcps_sc_bucketoverflow++;
285 	} else if (tcp_syncache.cache_count >= tcp_syncache.cache_limit) {
286 		/*
287 		 * The cache is full.  Toss the oldest entry in the
288 		 * entire cache.  This is the front entry in the
289 		 * first non-empty timer queue with the largest
290 		 * timeout value.
291 		 */
292 		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
293 			sc2 = TAILQ_FIRST(&tcp_syncache.timerq[i]);
294 			if (sc2 != NULL)
295 				break;
296 		}
297 		sc2->sc_tp->ts_recent = ticks;
298 		syncache_drop(sc2, NULL);
299 		tcpstat.tcps_sc_cacheoverflow++;
300 	}
301 
302 	/* Initialize the entry's timer. */
303 	SYNCACHE_TIMEOUT(sc, 0);
304 
305 	/* Put it into the bucket. */
306 	TAILQ_INSERT_TAIL(&sch->sch_bucket, sc, sc_hash);
307 	sch->sch_length++;
308 	tcp_syncache.cache_count++;
309 	tcpstat.tcps_sc_added++;
310 	splx(s);
311 }
312 
313 static void
314 syncache_drop(sc, sch)
315 	struct syncache *sc;
316 	struct syncache_head *sch;
317 {
318 	int s;
319 
320 	if (sch == NULL) {
321 #ifdef INET6
322 		if (sc->sc_inc.inc_isipv6) {
323 			sch = &tcp_syncache.hashbase[
324 			    SYNCACHE_HASH6(&sc->sc_inc, tcp_syncache.hashmask)];
325 		} else
326 #endif
327 		{
328 			sch = &tcp_syncache.hashbase[
329 			    SYNCACHE_HASH(&sc->sc_inc, tcp_syncache.hashmask)];
330 		}
331 	}
332 
333 	s = splnet();
334 
335 	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
336 	sch->sch_length--;
337 	tcp_syncache.cache_count--;
338 
339 	TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot], sc, sc_timerq);
340 	if (TAILQ_EMPTY(&tcp_syncache.timerq[sc->sc_rxtslot]))
341 		callout_stop(&tcp_syncache.tt_timerq[sc->sc_rxtslot]);
342 	splx(s);
343 
344 	syncache_free(sc);
345 }
346 
347 /*
348  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
349  * If we have retransmitted an entry the maximum number of times, expire it.
350  */
351 static void
352 syncache_timer(xslot)
353 	void *xslot;
354 {
355 	intptr_t slot = (intptr_t)xslot;
356 	struct syncache *sc, *nsc;
357 	struct inpcb *inp;
358 	int s;
359 
360 	s = splnet();
361         if (callout_pending(&tcp_syncache.tt_timerq[slot]) ||
362             !callout_active(&tcp_syncache.tt_timerq[slot])) {
363                 splx(s);
364                 return;
365         }
366         callout_deactivate(&tcp_syncache.tt_timerq[slot]);
367 
368         nsc = TAILQ_FIRST(&tcp_syncache.timerq[slot]);
369 	while (nsc != NULL) {
370 		if (ticks < nsc->sc_rxttime)
371 			break;
372 		sc = nsc;
373 		nsc = TAILQ_NEXT(sc, sc_timerq);
374 		inp = sc->sc_tp->t_inpcb;
375 		if (slot == SYNCACHE_MAXREXMTS ||
376 		    slot >= tcp_syncache.rexmt_limit ||
377 		    inp->inp_gencnt != sc->sc_inp_gencnt) {
378 			syncache_drop(sc, NULL);
379 			tcpstat.tcps_sc_stale++;
380 			continue;
381 		}
382 		(void) syncache_respond(sc, NULL);
383 		tcpstat.tcps_sc_retransmitted++;
384 		TAILQ_REMOVE(&tcp_syncache.timerq[slot], sc, sc_timerq);
385 		SYNCACHE_TIMEOUT(sc, slot + 1);
386 	}
387 	if (nsc != NULL)
388 		callout_reset(&tcp_syncache.tt_timerq[slot],
389 		    nsc->sc_rxttime - ticks, syncache_timer, (void *)(slot));
390 	splx(s);
391 }
392 
393 /*
394  * Find an entry in the syncache.
395  */
396 struct syncache *
397 syncache_lookup(inc, schp)
398 	struct in_conninfo *inc;
399 	struct syncache_head **schp;
400 {
401 	struct syncache *sc;
402 	struct syncache_head *sch;
403 	int s;
404 
405 #ifdef INET6
406 	if (inc->inc_isipv6) {
407 		sch = &tcp_syncache.hashbase[
408 		    SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
409 		*schp = sch;
410 		s = splnet();
411 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
412 			if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie)) {
413 				splx(s);
414 				return (sc);
415 			}
416 		}
417 		splx(s);
418 	} else
419 #endif
420 	{
421 		sch = &tcp_syncache.hashbase[
422 		    SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
423 		*schp = sch;
424 		s = splnet();
425 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
426 #ifdef INET6
427 			if (sc->sc_inc.inc_isipv6)
428 				continue;
429 #endif
430 			if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie)) {
431 				splx(s);
432 				return (sc);
433 			}
434 		}
435 		splx(s);
436 	}
437 	return (NULL);
438 }
439 
440 /*
441  * This function is called when we get a RST for a
442  * non-existent connection, so that we can see if the
443  * connection is in the syn cache.  If it is, zap it.
444  */
445 void
446 syncache_chkrst(inc, th)
447 	struct in_conninfo *inc;
448 	struct tcphdr *th;
449 {
450 	struct syncache *sc;
451 	struct syncache_head *sch;
452 
453 	sc = syncache_lookup(inc, &sch);
454 	if (sc == NULL)
455 		return;
456 	/*
457 	 * If the RST bit is set, check the sequence number to see
458 	 * if this is a valid reset segment.
459 	 * RFC 793 page 37:
460 	 *   In all states except SYN-SENT, all reset (RST) segments
461 	 *   are validated by checking their SEQ-fields.  A reset is
462 	 *   valid if its sequence number is in the window.
463 	 *
464 	 *   The sequence number in the reset segment is normally an
465 	 *   echo of our outgoing acknowlegement numbers, but some hosts
466 	 *   send a reset with the sequence number at the rightmost edge
467 	 *   of our receive window, and we have to handle this case.
468 	 */
469 	if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
470 	    SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
471 		syncache_drop(sc, sch);
472 		tcpstat.tcps_sc_reset++;
473 	}
474 }
475 
476 void
477 syncache_badack(inc)
478 	struct in_conninfo *inc;
479 {
480 	struct syncache *sc;
481 	struct syncache_head *sch;
482 
483 	sc = syncache_lookup(inc, &sch);
484 	if (sc != NULL) {
485 		syncache_drop(sc, sch);
486 		tcpstat.tcps_sc_badack++;
487 	}
488 }
489 
490 void
491 syncache_unreach(inc, th)
492 	struct in_conninfo *inc;
493 	struct tcphdr *th;
494 {
495 	struct syncache *sc;
496 	struct syncache_head *sch;
497 
498 	/* we are called at splnet() here */
499 	sc = syncache_lookup(inc, &sch);
500 	if (sc == NULL)
501 		return;
502 
503 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
504 	if (ntohl(th->th_seq) != sc->sc_iss)
505 		return;
506 
507 	/*
508 	 * If we've rertransmitted 3 times and this is our second error,
509 	 * we remove the entry.  Otherwise, we allow it to continue on.
510 	 * This prevents us from incorrectly nuking an entry during a
511 	 * spurious network outage.
512 	 *
513 	 * See tcp_notify().
514 	 */
515 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtslot < 3) {
516 		sc->sc_flags |= SCF_UNREACH;
517 		return;
518 	}
519 	syncache_drop(sc, sch);
520 	tcpstat.tcps_sc_unreach++;
521 }
522 
523 /*
524  * Build a new TCP socket structure from a syncache entry.
525  */
526 static struct socket *
527 syncache_socket(sc, lso)
528 	struct syncache *sc;
529 	struct socket *lso;
530 {
531 	struct inpcb *inp = NULL;
532 	struct socket *so;
533 	struct tcpcb *tp;
534 
535 	/*
536 	 * Ok, create the full blown connection, and set things up
537 	 * as they would have been set up if we had created the
538 	 * connection when the SYN arrived.  If we can't create
539 	 * the connection, abort it.
540 	 */
541 	so = sonewconn(lso, SS_ISCONNECTED);
542 	if (so == NULL) {
543 		/*
544 		 * Drop the connection; we will send a RST if the peer
545 		 * retransmits the ACK,
546 		 */
547 		tcpstat.tcps_listendrop++;
548 		goto abort;
549 	}
550 
551 	inp = sotoinpcb(so);
552 
553 	/*
554 	 * Insert new socket into hash list.
555 	 */
556 	inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
557 #ifdef INET6
558 	if (sc->sc_inc.inc_isipv6) {
559 		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
560 	} else {
561 		inp->inp_vflag &= ~INP_IPV6;
562 		inp->inp_vflag |= INP_IPV4;
563 #endif
564 		inp->inp_laddr = sc->sc_inc.inc_laddr;
565 #ifdef INET6
566 	}
567 #endif
568 	inp->inp_lport = sc->sc_inc.inc_lport;
569 	if (in_pcbinshash(inp) != 0) {
570 		/*
571 		 * Undo the assignments above if we failed to
572 		 * put the PCB on the hash lists.
573 		 */
574 #ifdef INET6
575 		if (sc->sc_inc.inc_isipv6)
576 			inp->in6p_laddr = in6addr_any;
577        		else
578 #endif
579 			inp->inp_laddr.s_addr = INADDR_ANY;
580 		inp->inp_lport = 0;
581 		goto abort;
582 	}
583 #ifdef IPSEC
584 	/* copy old policy into new socket's */
585 	if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
586 		printf("syncache_expand: could not copy policy\n");
587 #endif
588 #ifdef INET6
589 	if (sc->sc_inc.inc_isipv6) {
590 		struct inpcb *oinp = sotoinpcb(lso);
591 		struct in6_addr laddr6;
592 		struct sockaddr_in6 *sin6;
593 		/*
594 		 * Inherit socket options from the listening socket.
595 		 * Note that in6p_inputopts are not (and should not be)
596 		 * copied, since it stores previously received options and is
597 		 * used to detect if each new option is different than the
598 		 * previous one and hence should be passed to a user.
599                  * If we copied in6p_inputopts, a user would not be able to
600 		 * receive options just after calling the accept system call.
601 		 */
602 		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
603 		if (oinp->in6p_outputopts)
604 			inp->in6p_outputopts =
605 			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
606 		inp->in6p_route = sc->sc_route6;
607 		sc->sc_route6.ro_rt = NULL;
608 
609 		MALLOC(sin6, struct sockaddr_in6 *, sizeof *sin6,
610 		    M_SONAME, M_NOWAIT | M_ZERO);
611 		if (sin6 == NULL)
612 			goto abort;
613 		sin6->sin6_family = AF_INET6;
614 		sin6->sin6_len = sizeof(*sin6);
615 		sin6->sin6_addr = sc->sc_inc.inc6_faddr;
616 		sin6->sin6_port = sc->sc_inc.inc_fport;
617 		laddr6 = inp->in6p_laddr;
618 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
619 			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
620 		if (in6_pcbconnect(inp, (struct sockaddr *)sin6, &thread0)) {
621 			inp->in6p_laddr = laddr6;
622 			FREE(sin6, M_SONAME);
623 			goto abort;
624 		}
625 		FREE(sin6, M_SONAME);
626 	} else
627 #endif
628 	{
629 		struct in_addr laddr;
630 		struct sockaddr_in *sin;
631 
632 		inp->inp_options = ip_srcroute();
633 		if (inp->inp_options == NULL) {
634 			inp->inp_options = sc->sc_ipopts;
635 			sc->sc_ipopts = NULL;
636 		}
637 		inp->inp_route = sc->sc_route;
638 		sc->sc_route.ro_rt = NULL;
639 
640 		MALLOC(sin, struct sockaddr_in *, sizeof *sin,
641 		    M_SONAME, M_NOWAIT | M_ZERO);
642 		if (sin == NULL)
643 			goto abort;
644 		sin->sin_family = AF_INET;
645 		sin->sin_len = sizeof(*sin);
646 		sin->sin_addr = sc->sc_inc.inc_faddr;
647 		sin->sin_port = sc->sc_inc.inc_fport;
648 		bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
649 		laddr = inp->inp_laddr;
650 		if (inp->inp_laddr.s_addr == INADDR_ANY)
651 			inp->inp_laddr = sc->sc_inc.inc_laddr;
652 		if (in_pcbconnect(inp, (struct sockaddr *)sin, &thread0)) {
653 			inp->inp_laddr = laddr;
654 			FREE(sin, M_SONAME);
655 			goto abort;
656 		}
657 		FREE(sin, M_SONAME);
658 	}
659 
660 	tp = intotcpcb(inp);
661 	tp->t_state = TCPS_SYN_RECEIVED;
662 	tp->iss = sc->sc_iss;
663 	tp->irs = sc->sc_irs;
664 	tcp_rcvseqinit(tp);
665 	tcp_sendseqinit(tp);
666 	tp->snd_wl1 = sc->sc_irs;
667 	tp->rcv_up = sc->sc_irs + 1;
668 	tp->rcv_wnd = sc->sc_wnd;
669 	tp->rcv_adv += tp->rcv_wnd;
670 
671 	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
672 	if (sc->sc_flags & SCF_NOOPT)
673 		tp->t_flags |= TF_NOOPT;
674 	if (sc->sc_flags & SCF_WINSCALE) {
675 		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
676 		tp->requested_s_scale = sc->sc_requested_s_scale;
677 		tp->request_r_scale = sc->sc_request_r_scale;
678 	}
679 	if (sc->sc_flags & SCF_TIMESTAMP) {
680 		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
681 		tp->ts_recent = sc->sc_tsrecent;
682 		tp->ts_recent_age = ticks;
683 	}
684 	if (sc->sc_flags & SCF_CC) {
685 		/*
686 		 * Initialization of the tcpcb for transaction;
687 		 *   set SND.WND = SEG.WND,
688 		 *   initialize CCsend and CCrecv.
689 		 */
690 		tp->t_flags |= TF_REQ_CC|TF_RCVD_CC;
691 		tp->cc_send = sc->sc_cc_send;
692 		tp->cc_recv = sc->sc_cc_recv;
693 	}
694 
695 	tcp_mss(tp, sc->sc_peer_mss);
696 
697 	/*
698 	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
699 	 */
700 	if (sc->sc_rxtslot != 0)
701                 tp->snd_cwnd = tp->t_maxseg;
702 	callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
703 
704 	tcpstat.tcps_accepts++;
705 	return (so);
706 
707 abort:
708 	if (so != NULL)
709 		(void) soabort(so);
710 	return (NULL);
711 }
712 
713 /*
714  * This function gets called when we receive an ACK for a
715  * socket in the LISTEN state.  We look up the connection
716  * in the syncache, and if its there, we pull it out of
717  * the cache and turn it into a full-blown connection in
718  * the SYN-RECEIVED state.
719  */
720 int
721 syncache_expand(inc, th, sop, m)
722 	struct in_conninfo *inc;
723 	struct tcphdr *th;
724 	struct socket **sop;
725 	struct mbuf *m;
726 {
727 	struct syncache *sc;
728 	struct syncache_head *sch;
729 	struct socket *so;
730 
731 	sc = syncache_lookup(inc, &sch);
732 	if (sc == NULL) {
733 		/*
734 		 * There is no syncache entry, so see if this ACK is
735 		 * a returning syncookie.  To do this, first:
736 		 *  A. See if this socket has had a syncache entry dropped in
737 		 *     the past.  We don't want to accept a bogus syncookie
738  		 *     if we've never received a SYN.
739 		 *  B. check that the syncookie is valid.  If it is, then
740 		 *     cobble up a fake syncache entry, and return.
741 		 */
742 		if (!tcp_syncookies)
743 			return (0);
744 		sc = syncookie_lookup(inc, th, *sop);
745 		if (sc == NULL)
746 			return (0);
747 		sch = NULL;
748 		tcpstat.tcps_sc_recvcookie++;
749 	}
750 
751 	/*
752 	 * If seg contains an ACK, but not for our SYN/ACK, send a RST.
753 	 */
754 	if (th->th_ack != sc->sc_iss + 1)
755 		return (0);
756 
757 	so = syncache_socket(sc, *sop);
758 	if (so == NULL) {
759 #if 0
760 resetandabort:
761 		/* XXXjlemon check this - is this correct? */
762 		(void) tcp_respond(NULL, m, m, th,
763 		    th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
764 #endif
765 		m_freem(m);			/* XXX only needed for above */
766 		tcpstat.tcps_sc_aborted++;
767 	} else {
768 		sc->sc_flags |= SCF_KEEPROUTE;
769 		tcpstat.tcps_sc_completed++;
770 	}
771 	if (sch == NULL)
772 		syncache_free(sc);
773 	else
774 		syncache_drop(sc, sch);
775 	*sop = so;
776 	return (1);
777 }
778 
779 /*
780  * Given a LISTEN socket and an inbound SYN request, add
781  * this to the syn cache, and send back a segment:
782  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
783  * to the source.
784  *
785  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
786  * Doing so would require that we hold onto the data and deliver it
787  * to the application.  However, if we are the target of a SYN-flood
788  * DoS attack, an attacker could send data which would eventually
789  * consume all available buffer space if it were ACKed.  By not ACKing
790  * the data, we avoid this DoS scenario.
791  */
792 int
793 syncache_add(inc, to, th, sop, m)
794 	struct in_conninfo *inc;
795 	struct tcpopt *to;
796 	struct tcphdr *th;
797 	struct socket **sop;
798 	struct mbuf *m;
799 {
800 	struct tcpcb *tp;
801 	struct socket *so;
802 	struct syncache *sc = NULL;
803 	struct syncache_head *sch;
804 	struct mbuf *ipopts = NULL;
805 	struct rmxp_tao *taop;
806 	int i, s, win;
807 
808 	so = *sop;
809 	tp = sototcpcb(so);
810 
811 	/*
812 	 * Remember the IP options, if any.
813 	 */
814 #ifdef INET6
815 	if (!inc->inc_isipv6)
816 #endif
817 		ipopts = ip_srcroute();
818 
819 	/*
820 	 * See if we already have an entry for this connection.
821 	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
822 	 *
823 	 * XXX
824 	 * should the syncache be re-initialized with the contents
825 	 * of the new SYN here (which may have different options?)
826 	 */
827 	sc = syncache_lookup(inc, &sch);
828 	if (sc != NULL) {
829 		tcpstat.tcps_sc_dupsyn++;
830 		if (ipopts) {
831 			/*
832 			 * If we were remembering a previous source route,
833 			 * forget it and use the new one we've been given.
834 			 */
835 			if (sc->sc_ipopts)
836 				(void) m_free(sc->sc_ipopts);
837 			sc->sc_ipopts = ipopts;
838 		}
839 		/*
840 		 * Update timestamp if present.
841 		 */
842 		if (sc->sc_flags & SCF_TIMESTAMP)
843 			sc->sc_tsrecent = to->to_tsval;
844 		/*
845 		 * PCB may have changed, pick up new values.
846 		 */
847 		sc->sc_tp = tp;
848 		sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
849 		if (syncache_respond(sc, m) == 0) {
850 		        s = splnet();
851 			TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot],
852 			    sc, sc_timerq);
853 			SYNCACHE_TIMEOUT(sc, sc->sc_rxtslot);
854 		        splx(s);
855 		 	tcpstat.tcps_sndacks++;
856 			tcpstat.tcps_sndtotal++;
857 		}
858 		*sop = NULL;
859 		return (1);
860 	}
861 
862 	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
863 	if (sc == NULL) {
864 		/*
865 		 * The zone allocator couldn't provide more entries.
866 		 * Treat this as if the cache was full; drop the oldest
867 		 * entry and insert the new one.
868 		 */
869 		s = splnet();
870 		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
871 			sc = TAILQ_FIRST(&tcp_syncache.timerq[i]);
872 			if (sc != NULL)
873 				break;
874 		}
875 		sc->sc_tp->ts_recent = ticks;
876 		syncache_drop(sc, NULL);
877 		splx(s);
878 		tcpstat.tcps_sc_zonefail++;
879 		sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
880 		if (sc == NULL) {
881 			if (ipopts)
882 				(void) m_free(ipopts);
883 			return (0);
884 		}
885 	}
886 
887 	/*
888 	 * Fill in the syncache values.
889 	 */
890 	bzero(sc, sizeof(*sc));
891 	sc->sc_tp = tp;
892 	sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
893 	sc->sc_ipopts = ipopts;
894 	sc->sc_inc.inc_fport = inc->inc_fport;
895 	sc->sc_inc.inc_lport = inc->inc_lport;
896 #ifdef INET6
897 	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
898 	if (inc->inc_isipv6) {
899 		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
900 		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
901 		sc->sc_route6.ro_rt = NULL;
902 	} else
903 #endif
904 	{
905 		sc->sc_inc.inc_faddr = inc->inc_faddr;
906 		sc->sc_inc.inc_laddr = inc->inc_laddr;
907 		sc->sc_route.ro_rt = NULL;
908 	}
909 	sc->sc_irs = th->th_seq;
910 	if (tcp_syncookies)
911 		sc->sc_iss = syncookie_generate(sc);
912 	else
913 		sc->sc_iss = arc4random();
914 
915 	/* Initial receive window: clip sbspace to [0 .. TCP_MAXWIN] */
916 	win = sbspace(&so->so_rcv);
917 	win = imax(win, 0);
918 	win = imin(win, TCP_MAXWIN);
919 	sc->sc_wnd = win;
920 
921 	sc->sc_flags = 0;
922 	sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
923 	if (tcp_do_rfc1323) {
924 		/*
925 		 * A timestamp received in a SYN makes
926 		 * it ok to send timestamp requests and replies.
927 		 */
928 		if (to->to_flags & TOF_TS) {
929 			sc->sc_tsrecent = to->to_tsval;
930 			sc->sc_flags |= SCF_TIMESTAMP;
931 		}
932 		if (to->to_flags & TOF_SCALE) {
933 			int wscale = 0;
934 
935 			/* Compute proper scaling value from buffer space */
936 			while (wscale < TCP_MAX_WINSHIFT &&
937 			    (TCP_MAXWIN << wscale) < so->so_rcv.sb_hiwat)
938 				wscale++;
939 			sc->sc_request_r_scale = wscale;
940 			sc->sc_requested_s_scale = to->to_requested_s_scale;
941 			sc->sc_flags |= SCF_WINSCALE;
942 		}
943 	}
944 	if (tcp_do_rfc1644) {
945 		/*
946 		 * A CC or CC.new option received in a SYN makes
947 		 * it ok to send CC in subsequent segments.
948 		 */
949 		if (to->to_flags & (TOF_CC|TOF_CCNEW)) {
950 			sc->sc_cc_recv = to->to_cc;
951 			sc->sc_cc_send = CC_INC(tcp_ccgen);
952 			sc->sc_flags |= SCF_CC;
953 		}
954 	}
955 	if (tp->t_flags & TF_NOOPT)
956 		sc->sc_flags = SCF_NOOPT;
957 
958 	/*
959 	 * XXX
960 	 * We have the option here of not doing TAO (even if the segment
961 	 * qualifies) and instead fall back to a normal 3WHS via the syncache.
962 	 * This allows us to apply synflood protection to TAO-qualifying SYNs
963 	 * also. However, there should be a hueristic to determine when to
964 	 * do this, and is not present at the moment.
965 	 */
966 
967 	/*
968 	 * Perform TAO test on incoming CC (SEG.CC) option, if any.
969 	 * - compare SEG.CC against cached CC from the same host, if any.
970 	 * - if SEG.CC > chached value, SYN must be new and is accepted
971 	 *	immediately: save new CC in the cache, mark the socket
972 	 *	connected, enter ESTABLISHED state, turn on flag to
973 	 *	send a SYN in the next segment.
974 	 *	A virtual advertised window is set in rcv_adv to
975 	 *	initialize SWS prevention.  Then enter normal segment
976 	 *	processing: drop SYN, process data and FIN.
977 	 * - otherwise do a normal 3-way handshake.
978 	 */
979 	taop = tcp_gettaocache(&sc->sc_inc);
980 	if ((to->to_flags & TOF_CC) != 0) {
981 		if (((tp->t_flags & TF_NOPUSH) != 0) &&
982 		    sc->sc_flags & SCF_CC &&
983 		    taop != NULL && taop->tao_cc != 0 &&
984 		    CC_GT(to->to_cc, taop->tao_cc)) {
985 			sc->sc_rxtslot = 0;
986 			so = syncache_socket(sc, *sop);
987 			if (so != NULL) {
988 				sc->sc_flags |= SCF_KEEPROUTE;
989 				taop->tao_cc = to->to_cc;
990 				*sop = so;
991 			}
992 			syncache_free(sc);
993 			return (so != NULL);
994 		}
995 	} else {
996 		/*
997 		 * No CC option, but maybe CC.NEW: invalidate cached value.
998 		 */
999 		if (taop != NULL)
1000 			taop->tao_cc = 0;
1001 	}
1002 	/*
1003 	 * TAO test failed or there was no CC option,
1004 	 *    do a standard 3-way handshake.
1005 	 */
1006 	if (syncache_respond(sc, m) == 0) {
1007 		syncache_insert(sc, sch);
1008 		tcpstat.tcps_sndacks++;
1009 		tcpstat.tcps_sndtotal++;
1010 	} else {
1011 		syncache_free(sc);
1012 		tcpstat.tcps_sc_dropped++;
1013 	}
1014 	*sop = NULL;
1015 	return (1);
1016 }
1017 
1018 static int
1019 syncache_respond(sc, m)
1020 	struct syncache *sc;
1021 	struct mbuf *m;
1022 {
1023 	u_int8_t *optp;
1024 	int optlen, error;
1025 	u_int16_t tlen, hlen, mssopt;
1026 	struct ip *ip = NULL;
1027 	struct rtentry *rt;
1028 	struct tcphdr *th;
1029 #ifdef INET6
1030 	struct ip6_hdr *ip6 = NULL;
1031 #endif
1032 
1033 #ifdef INET6
1034 	if (sc->sc_inc.inc_isipv6) {
1035 		rt = tcp_rtlookup6(&sc->sc_inc);
1036 		if (rt != NULL)
1037 			mssopt = rt->rt_ifp->if_mtu -
1038 			     (sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1039 		else
1040 			mssopt = tcp_v6mssdflt;
1041 		hlen = sizeof(struct ip6_hdr);
1042 	} else
1043 #endif
1044 	{
1045 		rt = tcp_rtlookup(&sc->sc_inc);
1046 		if (rt != NULL)
1047 			mssopt = rt->rt_ifp->if_mtu -
1048 			     (sizeof(struct ip) + sizeof(struct tcphdr));
1049 		else
1050 			mssopt = tcp_mssdflt;
1051 		hlen = sizeof(struct ip);
1052 	}
1053 
1054 	/* Compute the size of the TCP options. */
1055 	if (sc->sc_flags & SCF_NOOPT) {
1056 		optlen = 0;
1057 	} else {
1058 		optlen = TCPOLEN_MAXSEG +
1059 		    ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
1060 		    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0) +
1061 		    ((sc->sc_flags & SCF_CC) ? TCPOLEN_CC_APPA * 2 : 0);
1062 	}
1063 	tlen = hlen + sizeof(struct tcphdr) + optlen;
1064 
1065 	/*
1066 	 * XXX
1067 	 * assume that the entire packet will fit in a header mbuf
1068 	 */
1069 	KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
1070 
1071 	/*
1072 	 * XXX shouldn't this reuse the mbuf if possible ?
1073 	 * Create the IP+TCP header from scratch.
1074 	 */
1075 	if (m)
1076 		m_freem(m);
1077 
1078 	m = m_gethdr(M_DONTWAIT, MT_HEADER);
1079 	if (m == NULL)
1080 		return (ENOBUFS);
1081 	m->m_data += max_linkhdr;
1082 	m->m_len = tlen;
1083 	m->m_pkthdr.len = tlen;
1084 	m->m_pkthdr.rcvif = NULL;
1085 
1086 #ifdef IPSEC
1087 	/* use IPsec policy on listening socket to send SYN,ACK */
1088 	if (ipsec_setsocket(m, sc->sc_tp->t_inpcb->inp_socket) != 0) {
1089 		m_freem(m);
1090 		return (ENOBUFS);
1091 	}
1092 #endif
1093 
1094 #ifdef INET6
1095 	if (sc->sc_inc.inc_isipv6) {
1096 		ip6 = mtod(m, struct ip6_hdr *);
1097 		ip6->ip6_vfc = IPV6_VERSION;
1098 		ip6->ip6_nxt = IPPROTO_TCP;
1099 		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1100 		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1101 		ip6->ip6_plen = htons(tlen - hlen);
1102 		/* ip6_hlim is set after checksum */
1103 		/* ip6_flow = ??? */
1104 
1105 		th = (struct tcphdr *)(ip6 + 1);
1106 	} else
1107 #endif
1108 	{
1109 		ip = mtod(m, struct ip *);
1110 		ip->ip_v = IPVERSION;
1111 		ip->ip_hl = sizeof(struct ip) >> 2;
1112 		ip->ip_tos = 0;
1113 		ip->ip_len = tlen;
1114 		ip->ip_id = 0;
1115 		ip->ip_off = 0;
1116 		ip->ip_ttl = ip_defttl;
1117 		ip->ip_sum = 0;
1118 		ip->ip_p = IPPROTO_TCP;
1119 		ip->ip_src = sc->sc_inc.inc_laddr;
1120 		ip->ip_dst = sc->sc_inc.inc_faddr;
1121 
1122 		th = (struct tcphdr *)(ip + 1);
1123 	}
1124 	th->th_sport = sc->sc_inc.inc_lport;
1125 	th->th_dport = sc->sc_inc.inc_fport;
1126 
1127 	th->th_seq = htonl(sc->sc_iss);
1128 	th->th_ack = htonl(sc->sc_irs + 1);
1129 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1130 	th->th_x2 = 0;
1131 	th->th_flags = TH_SYN|TH_ACK;
1132 	th->th_win = htons(sc->sc_wnd);
1133 	th->th_urp = 0;
1134 
1135 	/* Tack on the TCP options. */
1136 	if (optlen == 0)
1137 		goto no_options;
1138 	optp = (u_int8_t *)(th + 1);
1139 	*optp++ = TCPOPT_MAXSEG;
1140 	*optp++ = TCPOLEN_MAXSEG;
1141 	*optp++ = (mssopt >> 8) & 0xff;
1142 	*optp++ = mssopt & 0xff;
1143 
1144 	if (sc->sc_flags & SCF_WINSCALE) {
1145 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1146 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1147 		    sc->sc_request_r_scale);
1148 		optp += 4;
1149 	}
1150 
1151 	if (sc->sc_flags & SCF_TIMESTAMP) {
1152 		u_int32_t *lp = (u_int32_t *)(optp);
1153 
1154 		/* Form timestamp option as shown in appendix A of RFC 1323. */
1155 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1156 		*lp++ = htonl(ticks);
1157 		*lp   = htonl(sc->sc_tsrecent);
1158 		optp += TCPOLEN_TSTAMP_APPA;
1159 	}
1160 
1161 	/*
1162          * Send CC and CC.echo if we received CC from our peer.
1163          */
1164         if (sc->sc_flags & SCF_CC) {
1165 		u_int32_t *lp = (u_int32_t *)(optp);
1166 
1167 		*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
1168 		*lp++ = htonl(sc->sc_cc_send);
1169 		*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CCECHO));
1170 		*lp   = htonl(sc->sc_cc_recv);
1171 		optp += TCPOLEN_CC_APPA * 2;
1172 	}
1173 no_options:
1174 
1175 #ifdef INET6
1176 	if (sc->sc_inc.inc_isipv6) {
1177 		struct route_in6 *ro6 = &sc->sc_route6;
1178 
1179 		th->th_sum = 0;
1180 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1181 		ip6->ip6_hlim = in6_selecthlim(NULL,
1182 		    ro6->ro_rt ? ro6->ro_rt->rt_ifp : NULL);
1183 		error = ip6_output(m, NULL, ro6, 0, NULL, NULL);
1184 	} else
1185 #endif
1186 	{
1187         	th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1188 		    htons(tlen - hlen + IPPROTO_TCP));
1189 		m->m_pkthdr.csum_flags = CSUM_TCP;
1190 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1191 		error = ip_output(m, sc->sc_ipopts, &sc->sc_route, 0, NULL);
1192 	}
1193 	return (error);
1194 }
1195 
1196 /*
1197  * cookie layers:
1198  *
1199  *	|. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
1200  *	| peer iss                                                      |
1201  *	| MD5(laddr,faddr,lport,fport,secret)             |. . . . . . .|
1202  *	|                     0                       |(A)|             |
1203  * (A): peer mss index
1204  */
1205 
1206 /*
1207  * The values below are chosen to minimize the size of the tcp_secret
1208  * table, as well as providing roughly a 4 second lifetime for the cookie.
1209  */
1210 
1211 #define SYNCOOKIE_HASHSHIFT	2	/* log2(# of 32bit words from hash) */
1212 #define SYNCOOKIE_WNDBITS	7	/* exposed bits for window indexing */
1213 #define SYNCOOKIE_TIMESHIFT	5	/* scale ticks to window time units */
1214 
1215 #define SYNCOOKIE_HASHMASK	((1 << SYNCOOKIE_HASHSHIFT) - 1)
1216 #define SYNCOOKIE_WNDMASK	((1 << SYNCOOKIE_WNDBITS) - 1)
1217 #define SYNCOOKIE_NSECRETS	(1 << (SYNCOOKIE_WNDBITS - SYNCOOKIE_HASHSHIFT))
1218 #define SYNCOOKIE_TIMEOUT \
1219     (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
1220 #define SYNCOOKIE_DATAMASK 	((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
1221 
1222 static struct {
1223 	u_int32_t	ts_secbits;
1224 	u_int		ts_expire;
1225 } tcp_secret[SYNCOOKIE_NSECRETS];
1226 
1227 static int tcp_msstab[] = { 0, 536, 1460, 8960 };
1228 
1229 static MD5_CTX syn_ctx;
1230 
1231 #define MD5Add(v)	MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
1232 
1233 /*
1234  * Consider the problem of a recreated (and retransmitted) cookie.  If the
1235  * original SYN was accepted, the connection is established.  The second
1236  * SYN is inflight, and if it arrives with an ISN that falls within the
1237  * receive window, the connection is killed.
1238  *
1239  * However, since cookies have other problems, this may not be worth
1240  * worrying about.
1241  */
1242 
1243 static u_int32_t
1244 syncookie_generate(struct syncache *sc)
1245 {
1246 	u_int32_t md5_buffer[4];
1247 	u_int32_t data;
1248 	int wnd, idx;
1249 
1250 	wnd = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
1251 	idx = wnd >> SYNCOOKIE_HASHSHIFT;
1252 	if (tcp_secret[idx].ts_expire < ticks) {
1253 		tcp_secret[idx].ts_secbits = arc4random();
1254 		tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
1255 	}
1256 	for (data = sizeof(tcp_msstab) / sizeof(int) - 1; data > 0; data--)
1257 		if (tcp_msstab[data] <= sc->sc_peer_mss)
1258 			break;
1259 	data = (data << SYNCOOKIE_WNDBITS) | wnd;
1260 	data ^= sc->sc_irs;				/* peer's iss */
1261 	MD5Init(&syn_ctx);
1262 #ifdef INET6
1263 	if (sc->sc_inc.inc_isipv6) {
1264 		MD5Add(sc->sc_inc.inc6_laddr);
1265 		MD5Add(sc->sc_inc.inc6_faddr);
1266 	} else
1267 #endif
1268 	{
1269 		MD5Add(sc->sc_inc.inc_laddr);
1270 		MD5Add(sc->sc_inc.inc_faddr);
1271 	}
1272 	MD5Add(sc->sc_inc.inc_lport);
1273 	MD5Add(sc->sc_inc.inc_fport);
1274 	MD5Add(tcp_secret[idx].ts_secbits);
1275 	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1276 	data ^= (md5_buffer[wnd & SYNCOOKIE_HASHMASK] & ~SYNCOOKIE_WNDMASK);
1277 	return (data);
1278 }
1279 
1280 static struct syncache *
1281 syncookie_lookup(inc, th, so)
1282 	struct in_conninfo *inc;
1283 	struct tcphdr *th;
1284 	struct socket *so;
1285 {
1286 	u_int32_t md5_buffer[4];
1287 	struct syncache *sc;
1288 	u_int32_t data;
1289 	int wnd, idx;
1290 
1291 	data = (th->th_ack - 1) ^ (th->th_seq - 1);	/* remove ISS */
1292 	wnd = data & SYNCOOKIE_WNDMASK;
1293 	idx = wnd >> SYNCOOKIE_HASHSHIFT;
1294 	if (tcp_secret[idx].ts_expire < ticks ||
1295 	    sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
1296 		return (NULL);
1297 	MD5Init(&syn_ctx);
1298 #ifdef INET6
1299 	if (inc->inc_isipv6) {
1300 		MD5Add(inc->inc6_laddr);
1301 		MD5Add(inc->inc6_faddr);
1302 	} else
1303 #endif
1304 	{
1305 		MD5Add(inc->inc_laddr);
1306 		MD5Add(inc->inc_faddr);
1307 	}
1308 	MD5Add(inc->inc_lport);
1309 	MD5Add(inc->inc_fport);
1310 	MD5Add(tcp_secret[idx].ts_secbits);
1311 	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1312 	data ^= md5_buffer[wnd & SYNCOOKIE_HASHMASK];
1313 	if ((data & ~SYNCOOKIE_DATAMASK) != 0)
1314 		return (NULL);
1315 	data = data >> SYNCOOKIE_WNDBITS;
1316 
1317 	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
1318 	if (sc == NULL)
1319 		return (NULL);
1320 	/*
1321 	 * Fill in the syncache values.
1322 	 * XXX duplicate code from syncache_add
1323 	 */
1324 	sc->sc_ipopts = NULL;
1325 	sc->sc_inc.inc_fport = inc->inc_fport;
1326 	sc->sc_inc.inc_lport = inc->inc_lport;
1327 #ifdef INET6
1328 	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1329 	if (inc->inc_isipv6) {
1330 		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1331 		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1332 		sc->sc_route6.ro_rt = NULL;
1333 	} else
1334 #endif
1335 	{
1336 		sc->sc_inc.inc_faddr = inc->inc_faddr;
1337 		sc->sc_inc.inc_laddr = inc->inc_laddr;
1338 		sc->sc_route.ro_rt = NULL;
1339 	}
1340 	sc->sc_irs = th->th_seq - 1;
1341 	sc->sc_iss = th->th_ack - 1;
1342 	wnd = sbspace(&so->so_rcv);
1343 	wnd = imax(wnd, 0);
1344 	wnd = imin(wnd, TCP_MAXWIN);
1345 	sc->sc_wnd = wnd;
1346 	sc->sc_flags = 0;
1347 	sc->sc_rxtslot = 0;
1348 	sc->sc_peer_mss = tcp_msstab[data];
1349 	return (sc);
1350 }
1351