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