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