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