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