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