xref: /freebsd/sys/netinet/tcp_syncache.c (revision 4f29da19bd44f0e99f021510460a81bf754c21d2)
1 /*-
2  * Copyright (c) 2001 McAfee, Inc.
3  * All rights reserved.
4  *
5  * This software was developed for the FreeBSD Project by Jonathan Lemon
6  * and McAfee Research, the Security Research Division of McAfee, Inc. under
7  * 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  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD$
32  */
33 
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_mac.h"
38 #include "opt_tcpdebug.h"
39 #include "opt_tcp_sack.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/sysctl.h>
45 #include <sys/malloc.h>
46 #include <sys/mac.h>
47 #include <sys/mbuf.h>
48 #include <sys/md5.h>
49 #include <sys/proc.h>		/* for proc0 declaration */
50 #include <sys/random.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 
54 #include <net/if.h>
55 #include <net/route.h>
56 
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/ip.h>
60 #include <netinet/in_var.h>
61 #include <netinet/in_pcb.h>
62 #include <netinet/ip_var.h>
63 #include <netinet/ip_options.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 *, u_int32_t *);
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) || tcp_syncache.hashsize == 0) {
230 		printf("WARNING: syncache hash size is not a power of 2.\n");
231 		tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
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], NET_CALLOUT_MPSAFE);
250 	}
251 
252 	/*
253 	 * Allocate the syncache entries.  Allow the zone to allocate one
254 	 * more entry than cache limit, so a new entry can bump out an
255 	 * older one.
256 	 */
257 	tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
258 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
259 	uma_zone_set_max(tcp_syncache.zone, tcp_syncache.cache_limit);
260 	tcp_syncache.cache_limit -= 1;
261 }
262 
263 static void
264 syncache_insert(sc, sch)
265 	struct syncache *sc;
266 	struct syncache_head *sch;
267 {
268 	struct syncache *sc2;
269 	int i;
270 
271 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
272 
273 	/*
274 	 * Make sure that we don't overflow the per-bucket
275 	 * limit or the total cache size limit.
276 	 */
277 	if (sch->sch_length >= tcp_syncache.bucket_limit) {
278 		/*
279 		 * The bucket is full, toss the oldest element.
280 		 */
281 		sc2 = TAILQ_FIRST(&sch->sch_bucket);
282 		sc2->sc_tp->ts_recent = ticks;
283 		syncache_drop(sc2, sch);
284 		tcpstat.tcps_sc_bucketoverflow++;
285 	} else if (tcp_syncache.cache_count >= tcp_syncache.cache_limit) {
286 		/*
287 		 * The cache is full.  Toss the oldest entry in the
288 		 * entire cache.  This is the front entry in the
289 		 * first non-empty timer queue with the largest
290 		 * timeout value.
291 		 */
292 		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
293 			sc2 = TAILQ_FIRST(&tcp_syncache.timerq[i]);
294 			if (sc2 != NULL)
295 				break;
296 		}
297 		sc2->sc_tp->ts_recent = ticks;
298 		syncache_drop(sc2, NULL);
299 		tcpstat.tcps_sc_cacheoverflow++;
300 	}
301 
302 	/* Initialize the entry's timer. */
303 	SYNCACHE_TIMEOUT(sc, 0);
304 
305 	/* Put it into the bucket. */
306 	TAILQ_INSERT_TAIL(&sch->sch_bucket, sc, sc_hash);
307 	sch->sch_length++;
308 	tcp_syncache.cache_count++;
309 	tcpstat.tcps_sc_added++;
310 }
311 
312 static void
313 syncache_drop(sc, sch)
314 	struct syncache *sc;
315 	struct syncache_head *sch;
316 {
317 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
318 
319 	if (sch == NULL) {
320 #ifdef INET6
321 		if (sc->sc_inc.inc_isipv6) {
322 			sch = &tcp_syncache.hashbase[
323 			    SYNCACHE_HASH6(&sc->sc_inc, tcp_syncache.hashmask)];
324 		} else
325 #endif
326 		{
327 			sch = &tcp_syncache.hashbase[
328 			    SYNCACHE_HASH(&sc->sc_inc, tcp_syncache.hashmask)];
329 		}
330 	}
331 
332 	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
333 	sch->sch_length--;
334 	tcp_syncache.cache_count--;
335 
336 	TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot], sc, sc_timerq);
337 	if (TAILQ_EMPTY(&tcp_syncache.timerq[sc->sc_rxtslot]))
338 		callout_stop(&tcp_syncache.tt_timerq[sc->sc_rxtslot]);
339 
340 	syncache_free(sc);
341 }
342 
343 /*
344  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
345  * If we have retransmitted an entry the maximum number of times, expire it.
346  */
347 static void
348 syncache_timer(xslot)
349 	void *xslot;
350 {
351 	intptr_t slot = (intptr_t)xslot;
352 	struct syncache *sc, *nsc;
353 	struct inpcb *inp;
354 
355 	INP_INFO_WLOCK(&tcbinfo);
356 	if (callout_pending(&tcp_syncache.tt_timerq[slot]) ||
357 	    !callout_active(&tcp_syncache.tt_timerq[slot])) {
358 		/* XXX can this happen? */
359 		INP_INFO_WUNLOCK(&tcbinfo);
360 		return;
361 	}
362 	callout_deactivate(&tcp_syncache.tt_timerq[slot]);
363 
364 	nsc = TAILQ_FIRST(&tcp_syncache.timerq[slot]);
365 	while (nsc != NULL) {
366 		if (ticks < nsc->sc_rxttime)
367 			break;
368 		sc = nsc;
369 		inp = sc->sc_tp->t_inpcb;
370 		if (slot == SYNCACHE_MAXREXMTS ||
371 		    slot >= tcp_syncache.rexmt_limit ||
372 		    inp == NULL || inp->inp_gencnt != sc->sc_inp_gencnt) {
373 			nsc = TAILQ_NEXT(sc, sc_timerq);
374 			syncache_drop(sc, NULL);
375 			tcpstat.tcps_sc_stale++;
376 			continue;
377 		}
378 		/*
379 		 * syncache_respond() may call back into the syncache to
380 		 * to modify another entry, so do not obtain the next
381 		 * entry on the timer chain until it has completed.
382 		 */
383 #ifdef TCPDEBUG
384 		(void) syncache_respond(sc, NULL, NULL);
385 #else
386 		(void) syncache_respond(sc, NULL);
387 #endif
388 		nsc = TAILQ_NEXT(sc, sc_timerq);
389 		tcpstat.tcps_sc_retransmitted++;
390 		TAILQ_REMOVE(&tcp_syncache.timerq[slot], sc, sc_timerq);
391 		SYNCACHE_TIMEOUT(sc, slot + 1);
392 	}
393 	if (nsc != NULL)
394 		callout_reset(&tcp_syncache.tt_timerq[slot],
395 		    nsc->sc_rxttime - ticks, syncache_timer, (void *)(slot));
396 	INP_INFO_WUNLOCK(&tcbinfo);
397 }
398 
399 /*
400  * Find an entry in the syncache.
401  */
402 struct syncache *
403 syncache_lookup(inc, schp)
404 	struct in_conninfo *inc;
405 	struct syncache_head **schp;
406 {
407 	struct syncache *sc;
408 	struct syncache_head *sch;
409 
410 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
411 
412 #ifdef INET6
413 	if (inc->inc_isipv6) {
414 		sch = &tcp_syncache.hashbase[
415 		    SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
416 		*schp = sch;
417 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
418 			if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
419 				return (sc);
420 		}
421 	} else
422 #endif
423 	{
424 		sch = &tcp_syncache.hashbase[
425 		    SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
426 		*schp = sch;
427 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
428 #ifdef INET6
429 			if (sc->sc_inc.inc_isipv6)
430 				continue;
431 #endif
432 			if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
433 				return (sc);
434 		}
435 	}
436 	return (NULL);
437 }
438 
439 /*
440  * This function is called when we get a RST for a
441  * non-existent connection, so that we can see if the
442  * connection is in the syn cache.  If it is, zap it.
443  */
444 void
445 syncache_chkrst(inc, th)
446 	struct in_conninfo *inc;
447 	struct tcphdr *th;
448 {
449 	struct syncache *sc;
450 	struct syncache_head *sch;
451 
452 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
453 
454 	sc = syncache_lookup(inc, &sch);
455 	if (sc == NULL)
456 		return;
457 	/*
458 	 * If the RST bit is set, check the sequence number to see
459 	 * if this is a valid reset segment.
460 	 * RFC 793 page 37:
461 	 *   In all states except SYN-SENT, all reset (RST) segments
462 	 *   are validated by checking their SEQ-fields.  A reset is
463 	 *   valid if its sequence number is in the window.
464 	 *
465 	 *   The sequence number in the reset segment is normally an
466 	 *   echo of our outgoing acknowlegement numbers, but some hosts
467 	 *   send a reset with the sequence number at the rightmost edge
468 	 *   of our receive window, and we have to handle this case.
469 	 */
470 	if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
471 	    SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
472 		syncache_drop(sc, sch);
473 		tcpstat.tcps_sc_reset++;
474 	}
475 }
476 
477 void
478 syncache_badack(inc)
479 	struct in_conninfo *inc;
480 {
481 	struct syncache *sc;
482 	struct syncache_head *sch;
483 
484 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
485 
486 	sc = syncache_lookup(inc, &sch);
487 	if (sc != NULL) {
488 		syncache_drop(sc, sch);
489 		tcpstat.tcps_sc_badack++;
490 	}
491 }
492 
493 void
494 syncache_unreach(inc, th)
495 	struct in_conninfo *inc;
496 	struct tcphdr *th;
497 {
498 	struct syncache *sc;
499 	struct syncache_head *sch;
500 
501 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
502 
503 	sc = syncache_lookup(inc, &sch);
504 	if (sc == NULL)
505 		return;
506 
507 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
508 	if (ntohl(th->th_seq) != sc->sc_iss)
509 		return;
510 
511 	/*
512 	 * If we've rertransmitted 3 times and this is our second error,
513 	 * we remove the entry.  Otherwise, we allow it to continue on.
514 	 * This prevents us from incorrectly nuking an entry during a
515 	 * spurious network outage.
516 	 *
517 	 * See tcp_notify().
518 	 */
519 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtslot < 3) {
520 		sc->sc_flags |= SCF_UNREACH;
521 		return;
522 	}
523 	syncache_drop(sc, sch);
524 	tcpstat.tcps_sc_unreach++;
525 }
526 
527 /*
528  * Build a new TCP socket structure from a syncache entry.
529  */
530 static struct socket *
531 syncache_socket(sc, lso, m)
532 	struct syncache *sc;
533 	struct socket *lso;
534 	struct mbuf *m;
535 {
536 	struct inpcb *inp = NULL;
537 	struct socket *so;
538 	struct tcpcb *tp;
539 
540 	NET_ASSERT_GIANT();
541 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
542 
543 	/*
544 	 * Ok, create the full blown connection, and set things up
545 	 * as they would have been set up if we had created the
546 	 * connection when the SYN arrived.  If we can't create
547 	 * the connection, abort it.
548 	 */
549 	so = sonewconn(lso, SS_ISCONNECTED);
550 	if (so == NULL) {
551 		/*
552 		 * Drop the connection; we will send a RST if the peer
553 		 * retransmits the ACK,
554 		 */
555 		tcpstat.tcps_listendrop++;
556 		goto abort2;
557 	}
558 #ifdef MAC
559 	SOCK_LOCK(so);
560 	mac_set_socket_peer_from_mbuf(m, so);
561 	SOCK_UNLOCK(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,
635 		    thread0.td_ucred)) {
636 			inp->in6p_laddr = laddr6;
637 			goto abort;
638 		}
639 		/* Override flowlabel from in6_pcbconnect. */
640 		inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
641 		inp->in6p_flowinfo |= sc->sc_flowlabel;
642 	} else
643 #endif
644 	{
645 		struct in_addr laddr;
646 		struct sockaddr_in sin;
647 
648 		inp->inp_options = ip_srcroute(m);
649 		if (inp->inp_options == NULL) {
650 			inp->inp_options = sc->sc_ipopts;
651 			sc->sc_ipopts = NULL;
652 		}
653 
654 		sin.sin_family = AF_INET;
655 		sin.sin_len = sizeof(sin);
656 		sin.sin_addr = sc->sc_inc.inc_faddr;
657 		sin.sin_port = sc->sc_inc.inc_fport;
658 		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
659 		laddr = inp->inp_laddr;
660 		if (inp->inp_laddr.s_addr == INADDR_ANY)
661 			inp->inp_laddr = sc->sc_inc.inc_laddr;
662 		if (in_pcbconnect(inp, (struct sockaddr *)&sin,
663 		    thread0.td_ucred)) {
664 			inp->inp_laddr = laddr;
665 			goto abort;
666 		}
667 	}
668 
669 	tp = intotcpcb(inp);
670 	tp->t_state = TCPS_SYN_RECEIVED;
671 	tp->iss = sc->sc_iss;
672 	tp->irs = sc->sc_irs;
673 	tcp_rcvseqinit(tp);
674 	tcp_sendseqinit(tp);
675 	tp->snd_wl1 = sc->sc_irs;
676 	tp->rcv_up = sc->sc_irs + 1;
677 	tp->rcv_wnd = sc->sc_wnd;
678 	tp->rcv_adv += tp->rcv_wnd;
679 
680 	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
681 	if (sc->sc_flags & SCF_NOOPT)
682 		tp->t_flags |= TF_NOOPT;
683 	if (sc->sc_flags & SCF_WINSCALE) {
684 		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
685 		tp->snd_scale = sc->sc_requested_s_scale;
686 		tp->request_r_scale = sc->sc_request_r_scale;
687 	}
688 	if (sc->sc_flags & SCF_TIMESTAMP) {
689 		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
690 		tp->ts_recent = sc->sc_tsrecent;
691 		tp->ts_recent_age = ticks;
692 	}
693 #ifdef TCP_SIGNATURE
694 	if (sc->sc_flags & SCF_SIGNATURE)
695 		tp->t_flags |= TF_SIGNATURE;
696 #endif
697 	if (sc->sc_flags & SCF_SACK) {
698 		tp->sack_enable = 1;
699 		tp->t_flags |= TF_SACK_PERMIT;
700 	}
701 	/*
702 	 * Set up MSS and get cached values from tcp_hostcache.
703 	 * This might overwrite some of the defaults we just set.
704 	 */
705 	tcp_mss(tp, sc->sc_peer_mss);
706 
707 	/*
708 	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
709 	 */
710 	if (sc->sc_rxtslot != 0)
711 		tp->snd_cwnd = tp->t_maxseg;
712 	callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
713 
714 	INP_UNLOCK(inp);
715 
716 	tcpstat.tcps_accepts++;
717 	return (so);
718 
719 abort:
720 	INP_UNLOCK(inp);
721 abort2:
722 	if (so != NULL)
723 		soabort(so);
724 	return (NULL);
725 }
726 
727 /*
728  * This function gets called when we receive an ACK for a
729  * socket in the LISTEN state.  We look up the connection
730  * in the syncache, and if its there, we pull it out of
731  * the cache and turn it into a full-blown connection in
732  * the SYN-RECEIVED state.
733  */
734 int
735 syncache_expand(inc, th, sop, m)
736 	struct in_conninfo *inc;
737 	struct tcphdr *th;
738 	struct socket **sop;
739 	struct mbuf *m;
740 {
741 	struct syncache *sc;
742 	struct syncache_head *sch;
743 	struct socket *so;
744 
745 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
746 
747 	sc = syncache_lookup(inc, &sch);
748 	if (sc == NULL) {
749 		/*
750 		 * There is no syncache entry, so see if this ACK is
751 		 * a returning syncookie.  To do this, first:
752 		 *  A. See if this socket has had a syncache entry dropped in
753 		 *     the past.  We don't want to accept a bogus syncookie
754 		 *     if we've never received a SYN.
755 		 *  B. check that the syncookie is valid.  If it is, then
756 		 *     cobble up a fake syncache entry, and return.
757 		 */
758 		if (!tcp_syncookies)
759 			return (0);
760 		sc = syncookie_lookup(inc, th, *sop);
761 		if (sc == NULL)
762 			return (0);
763 		sch = NULL;
764 		tcpstat.tcps_sc_recvcookie++;
765 	}
766 
767 	/*
768 	 * If seg contains an ACK, but not for our SYN/ACK, send a RST.
769 	 */
770 	if (th->th_ack != sc->sc_iss + 1) {
771 		if (sch == NULL)
772 			syncache_free(sc);
773 		return (0);
774 	}
775 
776 	so = syncache_socket(sc, *sop, m);
777 	if (so == NULL) {
778 #if 0
779 resetandabort:
780 		/* XXXjlemon check this - is this correct? */
781 		(void) tcp_respond(NULL, m, m, th,
782 		    th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
783 #endif
784 		m_freem(m);			/* XXX only needed for above */
785 		tcpstat.tcps_sc_aborted++;
786 	} else
787 		tcpstat.tcps_sc_completed++;
788 
789 	if (sch == NULL)
790 		syncache_free(sc);
791 	else
792 		syncache_drop(sc, sch);
793 	*sop = so;
794 	return (1);
795 }
796 
797 /*
798  * Given a LISTEN socket and an inbound SYN request, add
799  * this to the syn cache, and send back a segment:
800  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
801  * to the source.
802  *
803  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
804  * Doing so would require that we hold onto the data and deliver it
805  * to the application.  However, if we are the target of a SYN-flood
806  * DoS attack, an attacker could send data which would eventually
807  * consume all available buffer space if it were ACKed.  By not ACKing
808  * the data, we avoid this DoS scenario.
809  */
810 int
811 syncache_add(inc, to, th, sop, m)
812 	struct in_conninfo *inc;
813 	struct tcpopt *to;
814 	struct tcphdr *th;
815 	struct socket **sop;
816 	struct mbuf *m;
817 {
818 	struct tcpcb *tp;
819 	struct socket *so;
820 	struct syncache *sc = NULL;
821 	struct syncache_head *sch;
822 	struct mbuf *ipopts = NULL;
823 	u_int32_t flowtmp;
824 	int i, win;
825 
826 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
827 
828 	so = *sop;
829 	tp = sototcpcb(so);
830 
831 	/*
832 	 * Remember the IP options, if any.
833 	 */
834 #ifdef INET6
835 	if (!inc->inc_isipv6)
836 #endif
837 		ipopts = ip_srcroute(m);
838 
839 	/*
840 	 * See if we already have an entry for this connection.
841 	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
842 	 *
843 	 * XXX
844 	 * should the syncache be re-initialized with the contents
845 	 * of the new SYN here (which may have different options?)
846 	 */
847 	sc = syncache_lookup(inc, &sch);
848 	if (sc != NULL) {
849 		tcpstat.tcps_sc_dupsyn++;
850 		if (ipopts) {
851 			/*
852 			 * If we were remembering a previous source route,
853 			 * forget it and use the new one we've been given.
854 			 */
855 			if (sc->sc_ipopts)
856 				(void) m_free(sc->sc_ipopts);
857 			sc->sc_ipopts = ipopts;
858 		}
859 		/*
860 		 * Update timestamp if present.
861 		 */
862 		if (sc->sc_flags & SCF_TIMESTAMP)
863 			sc->sc_tsrecent = to->to_tsval;
864 		/*
865 		 * PCB may have changed, pick up new values.
866 		 */
867 		sc->sc_tp = tp;
868 		sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
869 #ifdef TCPDEBUG
870 		if (syncache_respond(sc, m, so) == 0) {
871 #else
872 		if (syncache_respond(sc, m) == 0) {
873 #endif
874 			/* NB: guarded by INP_INFO_WLOCK(&tcbinfo) */
875 			TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot],
876 			    sc, sc_timerq);
877 			SYNCACHE_TIMEOUT(sc, sc->sc_rxtslot);
878 			tcpstat.tcps_sndacks++;
879 			tcpstat.tcps_sndtotal++;
880 		}
881 		*sop = NULL;
882 		return (1);
883 	}
884 
885 	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
886 	if (sc == NULL) {
887 		/*
888 		 * The zone allocator couldn't provide more entries.
889 		 * Treat this as if the cache was full; drop the oldest
890 		 * entry and insert the new one.
891 		 */
892 		tcpstat.tcps_sc_zonefail++;
893 		/* NB: guarded by INP_INFO_WLOCK(&tcbinfo) */
894 		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
895 			sc = TAILQ_FIRST(&tcp_syncache.timerq[i]);
896 			if (sc != NULL)
897 				break;
898 		}
899 		if (sc == NULL) {
900 			/* Generic memory failure. */
901 			if (ipopts)
902 				(void) m_free(ipopts);
903 			return (0);
904 		}
905 		sc->sc_tp->ts_recent = ticks;
906 		syncache_drop(sc, NULL);
907 		sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
908 		if (sc == NULL) {
909 			if (ipopts)
910 				(void) m_free(ipopts);
911 			return (0);
912 		}
913 	}
914 
915 	/*
916 	 * Fill in the syncache values.
917 	 */
918 	sc->sc_tp = tp;
919 	sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
920 	sc->sc_ipopts = ipopts;
921 	sc->sc_inc.inc_fport = inc->inc_fport;
922 	sc->sc_inc.inc_lport = inc->inc_lport;
923 #ifdef INET6
924 	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
925 	if (inc->inc_isipv6) {
926 		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
927 		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
928 	} else
929 #endif
930 	{
931 		sc->sc_inc.inc_faddr = inc->inc_faddr;
932 		sc->sc_inc.inc_laddr = inc->inc_laddr;
933 	}
934 	sc->sc_irs = th->th_seq;
935 	sc->sc_flags = 0;
936 	sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
937 	sc->sc_flowlabel = 0;
938 	if (tcp_syncookies) {
939 		sc->sc_iss = syncookie_generate(sc, &flowtmp);
940 #ifdef INET6
941 		if (inc->inc_isipv6 &&
942 		    (sc->sc_tp->t_inpcb->in6p_flags & IN6P_AUTOFLOWLABEL)) {
943 			sc->sc_flowlabel = flowtmp & IPV6_FLOWLABEL_MASK;
944 		}
945 #endif
946 	} else {
947 		sc->sc_iss = arc4random();
948 #ifdef INET6
949 		if (inc->inc_isipv6 &&
950 		    (sc->sc_tp->t_inpcb->in6p_flags & IN6P_AUTOFLOWLABEL)) {
951 			sc->sc_flowlabel =
952 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
953 		}
954 #endif
955 	}
956 
957 	/* Initial receive window: clip sbspace to [0 .. TCP_MAXWIN] */
958 	win = sbspace(&so->so_rcv);
959 	win = imax(win, 0);
960 	win = imin(win, TCP_MAXWIN);
961 	sc->sc_wnd = win;
962 
963 	if (tcp_do_rfc1323) {
964 		/*
965 		 * A timestamp received in a SYN makes
966 		 * it ok to send timestamp requests and replies.
967 		 */
968 		if (to->to_flags & TOF_TS) {
969 			sc->sc_tsrecent = to->to_tsval;
970 			sc->sc_flags |= SCF_TIMESTAMP;
971 		}
972 		if (to->to_flags & TOF_SCALE) {
973 			int wscale = 0;
974 
975 			/* Compute proper scaling value from buffer space */
976 			while (wscale < TCP_MAX_WINSHIFT &&
977 			    (TCP_MAXWIN << wscale) < so->so_rcv.sb_hiwat)
978 				wscale++;
979 			sc->sc_request_r_scale = wscale;
980 			sc->sc_requested_s_scale = to->to_requested_s_scale;
981 			sc->sc_flags |= SCF_WINSCALE;
982 		}
983 	}
984 	if (tp->t_flags & TF_NOOPT)
985 		sc->sc_flags = SCF_NOOPT;
986 #ifdef TCP_SIGNATURE
987 	/*
988 	 * If listening socket requested TCP digests, and received SYN
989 	 * contains the option, flag this in the syncache so that
990 	 * syncache_respond() will do the right thing with the SYN+ACK.
991 	 * XXX Currently we always record the option by default and will
992 	 * attempt to use it in syncache_respond().
993 	 */
994 	if (to->to_flags & TOF_SIGNATURE)
995 		sc->sc_flags |= SCF_SIGNATURE;
996 #endif
997 
998 	if (to->to_flags & TOF_SACK)
999 		sc->sc_flags |= SCF_SACK;
1000 
1001 	/*
1002 	 * Do a standard 3-way handshake.
1003 	 */
1004 #ifdef TCPDEBUG
1005 	if (syncache_respond(sc, m, so) == 0) {
1006 #else
1007 	if (syncache_respond(sc, m) == 0) {
1008 #endif
1009 		syncache_insert(sc, sch);
1010 		tcpstat.tcps_sndacks++;
1011 		tcpstat.tcps_sndtotal++;
1012 	} else {
1013 		syncache_free(sc);
1014 		tcpstat.tcps_sc_dropped++;
1015 	}
1016 	*sop = NULL;
1017 	return (1);
1018 }
1019 
1020 #ifdef TCPDEBUG
1021 static int
1022 syncache_respond(sc, m, so)
1023 	struct syncache *sc;
1024 	struct mbuf *m;
1025 	struct socket *so;
1026 #else
1027 static int
1028 syncache_respond(sc, m)
1029 	struct syncache *sc;
1030 	struct mbuf *m;
1031 #endif
1032 {
1033 	u_int8_t *optp;
1034 	int optlen, error;
1035 	u_int16_t tlen, hlen, mssopt;
1036 	struct ip *ip = NULL;
1037 	struct tcphdr *th;
1038 	struct inpcb *inp;
1039 #ifdef INET6
1040 	struct ip6_hdr *ip6 = NULL;
1041 #endif
1042 
1043 	hlen =
1044 #ifdef INET6
1045 	       (sc->sc_inc.inc_isipv6) ? sizeof(struct ip6_hdr) :
1046 #endif
1047 		sizeof(struct ip);
1048 
1049 	KASSERT((&sc->sc_inc) != NULL, ("syncache_respond with NULL in_conninfo pointer"));
1050 
1051 	/* Determine MSS we advertize to other end of connection */
1052 	mssopt = tcp_mssopt(&sc->sc_inc);
1053 
1054 	/* Compute the size of the TCP options. */
1055 	if (sc->sc_flags & SCF_NOOPT) {
1056 		optlen = 0;
1057 	} else {
1058 		optlen = TCPOLEN_MAXSEG +
1059 		    ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
1060 		    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
1061 #ifdef TCP_SIGNATURE
1062 		if (sc->sc_flags & SCF_SIGNATURE)
1063 			optlen += TCPOLEN_SIGNATURE;
1064 #endif
1065 		if (sc->sc_flags & SCF_SACK)
1066 			optlen += TCPOLEN_SACK_PERMITTED;
1067 		optlen = roundup2(optlen, 4);
1068 	}
1069 	tlen = hlen + sizeof(struct tcphdr) + optlen;
1070 
1071 	/*
1072 	 * XXX
1073 	 * assume that the entire packet will fit in a header mbuf
1074 	 */
1075 	KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
1076 
1077 	/*
1078 	 * XXX shouldn't this reuse the mbuf if possible ?
1079 	 * Create the IP+TCP header from scratch.
1080 	 */
1081 	if (m)
1082 		m_freem(m);
1083 
1084 	m = m_gethdr(M_DONTWAIT, MT_DATA);
1085 	if (m == NULL)
1086 		return (ENOBUFS);
1087 	m->m_data += max_linkhdr;
1088 	m->m_len = tlen;
1089 	m->m_pkthdr.len = tlen;
1090 	m->m_pkthdr.rcvif = NULL;
1091 	inp = sc->sc_tp->t_inpcb;
1092 	INP_LOCK(inp);
1093 #ifdef MAC
1094 	mac_create_mbuf_from_inpcb(inp, m);
1095 #endif
1096 
1097 #ifdef INET6
1098 	if (sc->sc_inc.inc_isipv6) {
1099 		ip6 = mtod(m, struct ip6_hdr *);
1100 		ip6->ip6_vfc = IPV6_VERSION;
1101 		ip6->ip6_nxt = IPPROTO_TCP;
1102 		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1103 		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1104 		ip6->ip6_plen = htons(tlen - hlen);
1105 		/* ip6_hlim is set after checksum */
1106 		ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
1107 		ip6->ip6_flow |= sc->sc_flowlabel;
1108 
1109 		th = (struct tcphdr *)(ip6 + 1);
1110 	} else
1111 #endif
1112 	{
1113 		ip = mtod(m, struct ip *);
1114 		ip->ip_v = IPVERSION;
1115 		ip->ip_hl = sizeof(struct ip) >> 2;
1116 		ip->ip_len = tlen;
1117 		ip->ip_id = 0;
1118 		ip->ip_off = 0;
1119 		ip->ip_sum = 0;
1120 		ip->ip_p = IPPROTO_TCP;
1121 		ip->ip_src = sc->sc_inc.inc_laddr;
1122 		ip->ip_dst = sc->sc_inc.inc_faddr;
1123 		ip->ip_ttl = inp->inp_ip_ttl;   /* XXX */
1124 		ip->ip_tos = inp->inp_ip_tos;   /* XXX */
1125 
1126 		/*
1127 		 * See if we should do MTU discovery.  Route lookups are
1128 		 * expensive, so we will only unset the DF bit if:
1129 		 *
1130 		 *	1) path_mtu_discovery is disabled
1131 		 *	2) the SCF_UNREACH flag has been set
1132 		 */
1133 		if (path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1134 		       ip->ip_off |= IP_DF;
1135 
1136 		th = (struct tcphdr *)(ip + 1);
1137 	}
1138 	th->th_sport = sc->sc_inc.inc_lport;
1139 	th->th_dport = sc->sc_inc.inc_fport;
1140 
1141 	th->th_seq = htonl(sc->sc_iss);
1142 	th->th_ack = htonl(sc->sc_irs + 1);
1143 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1144 	th->th_x2 = 0;
1145 	th->th_flags = TH_SYN|TH_ACK;
1146 	th->th_win = htons(sc->sc_wnd);
1147 	th->th_urp = 0;
1148 
1149 	/* Tack on the TCP options. */
1150 	if (optlen != 0) {
1151 		optp = (u_int8_t *)(th + 1);
1152 		*optp++ = TCPOPT_MAXSEG;
1153 		*optp++ = TCPOLEN_MAXSEG;
1154 		*optp++ = (mssopt >> 8) & 0xff;
1155 		*optp++ = mssopt & 0xff;
1156 
1157 		if (sc->sc_flags & SCF_WINSCALE) {
1158 			*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1159 			    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1160 			    sc->sc_request_r_scale);
1161 			optp += 4;
1162 		}
1163 
1164 		if (sc->sc_flags & SCF_TIMESTAMP) {
1165 			u_int32_t *lp = (u_int32_t *)(optp);
1166 
1167 			/* Form timestamp option per appendix A of RFC 1323. */
1168 			*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1169 			*lp++ = htonl(ticks);
1170 			*lp   = htonl(sc->sc_tsrecent);
1171 			optp += TCPOLEN_TSTAMP_APPA;
1172 		}
1173 
1174 #ifdef TCP_SIGNATURE
1175 		/*
1176 		 * Handle TCP-MD5 passive opener response.
1177 		 */
1178 		if (sc->sc_flags & SCF_SIGNATURE) {
1179 			u_int8_t *bp = optp;
1180 			int i;
1181 
1182 			*bp++ = TCPOPT_SIGNATURE;
1183 			*bp++ = TCPOLEN_SIGNATURE;
1184 			for (i = 0; i < TCP_SIGLEN; i++)
1185 				*bp++ = 0;
1186 			tcp_signature_compute(m, sizeof(struct ip), 0, optlen,
1187 			    optp + 2, IPSEC_DIR_OUTBOUND);
1188 			optp += TCPOLEN_SIGNATURE;
1189 		}
1190 #endif /* TCP_SIGNATURE */
1191 
1192 		if (sc->sc_flags & SCF_SACK) {
1193 			*optp++ = TCPOPT_SACK_PERMITTED;
1194 			*optp++ = TCPOLEN_SACK_PERMITTED;
1195 		}
1196 
1197 		{
1198 			/* Pad TCP options to a 4 byte boundary */
1199 			int padlen = optlen - (optp - (u_int8_t *)(th + 1));
1200 			while (padlen-- > 0)
1201 				*optp++ = TCPOPT_EOL;
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, u_int32_t *flowid)
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 	*flowid = md5_buffer[1];
1333 	return (data);
1334 }
1335 
1336 static struct syncache *
1337 syncookie_lookup(inc, th, so)
1338 	struct in_conninfo *inc;
1339 	struct tcphdr *th;
1340 	struct socket *so;
1341 {
1342 	u_int32_t md5_buffer[4];
1343 	struct syncache *sc;
1344 	u_int32_t data;
1345 	int wnd, idx;
1346 	struct md5_add add;
1347 
1348 	/* NB: single threaded; could add INP_INFO_WLOCK_ASSERT(&tcbinfo) */
1349 
1350 	data = (th->th_ack - 1) ^ (th->th_seq - 1);	/* remove ISS */
1351 	idx = data & SYNCOOKIE_WNDMASK;
1352 	if (tcp_secret[idx].ts_expire < ticks ||
1353 	    sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
1354 		return (NULL);
1355 	MD5Init(&syn_ctx);
1356 #ifdef INET6
1357 	if (inc->inc_isipv6) {
1358 		MD5Add(inc->inc6_laddr);
1359 		MD5Add(inc->inc6_faddr);
1360 		add.laddr = 0;
1361 		add.faddr = 0;
1362 	} else
1363 #endif
1364 	{
1365 		add.laddr = inc->inc_laddr.s_addr;
1366 		add.faddr = inc->inc_faddr.s_addr;
1367 	}
1368 	add.lport = inc->inc_lport;
1369 	add.fport = inc->inc_fport;
1370 	add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1371 	add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1372 	add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1373 	add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1374 	MD5Add(add);
1375 	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1376 	data ^= md5_buffer[0];
1377 	if ((data & ~SYNCOOKIE_DATAMASK) != 0)
1378 		return (NULL);
1379 	data = data >> SYNCOOKIE_WNDBITS;
1380 
1381 	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
1382 	if (sc == NULL)
1383 		return (NULL);
1384 	/*
1385 	 * Fill in the syncache values.
1386 	 * XXX duplicate code from syncache_add
1387 	 */
1388 	sc->sc_ipopts = NULL;
1389 	sc->sc_inc.inc_fport = inc->inc_fport;
1390 	sc->sc_inc.inc_lport = inc->inc_lport;
1391 	sc->sc_tp = sototcpcb(so);
1392 #ifdef INET6
1393 	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1394 	if (inc->inc_isipv6) {
1395 		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1396 		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1397 		if (sc->sc_tp->t_inpcb->in6p_flags & IN6P_AUTOFLOWLABEL)
1398 			sc->sc_flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1399 	} else
1400 #endif
1401 	{
1402 		sc->sc_inc.inc_faddr = inc->inc_faddr;
1403 		sc->sc_inc.inc_laddr = inc->inc_laddr;
1404 	}
1405 	sc->sc_irs = th->th_seq - 1;
1406 	sc->sc_iss = th->th_ack - 1;
1407 	wnd = sbspace(&so->so_rcv);
1408 	wnd = imax(wnd, 0);
1409 	wnd = imin(wnd, TCP_MAXWIN);
1410 	sc->sc_wnd = wnd;
1411 	sc->sc_flags = 0;
1412 	sc->sc_rxtslot = 0;
1413 	sc->sc_peer_mss = tcp_msstab[data];
1414 	return (sc);
1415 }
1416