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