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