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