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