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