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