tcp_syncache.c revision 125819
186764Sjlemon/*-
292275Srwatson * Copyright (c) 2001 Networks Associates Technology, Inc.
386764Sjlemon * All rights reserved.
486764Sjlemon *
586764Sjlemon * This software was developed for the FreeBSD Project by Jonathan Lemon
686764Sjlemon * and NAI Labs, the Security Research Division of Network Associates, Inc.
786764Sjlemon * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
886764Sjlemon * DARPA CHATS research program.
986764Sjlemon *
1086764Sjlemon * Redistribution and use in source and binary forms, with or without
1186764Sjlemon * modification, are permitted provided that the following conditions
1286764Sjlemon * are met:
1386764Sjlemon * 1. Redistributions of source code must retain the above copyright
1486764Sjlemon *    notice, this list of conditions and the following disclaimer.
1586764Sjlemon * 2. Redistributions in binary form must reproduce the above copyright
1686764Sjlemon *    notice, this list of conditions and the following disclaimer in the
1786764Sjlemon *    documentation and/or other materials provided with the distribution.
1886764Sjlemon * 3. The name of the author may not be used to endorse or promote
1986764Sjlemon *    products derived from this software without specific prior written
2086764Sjlemon *    permission.
2186764Sjlemon *
2286764Sjlemon * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
2386764Sjlemon * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2486764Sjlemon * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2586764Sjlemon * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2686764Sjlemon * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2786764Sjlemon * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2886764Sjlemon * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2986764Sjlemon * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3086764Sjlemon * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3186764Sjlemon * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3286764Sjlemon * SUCH DAMAGE.
3386764Sjlemon *
3486764Sjlemon * $FreeBSD: head/sys/netinet/tcp_syncache.c 125819 2004-02-14 21:49:48Z bms $
3586764Sjlemon */
3686764Sjlemon
37125680Sbms#include "opt_inet.h"
3886764Sjlemon#include "opt_inet6.h"
3986764Sjlemon#include "opt_ipsec.h"
40101106Srwatson#include "opt_mac.h"
41118864Sharti#include "opt_tcpdebug.h"
4286764Sjlemon
4386764Sjlemon#include <sys/param.h>
4486764Sjlemon#include <sys/systm.h>
4586764Sjlemon#include <sys/kernel.h>
4686764Sjlemon#include <sys/sysctl.h>
4786764Sjlemon#include <sys/malloc.h>
48101106Srwatson#include <sys/mac.h>
4986764Sjlemon#include <sys/mbuf.h>
5086764Sjlemon#include <sys/md5.h>
5186764Sjlemon#include <sys/proc.h>		/* for proc0 declaration */
5286764Sjlemon#include <sys/random.h>
5386764Sjlemon#include <sys/socket.h>
5486764Sjlemon#include <sys/socketvar.h>
5586764Sjlemon
5686764Sjlemon#include <net/if.h>
5786764Sjlemon#include <net/route.h>
5886764Sjlemon
5986764Sjlemon#include <netinet/in.h>
6086764Sjlemon#include <netinet/in_systm.h>
6186764Sjlemon#include <netinet/ip.h>
6286764Sjlemon#include <netinet/in_var.h>
6386764Sjlemon#include <netinet/in_pcb.h>
6486764Sjlemon#include <netinet/ip_var.h>
6586764Sjlemon#ifdef INET6
6686764Sjlemon#include <netinet/ip6.h>
6786764Sjlemon#include <netinet/icmp6.h>
6886764Sjlemon#include <netinet6/nd6.h>
6986764Sjlemon#include <netinet6/ip6_var.h>
7086764Sjlemon#include <netinet6/in6_pcb.h>
7186764Sjlemon#endif
7286764Sjlemon#include <netinet/tcp.h>
73118864Sharti#ifdef TCPDEBUG
74118864Sharti#include <netinet/tcpip.h>
75118864Sharti#endif
7686764Sjlemon#include <netinet/tcp_fsm.h>
7786764Sjlemon#include <netinet/tcp_seq.h>
7886764Sjlemon#include <netinet/tcp_timer.h>
7986764Sjlemon#include <netinet/tcp_var.h>
80118864Sharti#ifdef TCPDEBUG
81118864Sharti#include <netinet/tcp_debug.h>
82118864Sharti#endif
8386764Sjlemon#ifdef INET6
8486764Sjlemon#include <netinet6/tcp6_var.h>
8586764Sjlemon#endif
8686764Sjlemon
8786764Sjlemon#ifdef IPSEC
8886764Sjlemon#include <netinet6/ipsec.h>
8986764Sjlemon#ifdef INET6
9086764Sjlemon#include <netinet6/ipsec6.h>
9186764Sjlemon#endif
9286764Sjlemon#endif /*IPSEC*/
9386764Sjlemon
94105199Ssam#ifdef FAST_IPSEC
95105199Ssam#include <netipsec/ipsec.h>
96105199Ssam#ifdef INET6
97105199Ssam#include <netipsec/ipsec6.h>
98105199Ssam#endif
99105199Ssam#include <netipsec/key.h>
100105199Ssam#endif /*FAST_IPSEC*/
101105199Ssam
10286764Sjlemon#include <machine/in_cksum.h>
10392760Sjeff#include <vm/uma.h>
10486764Sjlemon
10588180Sjlemonstatic int tcp_syncookies = 1;
10688180SjlemonSYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
10788180Sjlemon    &tcp_syncookies, 0,
10888180Sjlemon    "Use TCP SYN cookies if the syncache overflows");
10988180Sjlemon
11086764Sjlemonstatic void	 syncache_drop(struct syncache *, struct syncache_head *);
11186764Sjlemonstatic void	 syncache_free(struct syncache *);
11288180Sjlemonstatic void	 syncache_insert(struct syncache *, struct syncache_head *);
11386764Sjlemonstruct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
114118864Sharti#ifdef TCPDEBUG
115118864Shartistatic int	 syncache_respond(struct syncache *, struct mbuf *, struct socket *);
116118864Sharti#else
11786764Sjlemonstatic int	 syncache_respond(struct syncache *, struct mbuf *);
118118864Sharti#endif
11996602Srwatsonstatic struct 	 socket *syncache_socket(struct syncache *, struct socket *,
12096602Srwatson		    struct mbuf *m);
12186764Sjlemonstatic void	 syncache_timer(void *);
12288180Sjlemonstatic u_int32_t syncookie_generate(struct syncache *);
12388180Sjlemonstatic struct syncache *syncookie_lookup(struct in_conninfo *,
12488180Sjlemon		    struct tcphdr *, struct socket *);
12586764Sjlemon
12686764Sjlemon/*
12786764Sjlemon * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
12886764Sjlemon * 3 retransmits corresponds to a timeout of (1 + 2 + 4 + 8 == 15) seconds,
12986764Sjlemon * the odds are that the user has given up attempting to connect by then.
13086764Sjlemon */
13186764Sjlemon#define SYNCACHE_MAXREXMTS		3
13286764Sjlemon
13386764Sjlemon/* Arbitrary values */
13486764Sjlemon#define TCP_SYNCACHE_HASHSIZE		512
13586764Sjlemon#define TCP_SYNCACHE_BUCKETLIMIT	30
13686764Sjlemon
13786764Sjlemonstruct tcp_syncache {
13886764Sjlemon	struct	syncache_head *hashbase;
13992760Sjeff	uma_zone_t zone;
14086764Sjlemon	u_int	hashsize;
14186764Sjlemon	u_int	hashmask;
14286764Sjlemon	u_int	bucket_limit;
14386764Sjlemon	u_int	cache_count;
14486764Sjlemon	u_int	cache_limit;
14586764Sjlemon	u_int	rexmt_limit;
14686764Sjlemon	u_int	hash_secret;
14786764Sjlemon	TAILQ_HEAD(, syncache) timerq[SYNCACHE_MAXREXMTS + 1];
14886764Sjlemon	struct	callout tt_timerq[SYNCACHE_MAXREXMTS + 1];
14986764Sjlemon};
15086764Sjlemonstatic struct tcp_syncache tcp_syncache;
15186764Sjlemon
15286764SjlemonSYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
15386764Sjlemon
154121307SsilbySYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RDTUN,
15586764Sjlemon     &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
15686764Sjlemon
157121307SsilbySYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RDTUN,
15886764Sjlemon     &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
15986764Sjlemon
16086764SjlemonSYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
16186764Sjlemon     &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
16286764Sjlemon
163121307SsilbySYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RDTUN,
16486764Sjlemon     &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
16586764Sjlemon
16686764SjlemonSYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
16786764Sjlemon     &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
16886764Sjlemon
16986764Sjlemonstatic MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
17086764Sjlemon
17186764Sjlemon#define SYNCACHE_HASH(inc, mask) 					\
17286764Sjlemon	((tcp_syncache.hash_secret ^					\
17386764Sjlemon	  (inc)->inc_faddr.s_addr ^					\
17486764Sjlemon	  ((inc)->inc_faddr.s_addr >> 16) ^ 				\
17586764Sjlemon	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
17686764Sjlemon
17786764Sjlemon#define SYNCACHE_HASH6(inc, mask) 					\
17886764Sjlemon	((tcp_syncache.hash_secret ^					\
17986764Sjlemon	  (inc)->inc6_faddr.s6_addr32[0] ^ 				\
18086764Sjlemon	  (inc)->inc6_faddr.s6_addr32[3] ^ 				\
18186764Sjlemon	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
18286764Sjlemon
18386764Sjlemon#define ENDPTS_EQ(a, b) (						\
18489667Sjlemon	(a)->ie_fport == (b)->ie_fport &&				\
18586764Sjlemon	(a)->ie_lport == (b)->ie_lport &&				\
18686764Sjlemon	(a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&			\
18786764Sjlemon	(a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr			\
18886764Sjlemon)
18986764Sjlemon
19086764Sjlemon#define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
19186764Sjlemon
192106696Salfred#define SYNCACHE_TIMEOUT(sc, slot) do {				\
193106696Salfred	sc->sc_rxtslot = (slot);					\
194106696Salfred	sc->sc_rxttime = ticks + TCPTV_RTOBASE * tcp_backoff[(slot)];	\
195106696Salfred	TAILQ_INSERT_TAIL(&tcp_syncache.timerq[(slot)], sc, sc_timerq);	\
196106696Salfred	if (!callout_active(&tcp_syncache.tt_timerq[(slot)]))		\
197106696Salfred		callout_reset(&tcp_syncache.tt_timerq[(slot)],		\
198106696Salfred		    TCPTV_RTOBASE * tcp_backoff[(slot)],		\
199106696Salfred		    syncache_timer, (void *)((intptr_t)(slot)));	\
20086764Sjlemon} while (0)
20186764Sjlemon
20286764Sjlemonstatic void
20386764Sjlemonsyncache_free(struct syncache *sc)
20486764Sjlemon{
20586764Sjlemon	if (sc->sc_ipopts)
20686764Sjlemon		(void) m_free(sc->sc_ipopts);
207122922Sandre
20892760Sjeff	uma_zfree(tcp_syncache.zone, sc);
20986764Sjlemon}
21086764Sjlemon
21186764Sjlemonvoid
21286764Sjlemonsyncache_init(void)
21386764Sjlemon{
21486764Sjlemon	int i;
21586764Sjlemon
21686764Sjlemon	tcp_syncache.cache_count = 0;
21786764Sjlemon	tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
21886764Sjlemon	tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
21986764Sjlemon	tcp_syncache.cache_limit =
22086764Sjlemon	    tcp_syncache.hashsize * tcp_syncache.bucket_limit;
22186764Sjlemon	tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
22286764Sjlemon	tcp_syncache.hash_secret = arc4random();
22386764Sjlemon
22486764Sjlemon        TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
22586764Sjlemon	    &tcp_syncache.hashsize);
22686764Sjlemon        TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
22786764Sjlemon	    &tcp_syncache.cache_limit);
22886764Sjlemon        TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
22986764Sjlemon	    &tcp_syncache.bucket_limit);
23086764Sjlemon	if (!powerof2(tcp_syncache.hashsize)) {
23186764Sjlemon                printf("WARNING: syncache hash size is not a power of 2.\n");
23286764Sjlemon		tcp_syncache.hashsize = 512;	/* safe default */
23386764Sjlemon        }
23486764Sjlemon	tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
23586764Sjlemon
23686764Sjlemon	/* Allocate the hash table. */
23786764Sjlemon	MALLOC(tcp_syncache.hashbase, struct syncache_head *,
23886764Sjlemon	    tcp_syncache.hashsize * sizeof(struct syncache_head),
239111119Simp	    M_SYNCACHE, M_WAITOK);
24086764Sjlemon
24186764Sjlemon	/* Initialize the hash buckets. */
24286764Sjlemon	for (i = 0; i < tcp_syncache.hashsize; i++) {
24386764Sjlemon		TAILQ_INIT(&tcp_syncache.hashbase[i].sch_bucket);
24486764Sjlemon		tcp_syncache.hashbase[i].sch_length = 0;
24586764Sjlemon	}
24686764Sjlemon
24786764Sjlemon	/* Initialize the timer queues. */
24886814Sbde	for (i = 0; i <= SYNCACHE_MAXREXMTS; i++) {
24986764Sjlemon		TAILQ_INIT(&tcp_syncache.timerq[i]);
250122449Ssam		callout_init(&tcp_syncache.tt_timerq[i],
251122449Ssam			debug_mpsafenet ? CALLOUT_MPSAFE : 0);
25286764Sjlemon	}
25386764Sjlemon
25486764Sjlemon	/*
25586764Sjlemon	 * Allocate the syncache entries.  Allow the zone to allocate one
25686764Sjlemon	 * more entry than cache limit, so a new entry can bump out an
25786764Sjlemon	 * older one.
25886764Sjlemon	 */
25992760Sjeff	tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
26092760Sjeff	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
26192760Sjeff	uma_zone_set_max(tcp_syncache.zone, tcp_syncache.cache_limit);
262124848Sandre	tcp_syncache.cache_limit -= 1;
26386764Sjlemon}
26486764Sjlemon
26588180Sjlemonstatic void
26686764Sjlemonsyncache_insert(sc, sch)
26786764Sjlemon	struct syncache *sc;
26886764Sjlemon	struct syncache_head *sch;
26986764Sjlemon{
27086764Sjlemon	struct syncache *sc2;
271122496Ssam	int i;
27286764Sjlemon
273122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
274122496Ssam
27586764Sjlemon	/*
27686764Sjlemon	 * Make sure that we don't overflow the per-bucket
27786764Sjlemon	 * limit or the total cache size limit.
27886764Sjlemon	 */
27986764Sjlemon	if (sch->sch_length >= tcp_syncache.bucket_limit) {
28086764Sjlemon		/*
28186764Sjlemon		 * The bucket is full, toss the oldest element.
28286764Sjlemon		 */
28386764Sjlemon		sc2 = TAILQ_FIRST(&sch->sch_bucket);
28488180Sjlemon		sc2->sc_tp->ts_recent = ticks;
28586764Sjlemon		syncache_drop(sc2, sch);
28686764Sjlemon		tcpstat.tcps_sc_bucketoverflow++;
28786764Sjlemon	} else if (tcp_syncache.cache_count >= tcp_syncache.cache_limit) {
28886764Sjlemon		/*
28986764Sjlemon		 * The cache is full.  Toss the oldest entry in the
29086764Sjlemon		 * entire cache.  This is the front entry in the
29186764Sjlemon		 * first non-empty timer queue with the largest
29286764Sjlemon		 * timeout value.
29386764Sjlemon		 */
29486764Sjlemon		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
29586764Sjlemon			sc2 = TAILQ_FIRST(&tcp_syncache.timerq[i]);
29686764Sjlemon			if (sc2 != NULL)
29786764Sjlemon				break;
29886764Sjlemon		}
29988180Sjlemon		sc2->sc_tp->ts_recent = ticks;
30086764Sjlemon		syncache_drop(sc2, NULL);
30186764Sjlemon		tcpstat.tcps_sc_cacheoverflow++;
30286764Sjlemon	}
30386764Sjlemon
30486764Sjlemon	/* Initialize the entry's timer. */
30586764Sjlemon	SYNCACHE_TIMEOUT(sc, 0);
30686764Sjlemon
30786764Sjlemon	/* Put it into the bucket. */
30886764Sjlemon	TAILQ_INSERT_TAIL(&sch->sch_bucket, sc, sc_hash);
30986764Sjlemon	sch->sch_length++;
31086764Sjlemon	tcp_syncache.cache_count++;
31186764Sjlemon	tcpstat.tcps_sc_added++;
31286764Sjlemon}
31386764Sjlemon
31486764Sjlemonstatic void
31586764Sjlemonsyncache_drop(sc, sch)
31686764Sjlemon	struct syncache *sc;
31786764Sjlemon	struct syncache_head *sch;
31886764Sjlemon{
319122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
32086764Sjlemon
32186764Sjlemon	if (sch == NULL) {
32286764Sjlemon#ifdef INET6
32386764Sjlemon		if (sc->sc_inc.inc_isipv6) {
32486764Sjlemon			sch = &tcp_syncache.hashbase[
32586764Sjlemon			    SYNCACHE_HASH6(&sc->sc_inc, tcp_syncache.hashmask)];
32686764Sjlemon		} else
32786764Sjlemon#endif
32886764Sjlemon		{
32986764Sjlemon			sch = &tcp_syncache.hashbase[
33086764Sjlemon			    SYNCACHE_HASH(&sc->sc_inc, tcp_syncache.hashmask)];
33186764Sjlemon		}
33286764Sjlemon	}
33386764Sjlemon
33486764Sjlemon	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
33586764Sjlemon	sch->sch_length--;
33686764Sjlemon	tcp_syncache.cache_count--;
33786764Sjlemon
33886764Sjlemon	TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot], sc, sc_timerq);
33986764Sjlemon	if (TAILQ_EMPTY(&tcp_syncache.timerq[sc->sc_rxtslot]))
34086764Sjlemon		callout_stop(&tcp_syncache.tt_timerq[sc->sc_rxtslot]);
34186764Sjlemon
34286764Sjlemon	syncache_free(sc);
34386764Sjlemon}
34486764Sjlemon
34586764Sjlemon/*
34686764Sjlemon * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
34786764Sjlemon * If we have retransmitted an entry the maximum number of times, expire it.
34886764Sjlemon */
34986764Sjlemonstatic void
35086764Sjlemonsyncache_timer(xslot)
35186764Sjlemon	void *xslot;
35286764Sjlemon{
35388195Sjlemon	intptr_t slot = (intptr_t)xslot;
35486764Sjlemon	struct syncache *sc, *nsc;
35586764Sjlemon	struct inpcb *inp;
35686764Sjlemon
357110737Shsu	INP_INFO_WLOCK(&tcbinfo);
35886764Sjlemon        if (callout_pending(&tcp_syncache.tt_timerq[slot]) ||
35986764Sjlemon            !callout_active(&tcp_syncache.tt_timerq[slot])) {
360122496Ssam		/* XXX can this happen? */
361122501Ssam		INP_INFO_WUNLOCK(&tcbinfo);
36286764Sjlemon                return;
36386764Sjlemon        }
36486764Sjlemon        callout_deactivate(&tcp_syncache.tt_timerq[slot]);
36586764Sjlemon
36686764Sjlemon        nsc = TAILQ_FIRST(&tcp_syncache.timerq[slot]);
36786764Sjlemon	while (nsc != NULL) {
36886764Sjlemon		if (ticks < nsc->sc_rxttime)
36986764Sjlemon			break;
37086764Sjlemon		sc = nsc;
37186764Sjlemon		inp = sc->sc_tp->t_inpcb;
37286764Sjlemon		if (slot == SYNCACHE_MAXREXMTS ||
37386764Sjlemon		    slot >= tcp_syncache.rexmt_limit ||
374108703Shsu		    inp == NULL || inp->inp_gencnt != sc->sc_inp_gencnt) {
37598982Sjlemon			nsc = TAILQ_NEXT(sc, sc_timerq);
37686764Sjlemon			syncache_drop(sc, NULL);
37786764Sjlemon			tcpstat.tcps_sc_stale++;
37886764Sjlemon			continue;
37986764Sjlemon		}
38098982Sjlemon		/*
38198982Sjlemon		 * syncache_respond() may call back into the syncache to
38298982Sjlemon		 * to modify another entry, so do not obtain the next
38398982Sjlemon		 * entry on the timer chain until it has completed.
38498982Sjlemon		 */
385118864Sharti#ifdef TCPDEBUG
386118864Sharti		(void) syncache_respond(sc, NULL, NULL);
387118864Sharti#else
38886764Sjlemon		(void) syncache_respond(sc, NULL);
389118864Sharti#endif
39098982Sjlemon		nsc = TAILQ_NEXT(sc, sc_timerq);
39186764Sjlemon		tcpstat.tcps_sc_retransmitted++;
39286764Sjlemon		TAILQ_REMOVE(&tcp_syncache.timerq[slot], sc, sc_timerq);
39386764Sjlemon		SYNCACHE_TIMEOUT(sc, slot + 1);
39486764Sjlemon	}
39586764Sjlemon	if (nsc != NULL)
39686764Sjlemon		callout_reset(&tcp_syncache.tt_timerq[slot],
39786764Sjlemon		    nsc->sc_rxttime - ticks, syncache_timer, (void *)(slot));
398122501Ssam	INP_INFO_WUNLOCK(&tcbinfo);
39986764Sjlemon}
40086764Sjlemon
40186764Sjlemon/*
40286764Sjlemon * Find an entry in the syncache.
40386764Sjlemon */
40486764Sjlemonstruct syncache *
40586764Sjlemonsyncache_lookup(inc, schp)
40686764Sjlemon	struct in_conninfo *inc;
40786764Sjlemon	struct syncache_head **schp;
40886764Sjlemon{
40986764Sjlemon	struct syncache *sc;
41086764Sjlemon	struct syncache_head *sch;
41186764Sjlemon
412122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
413122496Ssam
41486764Sjlemon#ifdef INET6
41586764Sjlemon	if (inc->inc_isipv6) {
41686764Sjlemon		sch = &tcp_syncache.hashbase[
41786764Sjlemon		    SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
41886764Sjlemon		*schp = sch;
41986764Sjlemon		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
420122496Ssam			if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
42186764Sjlemon				return (sc);
42286764Sjlemon		}
42386764Sjlemon	} else
42486764Sjlemon#endif
42586764Sjlemon	{
42686764Sjlemon		sch = &tcp_syncache.hashbase[
42786764Sjlemon		    SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
42886764Sjlemon		*schp = sch;
42986764Sjlemon		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
43086764Sjlemon#ifdef INET6
43186764Sjlemon			if (sc->sc_inc.inc_isipv6)
43286764Sjlemon				continue;
43386764Sjlemon#endif
434122496Ssam			if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
43586764Sjlemon				return (sc);
43686764Sjlemon		}
43786764Sjlemon	}
43886764Sjlemon	return (NULL);
43986764Sjlemon}
44086764Sjlemon
44186764Sjlemon/*
44286764Sjlemon * This function is called when we get a RST for a
44386764Sjlemon * non-existent connection, so that we can see if the
44486764Sjlemon * connection is in the syn cache.  If it is, zap it.
44586764Sjlemon */
44686764Sjlemonvoid
44786764Sjlemonsyncache_chkrst(inc, th)
44886764Sjlemon	struct in_conninfo *inc;
44986764Sjlemon	struct tcphdr *th;
45086764Sjlemon{
45186764Sjlemon	struct syncache *sc;
45286764Sjlemon	struct syncache_head *sch;
45386764Sjlemon
454122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
455122496Ssam
45686764Sjlemon	sc = syncache_lookup(inc, &sch);
45786764Sjlemon	if (sc == NULL)
45886764Sjlemon		return;
45986764Sjlemon	/*
46086764Sjlemon	 * If the RST bit is set, check the sequence number to see
46186764Sjlemon	 * if this is a valid reset segment.
46286764Sjlemon	 * RFC 793 page 37:
46386764Sjlemon	 *   In all states except SYN-SENT, all reset (RST) segments
46486764Sjlemon	 *   are validated by checking their SEQ-fields.  A reset is
46586764Sjlemon	 *   valid if its sequence number is in the window.
46686764Sjlemon	 *
46786764Sjlemon	 *   The sequence number in the reset segment is normally an
46886764Sjlemon	 *   echo of our outgoing acknowlegement numbers, but some hosts
46986764Sjlemon	 *   send a reset with the sequence number at the rightmost edge
47086764Sjlemon	 *   of our receive window, and we have to handle this case.
47186764Sjlemon	 */
47286764Sjlemon	if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
47386764Sjlemon	    SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
47486764Sjlemon		syncache_drop(sc, sch);
47586764Sjlemon		tcpstat.tcps_sc_reset++;
47686764Sjlemon	}
47786764Sjlemon}
47886764Sjlemon
47986764Sjlemonvoid
48086764Sjlemonsyncache_badack(inc)
48186764Sjlemon	struct in_conninfo *inc;
48286764Sjlemon{
48386764Sjlemon	struct syncache *sc;
48486764Sjlemon	struct syncache_head *sch;
48586764Sjlemon
486122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
487122496Ssam
48886764Sjlemon	sc = syncache_lookup(inc, &sch);
48986764Sjlemon	if (sc != NULL) {
49086764Sjlemon		syncache_drop(sc, sch);
49186764Sjlemon		tcpstat.tcps_sc_badack++;
49286764Sjlemon	}
49386764Sjlemon}
49486764Sjlemon
49586764Sjlemonvoid
49686764Sjlemonsyncache_unreach(inc, th)
49786764Sjlemon	struct in_conninfo *inc;
49886764Sjlemon	struct tcphdr *th;
49986764Sjlemon{
50086764Sjlemon	struct syncache *sc;
50186764Sjlemon	struct syncache_head *sch;
50286764Sjlemon
503122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
504122496Ssam
50586764Sjlemon	/* we are called at splnet() here */
50686764Sjlemon	sc = syncache_lookup(inc, &sch);
50786764Sjlemon	if (sc == NULL)
50886764Sjlemon		return;
50986764Sjlemon
51086764Sjlemon	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
51186764Sjlemon	if (ntohl(th->th_seq) != sc->sc_iss)
51286764Sjlemon		return;
51386764Sjlemon
51486764Sjlemon	/*
51586764Sjlemon	 * If we've rertransmitted 3 times and this is our second error,
51686764Sjlemon	 * we remove the entry.  Otherwise, we allow it to continue on.
51786764Sjlemon	 * This prevents us from incorrectly nuking an entry during a
51886764Sjlemon	 * spurious network outage.
51986764Sjlemon	 *
52086764Sjlemon	 * See tcp_notify().
52186764Sjlemon	 */
52286764Sjlemon	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtslot < 3) {
52386764Sjlemon		sc->sc_flags |= SCF_UNREACH;
52486764Sjlemon		return;
52586764Sjlemon	}
52686764Sjlemon	syncache_drop(sc, sch);
52786764Sjlemon	tcpstat.tcps_sc_unreach++;
52886764Sjlemon}
52986764Sjlemon
53086764Sjlemon/*
53186764Sjlemon * Build a new TCP socket structure from a syncache entry.
53286764Sjlemon */
53386764Sjlemonstatic struct socket *
53496602Srwatsonsyncache_socket(sc, lso, m)
53586764Sjlemon	struct syncache *sc;
53686764Sjlemon	struct socket *lso;
53796602Srwatson	struct mbuf *m;
53886764Sjlemon{
53986764Sjlemon	struct inpcb *inp = NULL;
54086764Sjlemon	struct socket *so;
54186764Sjlemon	struct tcpcb *tp;
54286764Sjlemon
543122496Ssam	GIANT_REQUIRED;			/* XXX until socket locking */
544122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
545122496Ssam
54686764Sjlemon	/*
54786764Sjlemon	 * Ok, create the full blown connection, and set things up
54886764Sjlemon	 * as they would have been set up if we had created the
54986764Sjlemon	 * connection when the SYN arrived.  If we can't create
55086764Sjlemon	 * the connection, abort it.
55186764Sjlemon	 */
55286764Sjlemon	so = sonewconn(lso, SS_ISCONNECTED);
55386764Sjlemon	if (so == NULL) {
55486764Sjlemon		/*
55586764Sjlemon		 * Drop the connection; we will send a RST if the peer
55686764Sjlemon		 * retransmits the ACK,
55786764Sjlemon		 */
55886764Sjlemon		tcpstat.tcps_listendrop++;
559122496Ssam		goto abort2;
56086764Sjlemon	}
561101106Srwatson#ifdef MAC
562101106Srwatson	mac_set_socket_peer_from_mbuf(m, so);
563101106Srwatson#endif
56486764Sjlemon
56586764Sjlemon	inp = sotoinpcb(so);
566122496Ssam	INP_LOCK(inp);
56786764Sjlemon
56886764Sjlemon	/*
56986764Sjlemon	 * Insert new socket into hash list.
57086764Sjlemon	 */
57191492Sume	inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
57286764Sjlemon#ifdef INET6
57386764Sjlemon	if (sc->sc_inc.inc_isipv6) {
57486764Sjlemon		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
57586764Sjlemon	} else {
57686764Sjlemon		inp->inp_vflag &= ~INP_IPV6;
57786764Sjlemon		inp->inp_vflag |= INP_IPV4;
57886764Sjlemon#endif
57986764Sjlemon		inp->inp_laddr = sc->sc_inc.inc_laddr;
58086764Sjlemon#ifdef INET6
58186764Sjlemon	}
58286764Sjlemon#endif
58386764Sjlemon	inp->inp_lport = sc->sc_inc.inc_lport;
58486764Sjlemon	if (in_pcbinshash(inp) != 0) {
58586764Sjlemon		/*
58686764Sjlemon		 * Undo the assignments above if we failed to
58786764Sjlemon		 * put the PCB on the hash lists.
58886764Sjlemon		 */
58986764Sjlemon#ifdef INET6
59086764Sjlemon		if (sc->sc_inc.inc_isipv6)
59186764Sjlemon			inp->in6p_laddr = in6addr_any;
59286764Sjlemon       		else
59386764Sjlemon#endif
59486764Sjlemon			inp->inp_laddr.s_addr = INADDR_ANY;
59586764Sjlemon		inp->inp_lport = 0;
59686764Sjlemon		goto abort;
59786764Sjlemon	}
59886764Sjlemon#ifdef IPSEC
59986764Sjlemon	/* copy old policy into new socket's */
600122062Sume	if (ipsec_copy_pcbpolicy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
601122062Sume		printf("syncache_expand: could not copy policy\n");
602122062Sume#endif
603122062Sume#ifdef FAST_IPSEC
604122062Sume	/* copy old policy into new socket's */
60586764Sjlemon	if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
60686764Sjlemon		printf("syncache_expand: could not copy policy\n");
60786764Sjlemon#endif
60886764Sjlemon#ifdef INET6
60986764Sjlemon	if (sc->sc_inc.inc_isipv6) {
61086764Sjlemon		struct inpcb *oinp = sotoinpcb(lso);
61186764Sjlemon		struct in6_addr laddr6;
612124847Sandre		struct sockaddr_in6 sin6;
61386764Sjlemon		/*
61486764Sjlemon		 * Inherit socket options from the listening socket.
61586764Sjlemon		 * Note that in6p_inputopts are not (and should not be)
61686764Sjlemon		 * copied, since it stores previously received options and is
61786764Sjlemon		 * used to detect if each new option is different than the
61886764Sjlemon		 * previous one and hence should be passed to a user.
61986764Sjlemon                 * If we copied in6p_inputopts, a user would not be able to
62086764Sjlemon		 * receive options just after calling the accept system call.
62186764Sjlemon		 */
62286764Sjlemon		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
62386764Sjlemon		if (oinp->in6p_outputopts)
62486764Sjlemon			inp->in6p_outputopts =
62586764Sjlemon			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
62686764Sjlemon
627124847Sandre		sin6.sin6_family = AF_INET6;
628124847Sandre		sin6.sin6_len = sizeof(sin6);
629124847Sandre		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
630124847Sandre		sin6.sin6_port = sc->sc_inc.inc_fport;
631124847Sandre		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
63286764Sjlemon		laddr6 = inp->in6p_laddr;
63386764Sjlemon		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
63486764Sjlemon			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
635124847Sandre		if (in6_pcbconnect(inp, (struct sockaddr *)&sin6, &thread0)) {
63686764Sjlemon			inp->in6p_laddr = laddr6;
63786764Sjlemon			goto abort;
63886764Sjlemon		}
63986764Sjlemon	} else
64086764Sjlemon#endif
64186764Sjlemon	{
64286764Sjlemon		struct in_addr laddr;
643124847Sandre		struct sockaddr_in sin;
64486764Sjlemon
64586764Sjlemon		inp->inp_options = ip_srcroute();
64686764Sjlemon		if (inp->inp_options == NULL) {
64786764Sjlemon			inp->inp_options = sc->sc_ipopts;
64886764Sjlemon			sc->sc_ipopts = NULL;
64986764Sjlemon		}
65086764Sjlemon
651124847Sandre		sin.sin_family = AF_INET;
652124847Sandre		sin.sin_len = sizeof(sin);
653124847Sandre		sin.sin_addr = sc->sc_inc.inc_faddr;
654124847Sandre		sin.sin_port = sc->sc_inc.inc_fport;
655124847Sandre		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
65686764Sjlemon		laddr = inp->inp_laddr;
65786764Sjlemon		if (inp->inp_laddr.s_addr == INADDR_ANY)
65886764Sjlemon			inp->inp_laddr = sc->sc_inc.inc_laddr;
659124847Sandre		if (in_pcbconnect(inp, (struct sockaddr *)&sin, &thread0)) {
66086764Sjlemon			inp->inp_laddr = laddr;
66186764Sjlemon			goto abort;
66286764Sjlemon		}
66386764Sjlemon	}
66486764Sjlemon
66586764Sjlemon	tp = intotcpcb(inp);
66686764Sjlemon	tp->t_state = TCPS_SYN_RECEIVED;
66786764Sjlemon	tp->iss = sc->sc_iss;
66886764Sjlemon	tp->irs = sc->sc_irs;
66986764Sjlemon	tcp_rcvseqinit(tp);
67086764Sjlemon	tcp_sendseqinit(tp);
67186764Sjlemon	tp->snd_wl1 = sc->sc_irs;
67286764Sjlemon	tp->rcv_up = sc->sc_irs + 1;
67386764Sjlemon	tp->rcv_wnd = sc->sc_wnd;
67486764Sjlemon	tp->rcv_adv += tp->rcv_wnd;
67586764Sjlemon
67690982Sjlemon	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
67786764Sjlemon	if (sc->sc_flags & SCF_NOOPT)
67886764Sjlemon		tp->t_flags |= TF_NOOPT;
67986764Sjlemon	if (sc->sc_flags & SCF_WINSCALE) {
68086764Sjlemon		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
68186764Sjlemon		tp->requested_s_scale = sc->sc_requested_s_scale;
68286764Sjlemon		tp->request_r_scale = sc->sc_request_r_scale;
68386764Sjlemon	}
68486764Sjlemon	if (sc->sc_flags & SCF_TIMESTAMP) {
68586764Sjlemon		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
68686764Sjlemon		tp->ts_recent = sc->sc_tsrecent;
68786764Sjlemon		tp->ts_recent_age = ticks;
68886764Sjlemon	}
68986764Sjlemon	if (sc->sc_flags & SCF_CC) {
69086764Sjlemon		/*
69186764Sjlemon		 * Initialization of the tcpcb for transaction;
69286764Sjlemon		 *   set SND.WND = SEG.WND,
69386764Sjlemon		 *   initialize CCsend and CCrecv.
69486764Sjlemon		 */
69586764Sjlemon		tp->t_flags |= TF_REQ_CC|TF_RCVD_CC;
69686764Sjlemon		tp->cc_send = sc->sc_cc_send;
69786764Sjlemon		tp->cc_recv = sc->sc_cc_recv;
69886764Sjlemon	}
699125680Sbms#ifdef TCP_SIGNATURE
700125680Sbms	if (sc->sc_flags & SCF_SIGNATURE)
701125680Sbms		tp->t_flags |= TF_SIGNATURE;
702125783Sbms#endif
70386764Sjlemon
704122922Sandre	/*
705122922Sandre	 * Set up MSS and get cached values from tcp_hostcache.
706122922Sandre	 * This might overwrite some of the defaults we just set.
707122922Sandre	 */
70886764Sjlemon	tcp_mss(tp, sc->sc_peer_mss);
70986764Sjlemon
71086764Sjlemon	/*
71186764Sjlemon	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
71286764Sjlemon	 */
71386764Sjlemon	if (sc->sc_rxtslot != 0)
71486764Sjlemon                tp->snd_cwnd = tp->t_maxseg;
71586764Sjlemon	callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
71686764Sjlemon
717122496Ssam	INP_UNLOCK(inp);
718122496Ssam
71986764Sjlemon	tcpstat.tcps_accepts++;
72086764Sjlemon	return (so);
72186764Sjlemon
72286764Sjlemonabort:
723122496Ssam	INP_UNLOCK(inp);
724122496Ssamabort2:
72586764Sjlemon	if (so != NULL)
72686764Sjlemon		(void) soabort(so);
72786764Sjlemon	return (NULL);
72886764Sjlemon}
72986764Sjlemon
73086764Sjlemon/*
73186764Sjlemon * This function gets called when we receive an ACK for a
73286764Sjlemon * socket in the LISTEN state.  We look up the connection
73386764Sjlemon * in the syncache, and if its there, we pull it out of
73486764Sjlemon * the cache and turn it into a full-blown connection in
73586764Sjlemon * the SYN-RECEIVED state.
73686764Sjlemon */
73786764Sjlemonint
73886764Sjlemonsyncache_expand(inc, th, sop, m)
73986764Sjlemon	struct in_conninfo *inc;
74086764Sjlemon	struct tcphdr *th;
74186764Sjlemon	struct socket **sop;
74286764Sjlemon	struct mbuf *m;
74386764Sjlemon{
74486764Sjlemon	struct syncache *sc;
74586764Sjlemon	struct syncache_head *sch;
74686764Sjlemon	struct socket *so;
74786764Sjlemon
748122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
749122496Ssam
75086764Sjlemon	sc = syncache_lookup(inc, &sch);
75188180Sjlemon	if (sc == NULL) {
75288180Sjlemon		/*
75388180Sjlemon		 * There is no syncache entry, so see if this ACK is
75488180Sjlemon		 * a returning syncookie.  To do this, first:
75588180Sjlemon		 *  A. See if this socket has had a syncache entry dropped in
75688180Sjlemon		 *     the past.  We don't want to accept a bogus syncookie
75788180Sjlemon 		 *     if we've never received a SYN.
75888180Sjlemon		 *  B. check that the syncookie is valid.  If it is, then
75988180Sjlemon		 *     cobble up a fake syncache entry, and return.
76088180Sjlemon		 */
76188180Sjlemon		if (!tcp_syncookies)
76288180Sjlemon			return (0);
76388180Sjlemon		sc = syncookie_lookup(inc, th, *sop);
76488180Sjlemon		if (sc == NULL)
76588180Sjlemon			return (0);
76688180Sjlemon		sch = NULL;
76788180Sjlemon		tcpstat.tcps_sc_recvcookie++;
76888180Sjlemon	}
76986764Sjlemon
77086764Sjlemon	/*
77186764Sjlemon	 * If seg contains an ACK, but not for our SYN/ACK, send a RST.
77286764Sjlemon	 */
77386764Sjlemon	if (th->th_ack != sc->sc_iss + 1)
77486764Sjlemon		return (0);
77586764Sjlemon
77696602Srwatson	so = syncache_socket(sc, *sop, m);
77786764Sjlemon	if (so == NULL) {
77886764Sjlemon#if 0
77986764Sjlemonresetandabort:
78086764Sjlemon		/* XXXjlemon check this - is this correct? */
78186764Sjlemon		(void) tcp_respond(NULL, m, m, th,
78286764Sjlemon		    th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
78386764Sjlemon#endif
78486764Sjlemon		m_freem(m);			/* XXX only needed for above */
78586764Sjlemon		tcpstat.tcps_sc_aborted++;
786122922Sandre	} else
78786764Sjlemon		tcpstat.tcps_sc_completed++;
788122922Sandre
78986764Sjlemon	if (sch == NULL)
79086764Sjlemon		syncache_free(sc);
79186764Sjlemon	else
79286764Sjlemon		syncache_drop(sc, sch);
79386764Sjlemon	*sop = so;
79486764Sjlemon	return (1);
79586764Sjlemon}
79686764Sjlemon
79786764Sjlemon/*
79886764Sjlemon * Given a LISTEN socket and an inbound SYN request, add
79986764Sjlemon * this to the syn cache, and send back a segment:
80086764Sjlemon *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
80186764Sjlemon * to the source.
80286764Sjlemon *
80386764Sjlemon * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
80486764Sjlemon * Doing so would require that we hold onto the data and deliver it
80586764Sjlemon * to the application.  However, if we are the target of a SYN-flood
80686764Sjlemon * DoS attack, an attacker could send data which would eventually
80786764Sjlemon * consume all available buffer space if it were ACKed.  By not ACKing
80886764Sjlemon * the data, we avoid this DoS scenario.
80986764Sjlemon */
81086764Sjlemonint
81186764Sjlemonsyncache_add(inc, to, th, sop, m)
81286764Sjlemon	struct in_conninfo *inc;
81386764Sjlemon	struct tcpopt *to;
81486764Sjlemon	struct tcphdr *th;
81586764Sjlemon	struct socket **sop;
81686764Sjlemon	struct mbuf *m;
81786764Sjlemon{
81886764Sjlemon	struct tcpcb *tp;
81986764Sjlemon	struct socket *so;
82086764Sjlemon	struct syncache *sc = NULL;
82186764Sjlemon	struct syncache_head *sch;
82286764Sjlemon	struct mbuf *ipopts = NULL;
823122922Sandre	struct rmxp_tao tao;
824122496Ssam	int i, win;
82586764Sjlemon
826122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
827122496Ssam
82886764Sjlemon	so = *sop;
82986764Sjlemon	tp = sototcpcb(so);
830122922Sandre	bzero(&tao, sizeof(tao));
83186764Sjlemon
83286764Sjlemon	/*
83386764Sjlemon	 * Remember the IP options, if any.
83486764Sjlemon	 */
83586764Sjlemon#ifdef INET6
83686764Sjlemon	if (!inc->inc_isipv6)
83786764Sjlemon#endif
83886764Sjlemon		ipopts = ip_srcroute();
83986764Sjlemon
84086764Sjlemon	/*
84186764Sjlemon	 * See if we already have an entry for this connection.
84286764Sjlemon	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
84386764Sjlemon	 *
84486764Sjlemon	 * XXX
84586764Sjlemon	 * should the syncache be re-initialized with the contents
84686764Sjlemon	 * of the new SYN here (which may have different options?)
84786764Sjlemon	 */
84886764Sjlemon	sc = syncache_lookup(inc, &sch);
84986764Sjlemon	if (sc != NULL) {
85086764Sjlemon		tcpstat.tcps_sc_dupsyn++;
85186764Sjlemon		if (ipopts) {
85286764Sjlemon			/*
85386764Sjlemon			 * If we were remembering a previous source route,
85486764Sjlemon			 * forget it and use the new one we've been given.
85586764Sjlemon			 */
85686764Sjlemon			if (sc->sc_ipopts)
85786764Sjlemon				(void) m_free(sc->sc_ipopts);
85886764Sjlemon			sc->sc_ipopts = ipopts;
85986764Sjlemon		}
86086764Sjlemon		/*
86186764Sjlemon		 * Update timestamp if present.
86286764Sjlemon		 */
86386764Sjlemon		if (sc->sc_flags & SCF_TIMESTAMP)
86486764Sjlemon			sc->sc_tsrecent = to->to_tsval;
86590556Sjlemon		/*
86690556Sjlemon		 * PCB may have changed, pick up new values.
86790556Sjlemon		 */
86890556Sjlemon		sc->sc_tp = tp;
86990556Sjlemon		sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
870118864Sharti#ifdef TCPDEBUG
871118864Sharti		if (syncache_respond(sc, m, so) == 0) {
872118864Sharti#else
87386764Sjlemon		if (syncache_respond(sc, m) == 0) {
874118864Sharti#endif
875122496Ssam			/* NB: guarded by INP_INFO_WLOCK(&tcbinfo) */
87686764Sjlemon			TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot],
87786764Sjlemon			    sc, sc_timerq);
87886764Sjlemon			SYNCACHE_TIMEOUT(sc, sc->sc_rxtslot);
87986764Sjlemon		 	tcpstat.tcps_sndacks++;
88086764Sjlemon			tcpstat.tcps_sndtotal++;
88186764Sjlemon		}
88286764Sjlemon		*sop = NULL;
88386764Sjlemon		return (1);
88486764Sjlemon	}
88586764Sjlemon
88692760Sjeff	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
88786764Sjlemon	if (sc == NULL) {
88886764Sjlemon		/*
88986764Sjlemon		 * The zone allocator couldn't provide more entries.
89086764Sjlemon		 * Treat this as if the cache was full; drop the oldest
89186764Sjlemon		 * entry and insert the new one.
89286764Sjlemon		 */
893122496Ssam		/* NB: guarded by INP_INFO_WLOCK(&tcbinfo) */
89486764Sjlemon		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
89586764Sjlemon			sc = TAILQ_FIRST(&tcp_syncache.timerq[i]);
89686764Sjlemon			if (sc != NULL)
89786764Sjlemon				break;
89886764Sjlemon		}
89988180Sjlemon		sc->sc_tp->ts_recent = ticks;
90086764Sjlemon		syncache_drop(sc, NULL);
90186764Sjlemon		tcpstat.tcps_sc_zonefail++;
90292760Sjeff		sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
90386764Sjlemon		if (sc == NULL) {
90486764Sjlemon			if (ipopts)
90586764Sjlemon				(void) m_free(ipopts);
90686764Sjlemon			return (0);
90786764Sjlemon		}
90886764Sjlemon	}
90986764Sjlemon
91086764Sjlemon	/*
91186764Sjlemon	 * Fill in the syncache values.
91286764Sjlemon	 */
91386958Stanimura	bzero(sc, sizeof(*sc));
91486764Sjlemon	sc->sc_tp = tp;
91586764Sjlemon	sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
91686764Sjlemon	sc->sc_ipopts = ipopts;
91786764Sjlemon	sc->sc_inc.inc_fport = inc->inc_fport;
91886764Sjlemon	sc->sc_inc.inc_lport = inc->inc_lport;
91986764Sjlemon#ifdef INET6
92086764Sjlemon	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
92186764Sjlemon	if (inc->inc_isipv6) {
92286764Sjlemon		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
92386764Sjlemon		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
92486764Sjlemon	} else
92586764Sjlemon#endif
92686764Sjlemon	{
92786764Sjlemon		sc->sc_inc.inc_faddr = inc->inc_faddr;
92886764Sjlemon		sc->sc_inc.inc_laddr = inc->inc_laddr;
92986764Sjlemon	}
93086764Sjlemon	sc->sc_irs = th->th_seq;
931110023Ssilby	sc->sc_flags = 0;
932110023Ssilby	sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
93388330Sjlemon	if (tcp_syncookies)
93488330Sjlemon		sc->sc_iss = syncookie_generate(sc);
93588330Sjlemon	else
93688330Sjlemon		sc->sc_iss = arc4random();
93786764Sjlemon
93886764Sjlemon	/* Initial receive window: clip sbspace to [0 .. TCP_MAXWIN] */
93986764Sjlemon	win = sbspace(&so->so_rcv);
94086764Sjlemon	win = imax(win, 0);
94186764Sjlemon	win = imin(win, TCP_MAXWIN);
94286764Sjlemon	sc->sc_wnd = win;
94386764Sjlemon
94486764Sjlemon	if (tcp_do_rfc1323) {
94586764Sjlemon		/*
94686764Sjlemon		 * A timestamp received in a SYN makes
94786764Sjlemon		 * it ok to send timestamp requests and replies.
94886764Sjlemon		 */
94986764Sjlemon		if (to->to_flags & TOF_TS) {
95086764Sjlemon			sc->sc_tsrecent = to->to_tsval;
95186764Sjlemon			sc->sc_flags |= SCF_TIMESTAMP;
95286764Sjlemon		}
95386764Sjlemon		if (to->to_flags & TOF_SCALE) {
95486764Sjlemon			int wscale = 0;
95586764Sjlemon
95686764Sjlemon			/* Compute proper scaling value from buffer space */
95786764Sjlemon			while (wscale < TCP_MAX_WINSHIFT &&
95886764Sjlemon			    (TCP_MAXWIN << wscale) < so->so_rcv.sb_hiwat)
95986764Sjlemon				wscale++;
96086764Sjlemon			sc->sc_request_r_scale = wscale;
96186764Sjlemon			sc->sc_requested_s_scale = to->to_requested_s_scale;
96286764Sjlemon			sc->sc_flags |= SCF_WINSCALE;
96386764Sjlemon		}
96486764Sjlemon	}
96586764Sjlemon	if (tcp_do_rfc1644) {
96686764Sjlemon		/*
96786764Sjlemon		 * A CC or CC.new option received in a SYN makes
96886764Sjlemon		 * it ok to send CC in subsequent segments.
96986764Sjlemon		 */
97086764Sjlemon		if (to->to_flags & (TOF_CC|TOF_CCNEW)) {
97186764Sjlemon			sc->sc_cc_recv = to->to_cc;
97286764Sjlemon			sc->sc_cc_send = CC_INC(tcp_ccgen);
97386764Sjlemon			sc->sc_flags |= SCF_CC;
97486764Sjlemon		}
97586764Sjlemon	}
97686764Sjlemon	if (tp->t_flags & TF_NOOPT)
97786764Sjlemon		sc->sc_flags = SCF_NOOPT;
978125680Sbms#ifdef TCP_SIGNATURE
979125680Sbms	/*
980125680Sbms	 * If listening socket requested TCP digests, and received SYN
981125680Sbms	 * contains the option, flag this in the syncache so that
982125680Sbms	 * syncache_respond() will do the right thing with the SYN+ACK.
983125680Sbms	 * XXX Currently we always record the option by default and will
984125680Sbms	 * attempt to use it in syncache_respond().
985125680Sbms	 */
986125680Sbms	if (to->to_flags & TOF_SIGNATURE)
987125680Sbms		sc->sc_flags = SCF_SIGNATURE;
988125783Sbms#endif
98986764Sjlemon
99086764Sjlemon	/*
99186764Sjlemon	 * XXX
99286764Sjlemon	 * We have the option here of not doing TAO (even if the segment
99386764Sjlemon	 * qualifies) and instead fall back to a normal 3WHS via the syncache.
99486764Sjlemon	 * This allows us to apply synflood protection to TAO-qualifying SYNs
99586764Sjlemon	 * also. However, there should be a hueristic to determine when to
99686764Sjlemon	 * do this, and is not present at the moment.
99786764Sjlemon	 */
99886764Sjlemon
99986764Sjlemon	/*
100086764Sjlemon	 * Perform TAO test on incoming CC (SEG.CC) option, if any.
100186764Sjlemon	 * - compare SEG.CC against cached CC from the same host, if any.
100286764Sjlemon	 * - if SEG.CC > chached value, SYN must be new and is accepted
100386764Sjlemon	 *	immediately: save new CC in the cache, mark the socket
100486764Sjlemon	 *	connected, enter ESTABLISHED state, turn on flag to
100586764Sjlemon	 *	send a SYN in the next segment.
100686764Sjlemon	 *	A virtual advertised window is set in rcv_adv to
100786764Sjlemon	 *	initialize SWS prevention.  Then enter normal segment
100886764Sjlemon	 *	processing: drop SYN, process data and FIN.
100986764Sjlemon	 * - otherwise do a normal 3-way handshake.
101086764Sjlemon	 */
1011122922Sandre	if (tcp_do_rfc1644)
1012122922Sandre		tcp_hc_gettao(&sc->sc_inc, &tao);
1013122922Sandre
101486764Sjlemon	if ((to->to_flags & TOF_CC) != 0) {
101586764Sjlemon		if (((tp->t_flags & TF_NOPUSH) != 0) &&
1016122922Sandre		    sc->sc_flags & SCF_CC && tao.tao_cc != 0 &&
1017122922Sandre		    CC_GT(to->to_cc, tao.tao_cc)) {
101886764Sjlemon			sc->sc_rxtslot = 0;
101996602Srwatson			so = syncache_socket(sc, *sop, m);
102086764Sjlemon			if (so != NULL) {
1021122922Sandre				tao.tao_cc = to->to_cc;
1022122922Sandre				tcp_hc_updatetao(&sc->sc_inc, TCP_HC_TAO_CC,
1023122922Sandre						 tao.tao_cc, 0);
102486764Sjlemon				*sop = so;
102586764Sjlemon			}
102686764Sjlemon			syncache_free(sc);
102786764Sjlemon			return (so != NULL);
102886764Sjlemon		}
102986764Sjlemon	} else {
103086764Sjlemon		/*
103186764Sjlemon		 * No CC option, but maybe CC.NEW: invalidate cached value.
103286764Sjlemon		 */
1033122922Sandre		if (tcp_do_rfc1644) {
1034122922Sandre			tao.tao_cc = 0;
1035122922Sandre			tcp_hc_updatetao(&sc->sc_inc, TCP_HC_TAO_CC,
1036122922Sandre					 tao.tao_cc, 0);
1037122922Sandre		}
103886764Sjlemon	}
1039122922Sandre
104086764Sjlemon	/*
104186764Sjlemon	 * TAO test failed or there was no CC option,
104286764Sjlemon	 *    do a standard 3-way handshake.
104386764Sjlemon	 */
1044118864Sharti#ifdef TCPDEBUG
1045118864Sharti	if (syncache_respond(sc, m, so) == 0) {
1046118864Sharti#else
104788180Sjlemon	if (syncache_respond(sc, m) == 0) {
1048118864Sharti#endif
104988180Sjlemon		syncache_insert(sc, sch);
105088180Sjlemon		tcpstat.tcps_sndacks++;
105188180Sjlemon		tcpstat.tcps_sndtotal++;
105286764Sjlemon	} else {
105386764Sjlemon		syncache_free(sc);
105488180Sjlemon		tcpstat.tcps_sc_dropped++;
105586764Sjlemon	}
105686764Sjlemon	*sop = NULL;
105786764Sjlemon	return (1);
105886764Sjlemon}
105986764Sjlemon
1060118864Sharti#ifdef TCPDEBUG
106186764Sjlemonstatic int
1062118864Shartisyncache_respond(sc, m, so)
1063118864Sharti	struct syncache *sc;
1064118864Sharti	struct mbuf *m;
1065118864Sharti	struct socket *so;
1066118864Sharti#else
1067118864Shartistatic int
106886764Sjlemonsyncache_respond(sc, m)
106986764Sjlemon	struct syncache *sc;
107086764Sjlemon	struct mbuf *m;
1071118864Sharti#endif
107286764Sjlemon{
107386764Sjlemon	u_int8_t *optp;
107486764Sjlemon	int optlen, error;
107586764Sjlemon	u_int16_t tlen, hlen, mssopt;
107686764Sjlemon	struct ip *ip = NULL;
107786764Sjlemon	struct tcphdr *th;
1078122496Ssam	struct inpcb *inp;
107986764Sjlemon#ifdef INET6
108086764Sjlemon	struct ip6_hdr *ip6 = NULL;
108186764Sjlemon#endif
108286764Sjlemon
1083122922Sandre	hlen =
108486764Sjlemon#ifdef INET6
1085122922Sandre	       (sc->sc_inc.inc_isipv6) ? sizeof(struct ip6_hdr) :
108686764Sjlemon#endif
1087122922Sandre		sizeof(struct ip);
108886764Sjlemon
1089122922Sandre	KASSERT((&sc->sc_inc) != NULL, ("syncache_respond with NULL in_conninfo pointer"));
1090122922Sandre
1091122922Sandre	/* Determine MSS we advertize to other end of connection */
1092122922Sandre	mssopt = tcp_mssopt(&sc->sc_inc);
1093122922Sandre
109486764Sjlemon	/* Compute the size of the TCP options. */
109586764Sjlemon	if (sc->sc_flags & SCF_NOOPT) {
109686764Sjlemon		optlen = 0;
109786764Sjlemon	} else {
109886764Sjlemon		optlen = TCPOLEN_MAXSEG +
109986764Sjlemon		    ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
110086764Sjlemon		    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0) +
110186764Sjlemon		    ((sc->sc_flags & SCF_CC) ? TCPOLEN_CC_APPA * 2 : 0);
1102125680Sbms#ifdef TCP_SIGNATURE
1103125783Sbms		optlen += (sc->sc_flags & SCF_SIGNATURE) ?
1104125819Sbms		    TCPOLEN_SIGNATURE + 2 : 0;
1105125783Sbms#endif
110686764Sjlemon	}
110786764Sjlemon	tlen = hlen + sizeof(struct tcphdr) + optlen;
110886764Sjlemon
110986764Sjlemon	/*
111086764Sjlemon	 * XXX
111186764Sjlemon	 * assume that the entire packet will fit in a header mbuf
111286764Sjlemon	 */
111386764Sjlemon	KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
111486764Sjlemon
111586764Sjlemon	/*
111686764Sjlemon	 * XXX shouldn't this reuse the mbuf if possible ?
111786764Sjlemon	 * Create the IP+TCP header from scratch.
111886764Sjlemon	 */
111986764Sjlemon	if (m)
112086764Sjlemon		m_freem(m);
112186764Sjlemon
1122111119Simp	m = m_gethdr(M_DONTWAIT, MT_HEADER);
112386764Sjlemon	if (m == NULL)
112486764Sjlemon		return (ENOBUFS);
112586764Sjlemon	m->m_data += max_linkhdr;
112686764Sjlemon	m->m_len = tlen;
112786764Sjlemon	m->m_pkthdr.len = tlen;
112886764Sjlemon	m->m_pkthdr.rcvif = NULL;
1129122496Ssam	inp = sc->sc_tp->t_inpcb;
1130122496Ssam	INP_LOCK(inp);
1131101106Srwatson#ifdef MAC
1132122496Ssam	mac_create_mbuf_from_socket(inp->inp_socket, m);
1133101106Srwatson#endif
113486764Sjlemon
113586764Sjlemon#ifdef INET6
113686764Sjlemon	if (sc->sc_inc.inc_isipv6) {
113786764Sjlemon		ip6 = mtod(m, struct ip6_hdr *);
113886764Sjlemon		ip6->ip6_vfc = IPV6_VERSION;
113986764Sjlemon		ip6->ip6_nxt = IPPROTO_TCP;
114086764Sjlemon		ip6->ip6_src = sc->sc_inc.inc6_laddr;
114186764Sjlemon		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
114286764Sjlemon		ip6->ip6_plen = htons(tlen - hlen);
114386764Sjlemon		/* ip6_hlim is set after checksum */
114486764Sjlemon		/* ip6_flow = ??? */
114586764Sjlemon
114686764Sjlemon		th = (struct tcphdr *)(ip6 + 1);
114786764Sjlemon	} else
114886764Sjlemon#endif
114986764Sjlemon	{
115086764Sjlemon		ip = mtod(m, struct ip *);
115186764Sjlemon		ip->ip_v = IPVERSION;
115286764Sjlemon		ip->ip_hl = sizeof(struct ip) >> 2;
115386764Sjlemon		ip->ip_len = tlen;
115486764Sjlemon		ip->ip_id = 0;
115586764Sjlemon		ip->ip_off = 0;
115686764Sjlemon		ip->ip_sum = 0;
115786764Sjlemon		ip->ip_p = IPPROTO_TCP;
115886764Sjlemon		ip->ip_src = sc->sc_inc.inc_laddr;
115986764Sjlemon		ip->ip_dst = sc->sc_inc.inc_faddr;
1160122496Ssam		ip->ip_ttl = inp->inp_ip_ttl;   /* XXX */
1161122496Ssam		ip->ip_tos = inp->inp_ip_tos;   /* XXX */
116286764Sjlemon
116398204Ssilby		/*
1164108125Shsu		 * See if we should do MTU discovery.  Route lookups are
1165108125Shsu		 * expensive, so we will only unset the DF bit if:
1166101405Ssilby		 *
1167101405Ssilby		 *	1) path_mtu_discovery is disabled
1168101405Ssilby		 *	2) the SCF_UNREACH flag has been set
116998204Ssilby		 */
1170108125Shsu		if (path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
117198204Ssilby		       ip->ip_off |= IP_DF;
117298204Ssilby
117386764Sjlemon		th = (struct tcphdr *)(ip + 1);
117486764Sjlemon	}
117586764Sjlemon	th->th_sport = sc->sc_inc.inc_lport;
117686764Sjlemon	th->th_dport = sc->sc_inc.inc_fport;
117786764Sjlemon
117886764Sjlemon	th->th_seq = htonl(sc->sc_iss);
117986764Sjlemon	th->th_ack = htonl(sc->sc_irs + 1);
118086764Sjlemon	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
118186764Sjlemon	th->th_x2 = 0;
118286764Sjlemon	th->th_flags = TH_SYN|TH_ACK;
118386764Sjlemon	th->th_win = htons(sc->sc_wnd);
118486764Sjlemon	th->th_urp = 0;
118586764Sjlemon
118686764Sjlemon	/* Tack on the TCP options. */
1187108125Shsu	if (optlen != 0) {
1188108125Shsu		optp = (u_int8_t *)(th + 1);
1189108125Shsu		*optp++ = TCPOPT_MAXSEG;
1190108125Shsu		*optp++ = TCPOLEN_MAXSEG;
1191108125Shsu		*optp++ = (mssopt >> 8) & 0xff;
1192108125Shsu		*optp++ = mssopt & 0xff;
119386764Sjlemon
1194108125Shsu		if (sc->sc_flags & SCF_WINSCALE) {
1195108125Shsu			*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1196108125Shsu			    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1197108125Shsu			    sc->sc_request_r_scale);
1198108125Shsu			optp += 4;
1199108125Shsu		}
120086764Sjlemon
1201108125Shsu		if (sc->sc_flags & SCF_TIMESTAMP) {
1202108125Shsu			u_int32_t *lp = (u_int32_t *)(optp);
120386764Sjlemon
1204108125Shsu			/* Form timestamp option per appendix A of RFC 1323. */
1205108125Shsu			*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1206108125Shsu			*lp++ = htonl(ticks);
1207108125Shsu			*lp   = htonl(sc->sc_tsrecent);
1208108125Shsu			optp += TCPOLEN_TSTAMP_APPA;
1209108125Shsu		}
121086764Sjlemon
1211108125Shsu		/*
1212108125Shsu		 * Send CC and CC.echo if we received CC from our peer.
1213108125Shsu		 */
1214108125Shsu		if (sc->sc_flags & SCF_CC) {
1215108125Shsu			u_int32_t *lp = (u_int32_t *)(optp);
121686764Sjlemon
1217108125Shsu			*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
1218108125Shsu			*lp++ = htonl(sc->sc_cc_send);
1219108125Shsu			*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CCECHO));
1220108125Shsu			*lp   = htonl(sc->sc_cc_recv);
1221108125Shsu			optp += TCPOLEN_CC_APPA * 2;
1222108125Shsu		}
1223125680Sbms
1224125680Sbms#ifdef TCP_SIGNATURE
1225125680Sbms		/*
1226125680Sbms		 * Handle TCP-MD5 passive opener response.
1227125680Sbms		 */
1228125680Sbms		if (sc->sc_flags & SCF_SIGNATURE) {
1229125680Sbms			u_int8_t *bp = optp;
1230125680Sbms			int i;
1231125680Sbms
1232125680Sbms			*bp++ = TCPOPT_SIGNATURE;
1233125680Sbms			*bp++ = TCPOLEN_SIGNATURE;
1234125680Sbms			for (i = 0; i < TCP_SIGLEN; i++)
1235125680Sbms				*bp++ = 0;
1236125783Sbms			tcp_signature_compute(m, sizeof(struct ip), 0, optlen,
1237125680Sbms			    optp + 2, IPSEC_DIR_OUTBOUND);
1238125680Sbms			*bp++ = TCPOPT_NOP;
1239125680Sbms			*bp++ = TCPOPT_EOL;
1240125680Sbms			optp += TCPOLEN_SIGNATURE + 2;
1241125680Sbms		}
1242125680Sbms#endif /* TCP_SIGNATURE */
124386764Sjlemon	}
124486764Sjlemon
124586764Sjlemon#ifdef INET6
124686764Sjlemon	if (sc->sc_inc.inc_isipv6) {
124786764Sjlemon		th->th_sum = 0;
124886764Sjlemon		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1249122922Sandre		ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
1250122922Sandre		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
125186764Sjlemon	} else
125286764Sjlemon#endif
125386764Sjlemon	{
125486764Sjlemon        	th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
125586764Sjlemon		    htons(tlen - hlen + IPPROTO_TCP));
125686764Sjlemon		m->m_pkthdr.csum_flags = CSUM_TCP;
125786764Sjlemon		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1258118864Sharti#ifdef TCPDEBUG
1259118864Sharti		/*
1260118864Sharti		 * Trace.
1261118864Sharti		 */
1262118864Sharti		if (so != NULL && so->so_options & SO_DEBUG) {
1263118864Sharti			struct tcpcb *tp = sototcpcb(so);
1264118864Sharti			tcp_trace(TA_OUTPUT, tp->t_state, tp,
1265118864Sharti			    mtod(m, void *), th, 0);
1266118864Sharti		}
1267118864Sharti#endif
1268122922Sandre		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, inp);
126986764Sjlemon	}
1270122496Ssam	INP_UNLOCK(inp);
127186764Sjlemon	return (error);
127286764Sjlemon}
127388180Sjlemon
127488180Sjlemon/*
127588180Sjlemon * cookie layers:
127688180Sjlemon *
127788180Sjlemon *	|. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
127888180Sjlemon *	| peer iss                                                      |
1279111405Ssilby *	| MD5(laddr,faddr,secret,lport,fport)             |. . . . . . .|
128088180Sjlemon *	|                     0                       |(A)|             |
128188180Sjlemon * (A): peer mss index
128288180Sjlemon */
128388180Sjlemon
128488180Sjlemon/*
128588180Sjlemon * The values below are chosen to minimize the size of the tcp_secret
1286111338Ssilby * table, as well as providing roughly a 16 second lifetime for the cookie.
128788180Sjlemon */
128888180Sjlemon
1289111338Ssilby#define SYNCOOKIE_WNDBITS	5	/* exposed bits for window indexing */
1290111338Ssilby#define SYNCOOKIE_TIMESHIFT	1	/* scale ticks to window time units */
129188180Sjlemon
129288180Sjlemon#define SYNCOOKIE_WNDMASK	((1 << SYNCOOKIE_WNDBITS) - 1)
1293111338Ssilby#define SYNCOOKIE_NSECRETS	(1 << SYNCOOKIE_WNDBITS)
129488180Sjlemon#define SYNCOOKIE_TIMEOUT \
129588180Sjlemon    (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
129688180Sjlemon#define SYNCOOKIE_DATAMASK 	((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
129788180Sjlemon
129888180Sjlemonstatic struct {
1299111338Ssilby	u_int32_t	ts_secbits[4];
130088180Sjlemon	u_int		ts_expire;
130188180Sjlemon} tcp_secret[SYNCOOKIE_NSECRETS];
130288180Sjlemon
130388180Sjlemonstatic int tcp_msstab[] = { 0, 536, 1460, 8960 };
130488180Sjlemon
130588180Sjlemonstatic MD5_CTX syn_ctx;
130688180Sjlemon
130788180Sjlemon#define MD5Add(v)	MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
130888180Sjlemon
1309111338Ssilbystruct md5_add {
1310111338Ssilby	u_int32_t laddr, faddr;
1311111338Ssilby	u_int32_t secbits[4];
1312111338Ssilby	u_int16_t lport, fport;
1313111338Ssilby};
1314111338Ssilby
1315111338Ssilby#ifdef CTASSERT
1316111338SsilbyCTASSERT(sizeof(struct md5_add) == 28);
1317111338Ssilby#endif
1318111338Ssilby
131988180Sjlemon/*
132088180Sjlemon * Consider the problem of a recreated (and retransmitted) cookie.  If the
132188180Sjlemon * original SYN was accepted, the connection is established.  The second
132288180Sjlemon * SYN is inflight, and if it arrives with an ISN that falls within the
132388180Sjlemon * receive window, the connection is killed.
132488180Sjlemon *
132588180Sjlemon * However, since cookies have other problems, this may not be worth
132688180Sjlemon * worrying about.
132788180Sjlemon */
132888180Sjlemon
132988180Sjlemonstatic u_int32_t
133088180Sjlemonsyncookie_generate(struct syncache *sc)
133188180Sjlemon{
133288180Sjlemon	u_int32_t md5_buffer[4];
133388180Sjlemon	u_int32_t data;
1334111338Ssilby	int idx, i;
1335111338Ssilby	struct md5_add add;
133688180Sjlemon
1337122496Ssam	/* NB: single threaded; could add INP_INFO_WLOCK_ASSERT(&tcbinfo) */
1338122496Ssam
1339111338Ssilby	idx = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
134088180Sjlemon	if (tcp_secret[idx].ts_expire < ticks) {
1341111338Ssilby		for (i = 0; i < 4; i++)
1342111338Ssilby			tcp_secret[idx].ts_secbits[i] = arc4random();
134388180Sjlemon		tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
134488180Sjlemon	}
134588180Sjlemon	for (data = sizeof(tcp_msstab) / sizeof(int) - 1; data > 0; data--)
134688180Sjlemon		if (tcp_msstab[data] <= sc->sc_peer_mss)
134788180Sjlemon			break;
1348111338Ssilby	data = (data << SYNCOOKIE_WNDBITS) | idx;
134988180Sjlemon	data ^= sc->sc_irs;				/* peer's iss */
135088180Sjlemon	MD5Init(&syn_ctx);
135188180Sjlemon#ifdef INET6
135288180Sjlemon	if (sc->sc_inc.inc_isipv6) {
135388180Sjlemon		MD5Add(sc->sc_inc.inc6_laddr);
135488180Sjlemon		MD5Add(sc->sc_inc.inc6_faddr);
1355111338Ssilby		add.laddr = 0;
1356111338Ssilby		add.faddr = 0;
135788180Sjlemon	} else
135888180Sjlemon#endif
135988180Sjlemon	{
1360111338Ssilby		add.laddr = sc->sc_inc.inc_laddr.s_addr;
1361111338Ssilby		add.faddr = sc->sc_inc.inc_faddr.s_addr;
136288180Sjlemon	}
1363111338Ssilby	add.lport = sc->sc_inc.inc_lport;
1364111338Ssilby	add.fport = sc->sc_inc.inc_fport;
1365111338Ssilby	add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1366111338Ssilby	add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1367111338Ssilby	add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1368111338Ssilby	add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1369111338Ssilby	MD5Add(add);
137088180Sjlemon	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1371111338Ssilby	data ^= (md5_buffer[0] & ~SYNCOOKIE_WNDMASK);
137288180Sjlemon	return (data);
137388180Sjlemon}
137488180Sjlemon
137588180Sjlemonstatic struct syncache *
137688180Sjlemonsyncookie_lookup(inc, th, so)
137788180Sjlemon	struct in_conninfo *inc;
137888180Sjlemon	struct tcphdr *th;
137988180Sjlemon	struct socket *so;
138088180Sjlemon{
138188180Sjlemon	u_int32_t md5_buffer[4];
138288180Sjlemon	struct syncache *sc;
138388180Sjlemon	u_int32_t data;
138488180Sjlemon	int wnd, idx;
1385111338Ssilby	struct md5_add add;
138688180Sjlemon
1387122496Ssam	/* NB: single threaded; could add INP_INFO_WLOCK_ASSERT(&tcbinfo) */
1388122496Ssam
138988180Sjlemon	data = (th->th_ack - 1) ^ (th->th_seq - 1);	/* remove ISS */
1390111338Ssilby	idx = data & SYNCOOKIE_WNDMASK;
139188180Sjlemon	if (tcp_secret[idx].ts_expire < ticks ||
139288180Sjlemon	    sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
139388180Sjlemon		return (NULL);
139488180Sjlemon	MD5Init(&syn_ctx);
139588180Sjlemon#ifdef INET6
139688180Sjlemon	if (inc->inc_isipv6) {
139788180Sjlemon		MD5Add(inc->inc6_laddr);
139888180Sjlemon		MD5Add(inc->inc6_faddr);
1399111338Ssilby		add.laddr = 0;
1400111338Ssilby		add.faddr = 0;
140188180Sjlemon	} else
140288180Sjlemon#endif
140388180Sjlemon	{
1404111338Ssilby		add.laddr = inc->inc_laddr.s_addr;
1405111338Ssilby		add.faddr = inc->inc_faddr.s_addr;
140688180Sjlemon	}
1407111338Ssilby	add.lport = inc->inc_lport;
1408111338Ssilby	add.fport = inc->inc_fport;
1409111338Ssilby	add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1410111338Ssilby	add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1411111338Ssilby	add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1412111338Ssilby	add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1413111338Ssilby	MD5Add(add);
141488180Sjlemon	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1415111338Ssilby	data ^= md5_buffer[0];
141688180Sjlemon	if ((data & ~SYNCOOKIE_DATAMASK) != 0)
141788180Sjlemon		return (NULL);
141888180Sjlemon	data = data >> SYNCOOKIE_WNDBITS;
141988180Sjlemon
142092760Sjeff	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
142188180Sjlemon	if (sc == NULL)
142288180Sjlemon		return (NULL);
142388180Sjlemon	/*
142488180Sjlemon	 * Fill in the syncache values.
142588180Sjlemon	 * XXX duplicate code from syncache_add
142688180Sjlemon	 */
142788180Sjlemon	sc->sc_ipopts = NULL;
142888180Sjlemon	sc->sc_inc.inc_fport = inc->inc_fport;
142988180Sjlemon	sc->sc_inc.inc_lport = inc->inc_lport;
143088180Sjlemon#ifdef INET6
143188180Sjlemon	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
143288180Sjlemon	if (inc->inc_isipv6) {
143388180Sjlemon		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
143488180Sjlemon		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
143588180Sjlemon	} else
143688180Sjlemon#endif
143788180Sjlemon	{
143888180Sjlemon		sc->sc_inc.inc_faddr = inc->inc_faddr;
143988180Sjlemon		sc->sc_inc.inc_laddr = inc->inc_laddr;
144088180Sjlemon	}
144188180Sjlemon	sc->sc_irs = th->th_seq - 1;
144288180Sjlemon	sc->sc_iss = th->th_ack - 1;
144388180Sjlemon	wnd = sbspace(&so->so_rcv);
144488180Sjlemon	wnd = imax(wnd, 0);
144588180Sjlemon	wnd = imin(wnd, TCP_MAXWIN);
144688180Sjlemon	sc->sc_wnd = wnd;
144788180Sjlemon	sc->sc_flags = 0;
144888180Sjlemon	sc->sc_rxtslot = 0;
144988180Sjlemon	sc->sc_peer_mss = tcp_msstab[data];
145088180Sjlemon	return (sc);
145188180Sjlemon}
1452