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