tcp_syncache.c revision 90982
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: head/sys/netinet/tcp_syncache.c 90982 2002-02-20 16:47:11Z jlemon $
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
88static int tcp_syncookies = 1;
89SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
90    &tcp_syncookies, 0,
91    "Use TCP SYN cookies if the syncache overflows");
92
93static void	 syncache_drop(struct syncache *, struct syncache_head *);
94static void	 syncache_free(struct syncache *);
95static void	 syncache_insert(struct syncache *, struct syncache_head *);
96struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
97static int	 syncache_respond(struct syncache *, struct mbuf *);
98static struct 	 socket *syncache_socket(struct syncache *, struct socket *);
99static void	 syncache_timer(void *);
100static u_int32_t syncookie_generate(struct syncache *);
101static 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
115struct 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};
129static struct tcp_syncache tcp_syncache;
130
131SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
132
133SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RD,
134     &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
135
136SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RD,
137     &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
138
139SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
140     &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
141
142SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RD,
143     &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
144
145SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
146     &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
147
148static 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
181static void
182syncache_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
210void
211syncache_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
263static void
264syncache_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
312static void
313syncache_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 */
350static void
351syncache_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 */
395struct syncache *
396syncache_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 */
444void
445syncache_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
475void
476syncache_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
489void
490syncache_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 */
525static struct socket *
526syncache_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 = sototcpcb(lso)->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
705abort:
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 */
718int
719syncache_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
758resetandabort:
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 */
790int
791syncache_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		/*
843		 * PCB may have changed, pick up new values.
844		 */
845		sc->sc_tp = tp;
846		sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
847		if (syncache_respond(sc, m) == 0) {
848		        s = splnet();
849			TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot],
850			    sc, sc_timerq);
851			SYNCACHE_TIMEOUT(sc, sc->sc_rxtslot);
852		        splx(s);
853		 	tcpstat.tcps_sndacks++;
854			tcpstat.tcps_sndtotal++;
855		}
856		*sop = NULL;
857		return (1);
858	}
859
860	sc = zalloc(tcp_syncache.zone);
861	if (sc == NULL) {
862		/*
863		 * The zone allocator couldn't provide more entries.
864		 * Treat this as if the cache was full; drop the oldest
865		 * entry and insert the new one.
866		 */
867		s = splnet();
868		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
869			sc = TAILQ_FIRST(&tcp_syncache.timerq[i]);
870			if (sc != NULL)
871				break;
872		}
873		sc->sc_tp->ts_recent = ticks;
874		syncache_drop(sc, NULL);
875		splx(s);
876		tcpstat.tcps_sc_zonefail++;
877		sc = zalloc(tcp_syncache.zone);
878		if (sc == NULL) {
879			if (ipopts)
880				(void) m_free(ipopts);
881			return (0);
882		}
883	}
884
885	/*
886	 * Fill in the syncache values.
887	 */
888	bzero(sc, sizeof(*sc));
889	sc->sc_tp = tp;
890	sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
891	sc->sc_ipopts = ipopts;
892	sc->sc_inc.inc_fport = inc->inc_fport;
893	sc->sc_inc.inc_lport = inc->inc_lport;
894#ifdef INET6
895	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
896	if (inc->inc_isipv6) {
897		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
898		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
899		sc->sc_route6.ro_rt = NULL;
900	} else
901#endif
902	{
903		sc->sc_inc.inc_faddr = inc->inc_faddr;
904		sc->sc_inc.inc_laddr = inc->inc_laddr;
905		sc->sc_route.ro_rt = NULL;
906	}
907	sc->sc_irs = th->th_seq;
908	if (tcp_syncookies)
909		sc->sc_iss = syncookie_generate(sc);
910	else
911		sc->sc_iss = arc4random();
912
913	/* Initial receive window: clip sbspace to [0 .. TCP_MAXWIN] */
914	win = sbspace(&so->so_rcv);
915	win = imax(win, 0);
916	win = imin(win, TCP_MAXWIN);
917	sc->sc_wnd = win;
918
919	sc->sc_flags = 0;
920	sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
921	if (tcp_do_rfc1323) {
922		/*
923		 * A timestamp received in a SYN makes
924		 * it ok to send timestamp requests and replies.
925		 */
926		if (to->to_flags & TOF_TS) {
927			sc->sc_tsrecent = to->to_tsval;
928			sc->sc_flags |= SCF_TIMESTAMP;
929		}
930		if (to->to_flags & TOF_SCALE) {
931			int wscale = 0;
932
933			/* Compute proper scaling value from buffer space */
934			while (wscale < TCP_MAX_WINSHIFT &&
935			    (TCP_MAXWIN << wscale) < so->so_rcv.sb_hiwat)
936				wscale++;
937			sc->sc_request_r_scale = wscale;
938			sc->sc_requested_s_scale = to->to_requested_s_scale;
939			sc->sc_flags |= SCF_WINSCALE;
940		}
941	}
942	if (tcp_do_rfc1644) {
943		/*
944		 * A CC or CC.new option received in a SYN makes
945		 * it ok to send CC in subsequent segments.
946		 */
947		if (to->to_flags & (TOF_CC|TOF_CCNEW)) {
948			sc->sc_cc_recv = to->to_cc;
949			sc->sc_cc_send = CC_INC(tcp_ccgen);
950			sc->sc_flags |= SCF_CC;
951		}
952	}
953	if (tp->t_flags & TF_NOOPT)
954		sc->sc_flags = SCF_NOOPT;
955
956	/*
957	 * XXX
958	 * We have the option here of not doing TAO (even if the segment
959	 * qualifies) and instead fall back to a normal 3WHS via the syncache.
960	 * This allows us to apply synflood protection to TAO-qualifying SYNs
961	 * also. However, there should be a hueristic to determine when to
962	 * do this, and is not present at the moment.
963	 */
964
965	/*
966	 * Perform TAO test on incoming CC (SEG.CC) option, if any.
967	 * - compare SEG.CC against cached CC from the same host, if any.
968	 * - if SEG.CC > chached value, SYN must be new and is accepted
969	 *	immediately: save new CC in the cache, mark the socket
970	 *	connected, enter ESTABLISHED state, turn on flag to
971	 *	send a SYN in the next segment.
972	 *	A virtual advertised window is set in rcv_adv to
973	 *	initialize SWS prevention.  Then enter normal segment
974	 *	processing: drop SYN, process data and FIN.
975	 * - otherwise do a normal 3-way handshake.
976	 */
977	taop = tcp_gettaocache(&sc->sc_inc);
978	if ((to->to_flags & TOF_CC) != 0) {
979		if (((tp->t_flags & TF_NOPUSH) != 0) &&
980		    sc->sc_flags & SCF_CC &&
981		    taop != NULL && taop->tao_cc != 0 &&
982		    CC_GT(to->to_cc, taop->tao_cc)) {
983			sc->sc_rxtslot = 0;
984			so = syncache_socket(sc, *sop);
985			if (so != NULL) {
986				sc->sc_flags |= SCF_KEEPROUTE;
987				taop->tao_cc = to->to_cc;
988				*sop = so;
989			}
990			syncache_free(sc);
991			return (so != NULL);
992		}
993	} else {
994		/*
995		 * No CC option, but maybe CC.NEW: invalidate cached value.
996		 */
997		if (taop != NULL)
998			taop->tao_cc = 0;
999	}
1000	/*
1001	 * TAO test failed or there was no CC option,
1002	 *    do a standard 3-way handshake.
1003	 */
1004	if (syncache_respond(sc, m) == 0) {
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
1016static int
1017syncache_respond(sc, m)
1018	struct syncache *sc;
1019	struct mbuf *m;
1020{
1021	u_int8_t *optp;
1022	int optlen, error;
1023	u_int16_t tlen, hlen, mssopt;
1024	struct ip *ip = NULL;
1025	struct rtentry *rt;
1026	struct tcphdr *th;
1027#ifdef INET6
1028	struct ip6_hdr *ip6 = NULL;
1029#endif
1030
1031#ifdef INET6
1032	if (sc->sc_inc.inc_isipv6) {
1033		rt = tcp_rtlookup6(&sc->sc_inc);
1034		if (rt != NULL)
1035			mssopt = rt->rt_ifp->if_mtu -
1036			     (sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1037		else
1038			mssopt = tcp_v6mssdflt;
1039		hlen = sizeof(struct ip6_hdr);
1040	} else
1041#endif
1042	{
1043		rt = tcp_rtlookup(&sc->sc_inc);
1044		if (rt != NULL)
1045			mssopt = rt->rt_ifp->if_mtu -
1046			     (sizeof(struct ip) + sizeof(struct tcphdr));
1047		else
1048			mssopt = tcp_mssdflt;
1049		hlen = sizeof(struct ip);
1050	}
1051
1052	/* Compute the size of the TCP options. */
1053	if (sc->sc_flags & SCF_NOOPT) {
1054		optlen = 0;
1055	} else {
1056		optlen = TCPOLEN_MAXSEG +
1057		    ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
1058		    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0) +
1059		    ((sc->sc_flags & SCF_CC) ? TCPOLEN_CC_APPA * 2 : 0);
1060	}
1061	tlen = hlen + sizeof(struct tcphdr) + optlen;
1062
1063	/*
1064	 * XXX
1065	 * assume that the entire packet will fit in a header mbuf
1066	 */
1067	KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
1068
1069	/*
1070	 * XXX shouldn't this reuse the mbuf if possible ?
1071	 * Create the IP+TCP header from scratch.
1072	 */
1073	if (m)
1074		m_freem(m);
1075
1076	m = m_gethdr(M_DONTWAIT, MT_HEADER);
1077	if (m == NULL)
1078		return (ENOBUFS);
1079	m->m_data += max_linkhdr;
1080	m->m_len = tlen;
1081	m->m_pkthdr.len = tlen;
1082	m->m_pkthdr.rcvif = NULL;
1083
1084#ifdef IPSEC
1085	/* use IPsec policy on listening socket to send SYN,ACK */
1086	if (ipsec_setsocket(m, sc->sc_tp->t_inpcb->inp_socket) != 0) {
1087		m_freem(m);
1088		return (ENOBUFS);
1089	}
1090#endif
1091
1092#ifdef INET6
1093	if (sc->sc_inc.inc_isipv6) {
1094		ip6 = mtod(m, struct ip6_hdr *);
1095		ip6->ip6_vfc = IPV6_VERSION;
1096		ip6->ip6_nxt = IPPROTO_TCP;
1097		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1098		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1099		ip6->ip6_plen = htons(tlen - hlen);
1100		/* ip6_hlim is set after checksum */
1101		/* ip6_flow = ??? */
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_tos = 0;
1111		ip->ip_len = tlen;
1112		ip->ip_id = 0;
1113		ip->ip_off = 0;
1114		ip->ip_ttl = ip_defttl;
1115		ip->ip_sum = 0;
1116		ip->ip_p = IPPROTO_TCP;
1117		ip->ip_src = sc->sc_inc.inc_laddr;
1118		ip->ip_dst = sc->sc_inc.inc_faddr;
1119
1120		th = (struct tcphdr *)(ip + 1);
1121	}
1122	th->th_sport = sc->sc_inc.inc_lport;
1123	th->th_dport = sc->sc_inc.inc_fport;
1124
1125	th->th_seq = htonl(sc->sc_iss);
1126	th->th_ack = htonl(sc->sc_irs + 1);
1127	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1128	th->th_x2 = 0;
1129	th->th_flags = TH_SYN|TH_ACK;
1130	th->th_win = htons(sc->sc_wnd);
1131	th->th_urp = 0;
1132
1133	/* Tack on the TCP options. */
1134	if (optlen == 0)
1135		goto no_options;
1136	optp = (u_int8_t *)(th + 1);
1137	*optp++ = TCPOPT_MAXSEG;
1138	*optp++ = TCPOLEN_MAXSEG;
1139	*optp++ = (mssopt >> 8) & 0xff;
1140	*optp++ = mssopt & 0xff;
1141
1142	if (sc->sc_flags & SCF_WINSCALE) {
1143		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1144		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1145		    sc->sc_request_r_scale);
1146		optp += 4;
1147	}
1148
1149	if (sc->sc_flags & SCF_TIMESTAMP) {
1150		u_int32_t *lp = (u_int32_t *)(optp);
1151
1152		/* Form timestamp option as shown in appendix A of RFC 1323. */
1153		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1154		*lp++ = htonl(ticks);
1155		*lp   = htonl(sc->sc_tsrecent);
1156		optp += TCPOLEN_TSTAMP_APPA;
1157	}
1158
1159	/*
1160         * Send CC and CC.echo if we received CC from our peer.
1161         */
1162        if (sc->sc_flags & SCF_CC) {
1163		u_int32_t *lp = (u_int32_t *)(optp);
1164
1165		*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
1166		*lp++ = htonl(sc->sc_cc_send);
1167		*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CCECHO));
1168		*lp   = htonl(sc->sc_cc_recv);
1169		optp += TCPOLEN_CC_APPA * 2;
1170	}
1171no_options:
1172
1173#ifdef INET6
1174	if (sc->sc_inc.inc_isipv6) {
1175		struct route_in6 *ro6 = &sc->sc_route6;
1176
1177		th->th_sum = 0;
1178		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1179		ip6->ip6_hlim = in6_selecthlim(NULL,
1180		    ro6->ro_rt ? ro6->ro_rt->rt_ifp : NULL);
1181		error = ip6_output(m, NULL, ro6, 0, NULL, NULL);
1182	} else
1183#endif
1184	{
1185        	th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1186		    htons(tlen - hlen + IPPROTO_TCP));
1187		m->m_pkthdr.csum_flags = CSUM_TCP;
1188		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1189		error = ip_output(m, sc->sc_ipopts, &sc->sc_route, 0, NULL);
1190	}
1191	return (error);
1192}
1193
1194/*
1195 * cookie layers:
1196 *
1197 *	|. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
1198 *	| peer iss                                                      |
1199 *	| MD5(laddr,faddr,lport,fport,secret)             |. . . . . . .|
1200 *	|                     0                       |(A)|             |
1201 * (A): peer mss index
1202 */
1203
1204/*
1205 * The values below are chosen to minimize the size of the tcp_secret
1206 * table, as well as providing roughly a 4 second lifetime for the cookie.
1207 */
1208
1209#define SYNCOOKIE_HASHSHIFT	2	/* log2(# of 32bit words from hash) */
1210#define SYNCOOKIE_WNDBITS	7	/* exposed bits for window indexing */
1211#define SYNCOOKIE_TIMESHIFT	5	/* scale ticks to window time units */
1212
1213#define SYNCOOKIE_HASHMASK	((1 << SYNCOOKIE_HASHSHIFT) - 1)
1214#define SYNCOOKIE_WNDMASK	((1 << SYNCOOKIE_WNDBITS) - 1)
1215#define SYNCOOKIE_NSECRETS	(1 << (SYNCOOKIE_WNDBITS - SYNCOOKIE_HASHSHIFT))
1216#define SYNCOOKIE_TIMEOUT \
1217    (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
1218#define SYNCOOKIE_DATAMASK 	((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
1219
1220static struct {
1221	u_int32_t	ts_secbits;
1222	u_int		ts_expire;
1223} tcp_secret[SYNCOOKIE_NSECRETS];
1224
1225static int tcp_msstab[] = { 0, 536, 1460, 8960 };
1226
1227static MD5_CTX syn_ctx;
1228
1229#define MD5Add(v)	MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
1230
1231/*
1232 * Consider the problem of a recreated (and retransmitted) cookie.  If the
1233 * original SYN was accepted, the connection is established.  The second
1234 * SYN is inflight, and if it arrives with an ISN that falls within the
1235 * receive window, the connection is killed.
1236 *
1237 * However, since cookies have other problems, this may not be worth
1238 * worrying about.
1239 */
1240
1241static u_int32_t
1242syncookie_generate(struct syncache *sc)
1243{
1244	u_int32_t md5_buffer[4];
1245	u_int32_t data;
1246	int wnd, idx;
1247
1248	wnd = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
1249	idx = wnd >> SYNCOOKIE_HASHSHIFT;
1250	if (tcp_secret[idx].ts_expire < ticks) {
1251		tcp_secret[idx].ts_secbits = arc4random();
1252		tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
1253	}
1254	for (data = sizeof(tcp_msstab) / sizeof(int) - 1; data > 0; data--)
1255		if (tcp_msstab[data] <= sc->sc_peer_mss)
1256			break;
1257	data = (data << SYNCOOKIE_WNDBITS) | wnd;
1258	data ^= sc->sc_irs;				/* peer's iss */
1259	MD5Init(&syn_ctx);
1260#ifdef INET6
1261	if (sc->sc_inc.inc_isipv6) {
1262		MD5Add(sc->sc_inc.inc6_laddr);
1263		MD5Add(sc->sc_inc.inc6_faddr);
1264	} else
1265#endif
1266	{
1267		MD5Add(sc->sc_inc.inc_laddr);
1268		MD5Add(sc->sc_inc.inc_faddr);
1269	}
1270	MD5Add(sc->sc_inc.inc_lport);
1271	MD5Add(sc->sc_inc.inc_fport);
1272	MD5Add(tcp_secret[idx].ts_secbits);
1273	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1274	data ^= (md5_buffer[wnd & SYNCOOKIE_HASHMASK] & ~SYNCOOKIE_WNDMASK);
1275	return (data);
1276}
1277
1278static struct syncache *
1279syncookie_lookup(inc, th, so)
1280	struct in_conninfo *inc;
1281	struct tcphdr *th;
1282	struct socket *so;
1283{
1284	u_int32_t md5_buffer[4];
1285	struct syncache *sc;
1286	u_int32_t data;
1287	int wnd, idx;
1288
1289	data = (th->th_ack - 1) ^ (th->th_seq - 1);	/* remove ISS */
1290	wnd = data & SYNCOOKIE_WNDMASK;
1291	idx = wnd >> SYNCOOKIE_HASHSHIFT;
1292	if (tcp_secret[idx].ts_expire < ticks ||
1293	    sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
1294		return (NULL);
1295	MD5Init(&syn_ctx);
1296#ifdef INET6
1297	if (inc->inc_isipv6) {
1298		MD5Add(inc->inc6_laddr);
1299		MD5Add(inc->inc6_faddr);
1300	} else
1301#endif
1302	{
1303		MD5Add(inc->inc_laddr);
1304		MD5Add(inc->inc_faddr);
1305	}
1306	MD5Add(inc->inc_lport);
1307	MD5Add(inc->inc_fport);
1308	MD5Add(tcp_secret[idx].ts_secbits);
1309	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1310	data ^= md5_buffer[wnd & SYNCOOKIE_HASHMASK];
1311	if ((data & ~SYNCOOKIE_DATAMASK) != 0)
1312		return (NULL);
1313	data = data >> SYNCOOKIE_WNDBITS;
1314
1315	sc = zalloc(tcp_syncache.zone);
1316	if (sc == NULL)
1317		return (NULL);
1318	/*
1319	 * Fill in the syncache values.
1320	 * XXX duplicate code from syncache_add
1321	 */
1322	sc->sc_ipopts = NULL;
1323	sc->sc_inc.inc_fport = inc->inc_fport;
1324	sc->sc_inc.inc_lport = inc->inc_lport;
1325#ifdef INET6
1326	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1327	if (inc->inc_isipv6) {
1328		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1329		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1330		sc->sc_route6.ro_rt = NULL;
1331	} else
1332#endif
1333	{
1334		sc->sc_inc.inc_faddr = inc->inc_faddr;
1335		sc->sc_inc.inc_laddr = inc->inc_laddr;
1336		sc->sc_route.ro_rt = NULL;
1337	}
1338	sc->sc_irs = th->th_seq - 1;
1339	sc->sc_iss = th->th_ack - 1;
1340	wnd = sbspace(&so->so_rcv);
1341	wnd = imax(wnd, 0);
1342	wnd = imin(wnd, TCP_MAXWIN);
1343	sc->sc_wnd = wnd;
1344	sc->sc_flags = 0;
1345	sc->sc_rxtslot = 0;
1346	sc->sc_peer_mss = tcp_msstab[data];
1347	return (sc);
1348}
1349