tcp_syncache.c revision 130555
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 130555 2004-06-16 03:36:06Z rwatson $
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
543130555Srwatson	NET_ASSERT_GIANT();
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
562130398Srwatson	SOCK_LOCK(so);
563101106Srwatson	mac_set_socket_peer_from_mbuf(m, so);
564130398Srwatson	SOCK_UNLOCK(so);
565101106Srwatson#endif
56686764Sjlemon
56786764Sjlemon	inp = sotoinpcb(so);
568122496Ssam	INP_LOCK(inp);
56986764Sjlemon
57086764Sjlemon	/*
57186764Sjlemon	 * Insert new socket into hash list.
57286764Sjlemon	 */
57391492Sume	inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
57486764Sjlemon#ifdef INET6
57586764Sjlemon	if (sc->sc_inc.inc_isipv6) {
57686764Sjlemon		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
57786764Sjlemon	} else {
57886764Sjlemon		inp->inp_vflag &= ~INP_IPV6;
57986764Sjlemon		inp->inp_vflag |= INP_IPV4;
58086764Sjlemon#endif
58186764Sjlemon		inp->inp_laddr = sc->sc_inc.inc_laddr;
58286764Sjlemon#ifdef INET6
58386764Sjlemon	}
58486764Sjlemon#endif
58586764Sjlemon	inp->inp_lport = sc->sc_inc.inc_lport;
58686764Sjlemon	if (in_pcbinshash(inp) != 0) {
58786764Sjlemon		/*
58886764Sjlemon		 * Undo the assignments above if we failed to
58986764Sjlemon		 * put the PCB on the hash lists.
59086764Sjlemon		 */
59186764Sjlemon#ifdef INET6
59286764Sjlemon		if (sc->sc_inc.inc_isipv6)
59386764Sjlemon			inp->in6p_laddr = in6addr_any;
59486764Sjlemon       		else
59586764Sjlemon#endif
59686764Sjlemon			inp->inp_laddr.s_addr = INADDR_ANY;
59786764Sjlemon		inp->inp_lport = 0;
59886764Sjlemon		goto abort;
59986764Sjlemon	}
60086764Sjlemon#ifdef IPSEC
60186764Sjlemon	/* copy old policy into new socket's */
602122062Sume	if (ipsec_copy_pcbpolicy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
603122062Sume		printf("syncache_expand: could not copy policy\n");
604122062Sume#endif
605122062Sume#ifdef FAST_IPSEC
606122062Sume	/* copy old policy into new socket's */
60786764Sjlemon	if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
60886764Sjlemon		printf("syncache_expand: could not copy policy\n");
60986764Sjlemon#endif
61086764Sjlemon#ifdef INET6
61186764Sjlemon	if (sc->sc_inc.inc_isipv6) {
61286764Sjlemon		struct inpcb *oinp = sotoinpcb(lso);
61386764Sjlemon		struct in6_addr laddr6;
614124847Sandre		struct sockaddr_in6 sin6;
61586764Sjlemon		/*
61686764Sjlemon		 * Inherit socket options from the listening socket.
61786764Sjlemon		 * Note that in6p_inputopts are not (and should not be)
61886764Sjlemon		 * copied, since it stores previously received options and is
61986764Sjlemon		 * used to detect if each new option is different than the
62086764Sjlemon		 * previous one and hence should be passed to a user.
62186764Sjlemon                 * If we copied in6p_inputopts, a user would not be able to
62286764Sjlemon		 * receive options just after calling the accept system call.
62386764Sjlemon		 */
62486764Sjlemon		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
62586764Sjlemon		if (oinp->in6p_outputopts)
62686764Sjlemon			inp->in6p_outputopts =
62786764Sjlemon			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
62886764Sjlemon
629124847Sandre		sin6.sin6_family = AF_INET6;
630124847Sandre		sin6.sin6_len = sizeof(sin6);
631124847Sandre		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
632124847Sandre		sin6.sin6_port = sc->sc_inc.inc_fport;
633124847Sandre		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
63486764Sjlemon		laddr6 = inp->in6p_laddr;
63586764Sjlemon		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
63686764Sjlemon			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
637127505Spjd		if (in6_pcbconnect(inp, (struct sockaddr *)&sin6,
638127505Spjd		    thread0.td_ucred)) {
63986764Sjlemon			inp->in6p_laddr = laddr6;
64086764Sjlemon			goto abort;
64186764Sjlemon		}
64286764Sjlemon	} else
64386764Sjlemon#endif
64486764Sjlemon	{
64586764Sjlemon		struct in_addr laddr;
646124847Sandre		struct sockaddr_in sin;
64786764Sjlemon
64886764Sjlemon		inp->inp_options = ip_srcroute();
64986764Sjlemon		if (inp->inp_options == NULL) {
65086764Sjlemon			inp->inp_options = sc->sc_ipopts;
65186764Sjlemon			sc->sc_ipopts = NULL;
65286764Sjlemon		}
65386764Sjlemon
654124847Sandre		sin.sin_family = AF_INET;
655124847Sandre		sin.sin_len = sizeof(sin);
656124847Sandre		sin.sin_addr = sc->sc_inc.inc_faddr;
657124847Sandre		sin.sin_port = sc->sc_inc.inc_fport;
658124847Sandre		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
65986764Sjlemon		laddr = inp->inp_laddr;
66086764Sjlemon		if (inp->inp_laddr.s_addr == INADDR_ANY)
66186764Sjlemon			inp->inp_laddr = sc->sc_inc.inc_laddr;
662127505Spjd		if (in_pcbconnect(inp, (struct sockaddr *)&sin,
663127505Spjd		    thread0.td_ucred)) {
66486764Sjlemon			inp->inp_laddr = laddr;
66586764Sjlemon			goto abort;
66686764Sjlemon		}
66786764Sjlemon	}
66886764Sjlemon
66986764Sjlemon	tp = intotcpcb(inp);
67086764Sjlemon	tp->t_state = TCPS_SYN_RECEIVED;
67186764Sjlemon	tp->iss = sc->sc_iss;
67286764Sjlemon	tp->irs = sc->sc_irs;
67386764Sjlemon	tcp_rcvseqinit(tp);
67486764Sjlemon	tcp_sendseqinit(tp);
67586764Sjlemon	tp->snd_wl1 = sc->sc_irs;
67686764Sjlemon	tp->rcv_up = sc->sc_irs + 1;
67786764Sjlemon	tp->rcv_wnd = sc->sc_wnd;
67886764Sjlemon	tp->rcv_adv += tp->rcv_wnd;
67986764Sjlemon
68090982Sjlemon	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
68186764Sjlemon	if (sc->sc_flags & SCF_NOOPT)
68286764Sjlemon		tp->t_flags |= TF_NOOPT;
68386764Sjlemon	if (sc->sc_flags & SCF_WINSCALE) {
68486764Sjlemon		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
68586764Sjlemon		tp->requested_s_scale = sc->sc_requested_s_scale;
68686764Sjlemon		tp->request_r_scale = sc->sc_request_r_scale;
68786764Sjlemon	}
68886764Sjlemon	if (sc->sc_flags & SCF_TIMESTAMP) {
68986764Sjlemon		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
69086764Sjlemon		tp->ts_recent = sc->sc_tsrecent;
69186764Sjlemon		tp->ts_recent_age = ticks;
69286764Sjlemon	}
69386764Sjlemon	if (sc->sc_flags & SCF_CC) {
69486764Sjlemon		/*
69586764Sjlemon		 * Initialization of the tcpcb for transaction;
69686764Sjlemon		 *   set SND.WND = SEG.WND,
69786764Sjlemon		 *   initialize CCsend and CCrecv.
69886764Sjlemon		 */
69986764Sjlemon		tp->t_flags |= TF_REQ_CC|TF_RCVD_CC;
70086764Sjlemon		tp->cc_send = sc->sc_cc_send;
70186764Sjlemon		tp->cc_recv = sc->sc_cc_recv;
70286764Sjlemon	}
703125680Sbms#ifdef TCP_SIGNATURE
704125680Sbms	if (sc->sc_flags & SCF_SIGNATURE)
705125680Sbms		tp->t_flags |= TF_SIGNATURE;
706125783Sbms#endif
70786764Sjlemon
708122922Sandre	/*
709122922Sandre	 * Set up MSS and get cached values from tcp_hostcache.
710122922Sandre	 * This might overwrite some of the defaults we just set.
711122922Sandre	 */
71286764Sjlemon	tcp_mss(tp, sc->sc_peer_mss);
71386764Sjlemon
71486764Sjlemon	/*
71586764Sjlemon	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
71686764Sjlemon	 */
71786764Sjlemon	if (sc->sc_rxtslot != 0)
71886764Sjlemon                tp->snd_cwnd = tp->t_maxseg;
71986764Sjlemon	callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
72086764Sjlemon
721122496Ssam	INP_UNLOCK(inp);
722122496Ssam
72386764Sjlemon	tcpstat.tcps_accepts++;
72486764Sjlemon	return (so);
72586764Sjlemon
72686764Sjlemonabort:
727122496Ssam	INP_UNLOCK(inp);
728122496Ssamabort2:
72986764Sjlemon	if (so != NULL)
73086764Sjlemon		(void) soabort(so);
73186764Sjlemon	return (NULL);
73286764Sjlemon}
73386764Sjlemon
73486764Sjlemon/*
73586764Sjlemon * This function gets called when we receive an ACK for a
73686764Sjlemon * socket in the LISTEN state.  We look up the connection
73786764Sjlemon * in the syncache, and if its there, we pull it out of
73886764Sjlemon * the cache and turn it into a full-blown connection in
73986764Sjlemon * the SYN-RECEIVED state.
74086764Sjlemon */
74186764Sjlemonint
74286764Sjlemonsyncache_expand(inc, th, sop, m)
74386764Sjlemon	struct in_conninfo *inc;
74486764Sjlemon	struct tcphdr *th;
74586764Sjlemon	struct socket **sop;
74686764Sjlemon	struct mbuf *m;
74786764Sjlemon{
74886764Sjlemon	struct syncache *sc;
74986764Sjlemon	struct syncache_head *sch;
75086764Sjlemon	struct socket *so;
75186764Sjlemon
752122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
753122496Ssam
75486764Sjlemon	sc = syncache_lookup(inc, &sch);
75588180Sjlemon	if (sc == NULL) {
75688180Sjlemon		/*
75788180Sjlemon		 * There is no syncache entry, so see if this ACK is
75888180Sjlemon		 * a returning syncookie.  To do this, first:
75988180Sjlemon		 *  A. See if this socket has had a syncache entry dropped in
76088180Sjlemon		 *     the past.  We don't want to accept a bogus syncookie
76188180Sjlemon 		 *     if we've never received a SYN.
76288180Sjlemon		 *  B. check that the syncookie is valid.  If it is, then
76388180Sjlemon		 *     cobble up a fake syncache entry, and return.
76488180Sjlemon		 */
76588180Sjlemon		if (!tcp_syncookies)
76688180Sjlemon			return (0);
76788180Sjlemon		sc = syncookie_lookup(inc, th, *sop);
76888180Sjlemon		if (sc == NULL)
76988180Sjlemon			return (0);
77088180Sjlemon		sch = NULL;
77188180Sjlemon		tcpstat.tcps_sc_recvcookie++;
77288180Sjlemon	}
77386764Sjlemon
77486764Sjlemon	/*
77586764Sjlemon	 * If seg contains an ACK, but not for our SYN/ACK, send a RST.
77686764Sjlemon	 */
77786764Sjlemon	if (th->th_ack != sc->sc_iss + 1)
77886764Sjlemon		return (0);
77986764Sjlemon
78096602Srwatson	so = syncache_socket(sc, *sop, m);
78186764Sjlemon	if (so == NULL) {
78286764Sjlemon#if 0
78386764Sjlemonresetandabort:
78486764Sjlemon		/* XXXjlemon check this - is this correct? */
78586764Sjlemon		(void) tcp_respond(NULL, m, m, th,
78686764Sjlemon		    th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
78786764Sjlemon#endif
78886764Sjlemon		m_freem(m);			/* XXX only needed for above */
78986764Sjlemon		tcpstat.tcps_sc_aborted++;
790122922Sandre	} else
79186764Sjlemon		tcpstat.tcps_sc_completed++;
792122922Sandre
79386764Sjlemon	if (sch == NULL)
79486764Sjlemon		syncache_free(sc);
79586764Sjlemon	else
79686764Sjlemon		syncache_drop(sc, sch);
79786764Sjlemon	*sop = so;
79886764Sjlemon	return (1);
79986764Sjlemon}
80086764Sjlemon
80186764Sjlemon/*
80286764Sjlemon * Given a LISTEN socket and an inbound SYN request, add
80386764Sjlemon * this to the syn cache, and send back a segment:
80486764Sjlemon *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
80586764Sjlemon * to the source.
80686764Sjlemon *
80786764Sjlemon * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
80886764Sjlemon * Doing so would require that we hold onto the data and deliver it
80986764Sjlemon * to the application.  However, if we are the target of a SYN-flood
81086764Sjlemon * DoS attack, an attacker could send data which would eventually
81186764Sjlemon * consume all available buffer space if it were ACKed.  By not ACKing
81286764Sjlemon * the data, we avoid this DoS scenario.
81386764Sjlemon */
81486764Sjlemonint
81586764Sjlemonsyncache_add(inc, to, th, sop, m)
81686764Sjlemon	struct in_conninfo *inc;
81786764Sjlemon	struct tcpopt *to;
81886764Sjlemon	struct tcphdr *th;
81986764Sjlemon	struct socket **sop;
82086764Sjlemon	struct mbuf *m;
82186764Sjlemon{
82286764Sjlemon	struct tcpcb *tp;
82386764Sjlemon	struct socket *so;
82486764Sjlemon	struct syncache *sc = NULL;
82586764Sjlemon	struct syncache_head *sch;
82686764Sjlemon	struct mbuf *ipopts = NULL;
827122922Sandre	struct rmxp_tao tao;
828122496Ssam	int i, win;
82986764Sjlemon
830122496Ssam	INP_INFO_WLOCK_ASSERT(&tcbinfo);
831122496Ssam
83286764Sjlemon	so = *sop;
83386764Sjlemon	tp = sototcpcb(so);
834122922Sandre	bzero(&tao, sizeof(tao));
83586764Sjlemon
83686764Sjlemon	/*
83786764Sjlemon	 * Remember the IP options, if any.
83886764Sjlemon	 */
83986764Sjlemon#ifdef INET6
84086764Sjlemon	if (!inc->inc_isipv6)
84186764Sjlemon#endif
84286764Sjlemon		ipopts = ip_srcroute();
84386764Sjlemon
84486764Sjlemon	/*
84586764Sjlemon	 * See if we already have an entry for this connection.
84686764Sjlemon	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
84786764Sjlemon	 *
84886764Sjlemon	 * XXX
84986764Sjlemon	 * should the syncache be re-initialized with the contents
85086764Sjlemon	 * of the new SYN here (which may have different options?)
85186764Sjlemon	 */
85286764Sjlemon	sc = syncache_lookup(inc, &sch);
85386764Sjlemon	if (sc != NULL) {
85486764Sjlemon		tcpstat.tcps_sc_dupsyn++;
85586764Sjlemon		if (ipopts) {
85686764Sjlemon			/*
85786764Sjlemon			 * If we were remembering a previous source route,
85886764Sjlemon			 * forget it and use the new one we've been given.
85986764Sjlemon			 */
86086764Sjlemon			if (sc->sc_ipopts)
86186764Sjlemon				(void) m_free(sc->sc_ipopts);
86286764Sjlemon			sc->sc_ipopts = ipopts;
86386764Sjlemon		}
86486764Sjlemon		/*
86586764Sjlemon		 * Update timestamp if present.
86686764Sjlemon		 */
86786764Sjlemon		if (sc->sc_flags & SCF_TIMESTAMP)
86886764Sjlemon			sc->sc_tsrecent = to->to_tsval;
86990556Sjlemon		/*
87090556Sjlemon		 * PCB may have changed, pick up new values.
87190556Sjlemon		 */
87290556Sjlemon		sc->sc_tp = tp;
87390556Sjlemon		sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
874118864Sharti#ifdef TCPDEBUG
875118864Sharti		if (syncache_respond(sc, m, so) == 0) {
876118864Sharti#else
87786764Sjlemon		if (syncache_respond(sc, m) == 0) {
878118864Sharti#endif
879122496Ssam			/* NB: guarded by INP_INFO_WLOCK(&tcbinfo) */
88086764Sjlemon			TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot],
88186764Sjlemon			    sc, sc_timerq);
88286764Sjlemon			SYNCACHE_TIMEOUT(sc, sc->sc_rxtslot);
88386764Sjlemon		 	tcpstat.tcps_sndacks++;
88486764Sjlemon			tcpstat.tcps_sndtotal++;
88586764Sjlemon		}
88686764Sjlemon		*sop = NULL;
88786764Sjlemon		return (1);
88886764Sjlemon	}
88986764Sjlemon
89092760Sjeff	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
89186764Sjlemon	if (sc == NULL) {
89286764Sjlemon		/*
89386764Sjlemon		 * The zone allocator couldn't provide more entries.
89486764Sjlemon		 * Treat this as if the cache was full; drop the oldest
89586764Sjlemon		 * entry and insert the new one.
89686764Sjlemon		 */
897122496Ssam		/* NB: guarded by INP_INFO_WLOCK(&tcbinfo) */
89886764Sjlemon		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
89986764Sjlemon			sc = TAILQ_FIRST(&tcp_syncache.timerq[i]);
90086764Sjlemon			if (sc != NULL)
90186764Sjlemon				break;
90286764Sjlemon		}
90388180Sjlemon		sc->sc_tp->ts_recent = ticks;
90486764Sjlemon		syncache_drop(sc, NULL);
90586764Sjlemon		tcpstat.tcps_sc_zonefail++;
90692760Sjeff		sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
90786764Sjlemon		if (sc == NULL) {
90886764Sjlemon			if (ipopts)
90986764Sjlemon				(void) m_free(ipopts);
91086764Sjlemon			return (0);
91186764Sjlemon		}
91286764Sjlemon	}
91386764Sjlemon
91486764Sjlemon	/*
91586764Sjlemon	 * Fill in the syncache values.
91686764Sjlemon	 */
91786958Stanimura	bzero(sc, sizeof(*sc));
91886764Sjlemon	sc->sc_tp = tp;
91986764Sjlemon	sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
92086764Sjlemon	sc->sc_ipopts = ipopts;
92186764Sjlemon	sc->sc_inc.inc_fport = inc->inc_fport;
92286764Sjlemon	sc->sc_inc.inc_lport = inc->inc_lport;
92386764Sjlemon#ifdef INET6
92486764Sjlemon	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
92586764Sjlemon	if (inc->inc_isipv6) {
92686764Sjlemon		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
92786764Sjlemon		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
92886764Sjlemon	} else
92986764Sjlemon#endif
93086764Sjlemon	{
93186764Sjlemon		sc->sc_inc.inc_faddr = inc->inc_faddr;
93286764Sjlemon		sc->sc_inc.inc_laddr = inc->inc_laddr;
93386764Sjlemon	}
93486764Sjlemon	sc->sc_irs = th->th_seq;
935110023Ssilby	sc->sc_flags = 0;
936110023Ssilby	sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
93788330Sjlemon	if (tcp_syncookies)
93888330Sjlemon		sc->sc_iss = syncookie_generate(sc);
93988330Sjlemon	else
94088330Sjlemon		sc->sc_iss = arc4random();
94186764Sjlemon
94286764Sjlemon	/* Initial receive window: clip sbspace to [0 .. TCP_MAXWIN] */
94386764Sjlemon	win = sbspace(&so->so_rcv);
94486764Sjlemon	win = imax(win, 0);
94586764Sjlemon	win = imin(win, TCP_MAXWIN);
94686764Sjlemon	sc->sc_wnd = win;
94786764Sjlemon
94886764Sjlemon	if (tcp_do_rfc1323) {
94986764Sjlemon		/*
95086764Sjlemon		 * A timestamp received in a SYN makes
95186764Sjlemon		 * it ok to send timestamp requests and replies.
95286764Sjlemon		 */
95386764Sjlemon		if (to->to_flags & TOF_TS) {
95486764Sjlemon			sc->sc_tsrecent = to->to_tsval;
95586764Sjlemon			sc->sc_flags |= SCF_TIMESTAMP;
95686764Sjlemon		}
95786764Sjlemon		if (to->to_flags & TOF_SCALE) {
95886764Sjlemon			int wscale = 0;
95986764Sjlemon
96086764Sjlemon			/* Compute proper scaling value from buffer space */
96186764Sjlemon			while (wscale < TCP_MAX_WINSHIFT &&
96286764Sjlemon			    (TCP_MAXWIN << wscale) < so->so_rcv.sb_hiwat)
96386764Sjlemon				wscale++;
96486764Sjlemon			sc->sc_request_r_scale = wscale;
96586764Sjlemon			sc->sc_requested_s_scale = to->to_requested_s_scale;
96686764Sjlemon			sc->sc_flags |= SCF_WINSCALE;
96786764Sjlemon		}
96886764Sjlemon	}
96986764Sjlemon	if (tcp_do_rfc1644) {
97086764Sjlemon		/*
97186764Sjlemon		 * A CC or CC.new option received in a SYN makes
97286764Sjlemon		 * it ok to send CC in subsequent segments.
97386764Sjlemon		 */
97486764Sjlemon		if (to->to_flags & (TOF_CC|TOF_CCNEW)) {
97586764Sjlemon			sc->sc_cc_recv = to->to_cc;
97686764Sjlemon			sc->sc_cc_send = CC_INC(tcp_ccgen);
97786764Sjlemon			sc->sc_flags |= SCF_CC;
97886764Sjlemon		}
97986764Sjlemon	}
98086764Sjlemon	if (tp->t_flags & TF_NOOPT)
98186764Sjlemon		sc->sc_flags = SCF_NOOPT;
982125680Sbms#ifdef TCP_SIGNATURE
983125680Sbms	/*
984125680Sbms	 * If listening socket requested TCP digests, and received SYN
985125680Sbms	 * contains the option, flag this in the syncache so that
986125680Sbms	 * syncache_respond() will do the right thing with the SYN+ACK.
987125680Sbms	 * XXX Currently we always record the option by default and will
988125680Sbms	 * attempt to use it in syncache_respond().
989125680Sbms	 */
990125680Sbms	if (to->to_flags & TOF_SIGNATURE)
991125680Sbms		sc->sc_flags = SCF_SIGNATURE;
992125783Sbms#endif
99386764Sjlemon
99486764Sjlemon	/*
99586764Sjlemon	 * XXX
99686764Sjlemon	 * We have the option here of not doing TAO (even if the segment
99786764Sjlemon	 * qualifies) and instead fall back to a normal 3WHS via the syncache.
99886764Sjlemon	 * This allows us to apply synflood protection to TAO-qualifying SYNs
99986764Sjlemon	 * also. However, there should be a hueristic to determine when to
100086764Sjlemon	 * do this, and is not present at the moment.
100186764Sjlemon	 */
100286764Sjlemon
100386764Sjlemon	/*
100486764Sjlemon	 * Perform TAO test on incoming CC (SEG.CC) option, if any.
100586764Sjlemon	 * - compare SEG.CC against cached CC from the same host, if any.
100686764Sjlemon	 * - if SEG.CC > chached value, SYN must be new and is accepted
100786764Sjlemon	 *	immediately: save new CC in the cache, mark the socket
100886764Sjlemon	 *	connected, enter ESTABLISHED state, turn on flag to
100986764Sjlemon	 *	send a SYN in the next segment.
101086764Sjlemon	 *	A virtual advertised window is set in rcv_adv to
101186764Sjlemon	 *	initialize SWS prevention.  Then enter normal segment
101286764Sjlemon	 *	processing: drop SYN, process data and FIN.
101386764Sjlemon	 * - otherwise do a normal 3-way handshake.
101486764Sjlemon	 */
1015122922Sandre	if (tcp_do_rfc1644)
1016122922Sandre		tcp_hc_gettao(&sc->sc_inc, &tao);
1017122922Sandre
101886764Sjlemon	if ((to->to_flags & TOF_CC) != 0) {
101986764Sjlemon		if (((tp->t_flags & TF_NOPUSH) != 0) &&
1020122922Sandre		    sc->sc_flags & SCF_CC && tao.tao_cc != 0 &&
1021122922Sandre		    CC_GT(to->to_cc, tao.tao_cc)) {
102286764Sjlemon			sc->sc_rxtslot = 0;
102396602Srwatson			so = syncache_socket(sc, *sop, m);
102486764Sjlemon			if (so != NULL) {
1025122922Sandre				tao.tao_cc = to->to_cc;
1026122922Sandre				tcp_hc_updatetao(&sc->sc_inc, TCP_HC_TAO_CC,
1027122922Sandre						 tao.tao_cc, 0);
102886764Sjlemon				*sop = so;
102986764Sjlemon			}
103086764Sjlemon			syncache_free(sc);
103186764Sjlemon			return (so != NULL);
103286764Sjlemon		}
103386764Sjlemon	} else {
103486764Sjlemon		/*
103586764Sjlemon		 * No CC option, but maybe CC.NEW: invalidate cached value.
103686764Sjlemon		 */
1037122922Sandre		if (tcp_do_rfc1644) {
1038122922Sandre			tao.tao_cc = 0;
1039122922Sandre			tcp_hc_updatetao(&sc->sc_inc, TCP_HC_TAO_CC,
1040122922Sandre					 tao.tao_cc, 0);
1041122922Sandre		}
104286764Sjlemon	}
1043122922Sandre
104486764Sjlemon	/*
104586764Sjlemon	 * TAO test failed or there was no CC option,
104686764Sjlemon	 *    do a standard 3-way handshake.
104786764Sjlemon	 */
1048118864Sharti#ifdef TCPDEBUG
1049118864Sharti	if (syncache_respond(sc, m, so) == 0) {
1050118864Sharti#else
105188180Sjlemon	if (syncache_respond(sc, m) == 0) {
1052118864Sharti#endif
105388180Sjlemon		syncache_insert(sc, sch);
105488180Sjlemon		tcpstat.tcps_sndacks++;
105588180Sjlemon		tcpstat.tcps_sndtotal++;
105686764Sjlemon	} else {
105786764Sjlemon		syncache_free(sc);
105888180Sjlemon		tcpstat.tcps_sc_dropped++;
105986764Sjlemon	}
106086764Sjlemon	*sop = NULL;
106186764Sjlemon	return (1);
106286764Sjlemon}
106386764Sjlemon
1064118864Sharti#ifdef TCPDEBUG
106586764Sjlemonstatic int
1066118864Shartisyncache_respond(sc, m, so)
1067118864Sharti	struct syncache *sc;
1068118864Sharti	struct mbuf *m;
1069118864Sharti	struct socket *so;
1070118864Sharti#else
1071118864Shartistatic int
107286764Sjlemonsyncache_respond(sc, m)
107386764Sjlemon	struct syncache *sc;
107486764Sjlemon	struct mbuf *m;
1075118864Sharti#endif
107686764Sjlemon{
107786764Sjlemon	u_int8_t *optp;
107886764Sjlemon	int optlen, error;
107986764Sjlemon	u_int16_t tlen, hlen, mssopt;
108086764Sjlemon	struct ip *ip = NULL;
108186764Sjlemon	struct tcphdr *th;
1082122496Ssam	struct inpcb *inp;
108386764Sjlemon#ifdef INET6
108486764Sjlemon	struct ip6_hdr *ip6 = NULL;
108586764Sjlemon#endif
108686764Sjlemon
1087122922Sandre	hlen =
108886764Sjlemon#ifdef INET6
1089122922Sandre	       (sc->sc_inc.inc_isipv6) ? sizeof(struct ip6_hdr) :
109086764Sjlemon#endif
1091122922Sandre		sizeof(struct ip);
109286764Sjlemon
1093122922Sandre	KASSERT((&sc->sc_inc) != NULL, ("syncache_respond with NULL in_conninfo pointer"));
1094122922Sandre
1095122922Sandre	/* Determine MSS we advertize to other end of connection */
1096122922Sandre	mssopt = tcp_mssopt(&sc->sc_inc);
1097122922Sandre
109886764Sjlemon	/* Compute the size of the TCP options. */
109986764Sjlemon	if (sc->sc_flags & SCF_NOOPT) {
110086764Sjlemon		optlen = 0;
110186764Sjlemon	} else {
110286764Sjlemon		optlen = TCPOLEN_MAXSEG +
110386764Sjlemon		    ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
110486764Sjlemon		    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0) +
110586764Sjlemon		    ((sc->sc_flags & SCF_CC) ? TCPOLEN_CC_APPA * 2 : 0);
1106125680Sbms#ifdef TCP_SIGNATURE
1107125783Sbms		optlen += (sc->sc_flags & SCF_SIGNATURE) ?
1108125819Sbms		    TCPOLEN_SIGNATURE + 2 : 0;
1109125783Sbms#endif
111086764Sjlemon	}
111186764Sjlemon	tlen = hlen + sizeof(struct tcphdr) + optlen;
111286764Sjlemon
111386764Sjlemon	/*
111486764Sjlemon	 * XXX
111586764Sjlemon	 * assume that the entire packet will fit in a header mbuf
111686764Sjlemon	 */
111786764Sjlemon	KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
111886764Sjlemon
111986764Sjlemon	/*
112086764Sjlemon	 * XXX shouldn't this reuse the mbuf if possible ?
112186764Sjlemon	 * Create the IP+TCP header from scratch.
112286764Sjlemon	 */
112386764Sjlemon	if (m)
112486764Sjlemon		m_freem(m);
112586764Sjlemon
1126111119Simp	m = m_gethdr(M_DONTWAIT, MT_HEADER);
112786764Sjlemon	if (m == NULL)
112886764Sjlemon		return (ENOBUFS);
112986764Sjlemon	m->m_data += max_linkhdr;
113086764Sjlemon	m->m_len = tlen;
113186764Sjlemon	m->m_pkthdr.len = tlen;
113286764Sjlemon	m->m_pkthdr.rcvif = NULL;
1133122496Ssam	inp = sc->sc_tp->t_inpcb;
1134122496Ssam	INP_LOCK(inp);
1135101106Srwatson#ifdef MAC
1136128905Srwatson	mac_create_mbuf_from_inpcb(inp, m);
1137101106Srwatson#endif
113886764Sjlemon
113986764Sjlemon#ifdef INET6
114086764Sjlemon	if (sc->sc_inc.inc_isipv6) {
114186764Sjlemon		ip6 = mtod(m, struct ip6_hdr *);
114286764Sjlemon		ip6->ip6_vfc = IPV6_VERSION;
114386764Sjlemon		ip6->ip6_nxt = IPPROTO_TCP;
114486764Sjlemon		ip6->ip6_src = sc->sc_inc.inc6_laddr;
114586764Sjlemon		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
114686764Sjlemon		ip6->ip6_plen = htons(tlen - hlen);
114786764Sjlemon		/* ip6_hlim is set after checksum */
114886764Sjlemon		/* ip6_flow = ??? */
114986764Sjlemon
115086764Sjlemon		th = (struct tcphdr *)(ip6 + 1);
115186764Sjlemon	} else
115286764Sjlemon#endif
115386764Sjlemon	{
115486764Sjlemon		ip = mtod(m, struct ip *);
115586764Sjlemon		ip->ip_v = IPVERSION;
115686764Sjlemon		ip->ip_hl = sizeof(struct ip) >> 2;
115786764Sjlemon		ip->ip_len = tlen;
115886764Sjlemon		ip->ip_id = 0;
115986764Sjlemon		ip->ip_off = 0;
116086764Sjlemon		ip->ip_sum = 0;
116186764Sjlemon		ip->ip_p = IPPROTO_TCP;
116286764Sjlemon		ip->ip_src = sc->sc_inc.inc_laddr;
116386764Sjlemon		ip->ip_dst = sc->sc_inc.inc_faddr;
1164122496Ssam		ip->ip_ttl = inp->inp_ip_ttl;   /* XXX */
1165122496Ssam		ip->ip_tos = inp->inp_ip_tos;   /* XXX */
116686764Sjlemon
116798204Ssilby		/*
1168108125Shsu		 * See if we should do MTU discovery.  Route lookups are
1169108125Shsu		 * expensive, so we will only unset the DF bit if:
1170101405Ssilby		 *
1171101405Ssilby		 *	1) path_mtu_discovery is disabled
1172101405Ssilby		 *	2) the SCF_UNREACH flag has been set
117398204Ssilby		 */
1174108125Shsu		if (path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
117598204Ssilby		       ip->ip_off |= IP_DF;
117698204Ssilby
117786764Sjlemon		th = (struct tcphdr *)(ip + 1);
117886764Sjlemon	}
117986764Sjlemon	th->th_sport = sc->sc_inc.inc_lport;
118086764Sjlemon	th->th_dport = sc->sc_inc.inc_fport;
118186764Sjlemon
118286764Sjlemon	th->th_seq = htonl(sc->sc_iss);
118386764Sjlemon	th->th_ack = htonl(sc->sc_irs + 1);
118486764Sjlemon	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
118586764Sjlemon	th->th_x2 = 0;
118686764Sjlemon	th->th_flags = TH_SYN|TH_ACK;
118786764Sjlemon	th->th_win = htons(sc->sc_wnd);
118886764Sjlemon	th->th_urp = 0;
118986764Sjlemon
119086764Sjlemon	/* Tack on the TCP options. */
1191108125Shsu	if (optlen != 0) {
1192108125Shsu		optp = (u_int8_t *)(th + 1);
1193108125Shsu		*optp++ = TCPOPT_MAXSEG;
1194108125Shsu		*optp++ = TCPOLEN_MAXSEG;
1195108125Shsu		*optp++ = (mssopt >> 8) & 0xff;
1196108125Shsu		*optp++ = mssopt & 0xff;
119786764Sjlemon
1198108125Shsu		if (sc->sc_flags & SCF_WINSCALE) {
1199108125Shsu			*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1200108125Shsu			    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1201108125Shsu			    sc->sc_request_r_scale);
1202108125Shsu			optp += 4;
1203108125Shsu		}
120486764Sjlemon
1205108125Shsu		if (sc->sc_flags & SCF_TIMESTAMP) {
1206108125Shsu			u_int32_t *lp = (u_int32_t *)(optp);
120786764Sjlemon
1208108125Shsu			/* Form timestamp option per appendix A of RFC 1323. */
1209108125Shsu			*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1210108125Shsu			*lp++ = htonl(ticks);
1211108125Shsu			*lp   = htonl(sc->sc_tsrecent);
1212108125Shsu			optp += TCPOLEN_TSTAMP_APPA;
1213108125Shsu		}
121486764Sjlemon
1215108125Shsu		/*
1216108125Shsu		 * Send CC and CC.echo if we received CC from our peer.
1217108125Shsu		 */
1218108125Shsu		if (sc->sc_flags & SCF_CC) {
1219108125Shsu			u_int32_t *lp = (u_int32_t *)(optp);
122086764Sjlemon
1221108125Shsu			*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
1222108125Shsu			*lp++ = htonl(sc->sc_cc_send);
1223108125Shsu			*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CCECHO));
1224108125Shsu			*lp   = htonl(sc->sc_cc_recv);
1225108125Shsu			optp += TCPOLEN_CC_APPA * 2;
1226108125Shsu		}
1227125680Sbms
1228125680Sbms#ifdef TCP_SIGNATURE
1229125680Sbms		/*
1230125680Sbms		 * Handle TCP-MD5 passive opener response.
1231125680Sbms		 */
1232125680Sbms		if (sc->sc_flags & SCF_SIGNATURE) {
1233125680Sbms			u_int8_t *bp = optp;
1234125680Sbms			int i;
1235125680Sbms
1236125680Sbms			*bp++ = TCPOPT_SIGNATURE;
1237125680Sbms			*bp++ = TCPOLEN_SIGNATURE;
1238125680Sbms			for (i = 0; i < TCP_SIGLEN; i++)
1239125680Sbms				*bp++ = 0;
1240125783Sbms			tcp_signature_compute(m, sizeof(struct ip), 0, optlen,
1241125680Sbms			    optp + 2, IPSEC_DIR_OUTBOUND);
1242125680Sbms			*bp++ = TCPOPT_NOP;
1243125680Sbms			*bp++ = TCPOPT_EOL;
1244125680Sbms			optp += TCPOLEN_SIGNATURE + 2;
1245125680Sbms		}
1246125680Sbms#endif /* TCP_SIGNATURE */
124786764Sjlemon	}
124886764Sjlemon
124986764Sjlemon#ifdef INET6
125086764Sjlemon	if (sc->sc_inc.inc_isipv6) {
125186764Sjlemon		th->th_sum = 0;
125286764Sjlemon		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1253122922Sandre		ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
1254122922Sandre		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
125586764Sjlemon	} else
125686764Sjlemon#endif
125786764Sjlemon	{
125886764Sjlemon        	th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
125986764Sjlemon		    htons(tlen - hlen + IPPROTO_TCP));
126086764Sjlemon		m->m_pkthdr.csum_flags = CSUM_TCP;
126186764Sjlemon		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1262118864Sharti#ifdef TCPDEBUG
1263118864Sharti		/*
1264118864Sharti		 * Trace.
1265118864Sharti		 */
1266118864Sharti		if (so != NULL && so->so_options & SO_DEBUG) {
1267118864Sharti			struct tcpcb *tp = sototcpcb(so);
1268118864Sharti			tcp_trace(TA_OUTPUT, tp->t_state, tp,
1269118864Sharti			    mtod(m, void *), th, 0);
1270118864Sharti		}
1271118864Sharti#endif
1272122922Sandre		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, inp);
127386764Sjlemon	}
1274122496Ssam	INP_UNLOCK(inp);
127586764Sjlemon	return (error);
127686764Sjlemon}
127788180Sjlemon
127888180Sjlemon/*
127988180Sjlemon * cookie layers:
128088180Sjlemon *
128188180Sjlemon *	|. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
128288180Sjlemon *	| peer iss                                                      |
1283111405Ssilby *	| MD5(laddr,faddr,secret,lport,fport)             |. . . . . . .|
128488180Sjlemon *	|                     0                       |(A)|             |
128588180Sjlemon * (A): peer mss index
128688180Sjlemon */
128788180Sjlemon
128888180Sjlemon/*
128988180Sjlemon * The values below are chosen to minimize the size of the tcp_secret
1290111338Ssilby * table, as well as providing roughly a 16 second lifetime for the cookie.
129188180Sjlemon */
129288180Sjlemon
1293111338Ssilby#define SYNCOOKIE_WNDBITS	5	/* exposed bits for window indexing */
1294111338Ssilby#define SYNCOOKIE_TIMESHIFT	1	/* scale ticks to window time units */
129588180Sjlemon
129688180Sjlemon#define SYNCOOKIE_WNDMASK	((1 << SYNCOOKIE_WNDBITS) - 1)
1297111338Ssilby#define SYNCOOKIE_NSECRETS	(1 << SYNCOOKIE_WNDBITS)
129888180Sjlemon#define SYNCOOKIE_TIMEOUT \
129988180Sjlemon    (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
130088180Sjlemon#define SYNCOOKIE_DATAMASK 	((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
130188180Sjlemon
130288180Sjlemonstatic struct {
1303111338Ssilby	u_int32_t	ts_secbits[4];
130488180Sjlemon	u_int		ts_expire;
130588180Sjlemon} tcp_secret[SYNCOOKIE_NSECRETS];
130688180Sjlemon
130788180Sjlemonstatic int tcp_msstab[] = { 0, 536, 1460, 8960 };
130888180Sjlemon
130988180Sjlemonstatic MD5_CTX syn_ctx;
131088180Sjlemon
131188180Sjlemon#define MD5Add(v)	MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
131288180Sjlemon
1313111338Ssilbystruct md5_add {
1314111338Ssilby	u_int32_t laddr, faddr;
1315111338Ssilby	u_int32_t secbits[4];
1316111338Ssilby	u_int16_t lport, fport;
1317111338Ssilby};
1318111338Ssilby
1319111338Ssilby#ifdef CTASSERT
1320111338SsilbyCTASSERT(sizeof(struct md5_add) == 28);
1321111338Ssilby#endif
1322111338Ssilby
132388180Sjlemon/*
132488180Sjlemon * Consider the problem of a recreated (and retransmitted) cookie.  If the
132588180Sjlemon * original SYN was accepted, the connection is established.  The second
132688180Sjlemon * SYN is inflight, and if it arrives with an ISN that falls within the
132788180Sjlemon * receive window, the connection is killed.
132888180Sjlemon *
132988180Sjlemon * However, since cookies have other problems, this may not be worth
133088180Sjlemon * worrying about.
133188180Sjlemon */
133288180Sjlemon
133388180Sjlemonstatic u_int32_t
133488180Sjlemonsyncookie_generate(struct syncache *sc)
133588180Sjlemon{
133688180Sjlemon	u_int32_t md5_buffer[4];
133788180Sjlemon	u_int32_t data;
1338111338Ssilby	int idx, i;
1339111338Ssilby	struct md5_add add;
134088180Sjlemon
1341122496Ssam	/* NB: single threaded; could add INP_INFO_WLOCK_ASSERT(&tcbinfo) */
1342122496Ssam
1343111338Ssilby	idx = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
134488180Sjlemon	if (tcp_secret[idx].ts_expire < ticks) {
1345111338Ssilby		for (i = 0; i < 4; i++)
1346111338Ssilby			tcp_secret[idx].ts_secbits[i] = arc4random();
134788180Sjlemon		tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
134888180Sjlemon	}
134988180Sjlemon	for (data = sizeof(tcp_msstab) / sizeof(int) - 1; data > 0; data--)
135088180Sjlemon		if (tcp_msstab[data] <= sc->sc_peer_mss)
135188180Sjlemon			break;
1352111338Ssilby	data = (data << SYNCOOKIE_WNDBITS) | idx;
135388180Sjlemon	data ^= sc->sc_irs;				/* peer's iss */
135488180Sjlemon	MD5Init(&syn_ctx);
135588180Sjlemon#ifdef INET6
135688180Sjlemon	if (sc->sc_inc.inc_isipv6) {
135788180Sjlemon		MD5Add(sc->sc_inc.inc6_laddr);
135888180Sjlemon		MD5Add(sc->sc_inc.inc6_faddr);
1359111338Ssilby		add.laddr = 0;
1360111338Ssilby		add.faddr = 0;
136188180Sjlemon	} else
136288180Sjlemon#endif
136388180Sjlemon	{
1364111338Ssilby		add.laddr = sc->sc_inc.inc_laddr.s_addr;
1365111338Ssilby		add.faddr = sc->sc_inc.inc_faddr.s_addr;
136688180Sjlemon	}
1367111338Ssilby	add.lport = sc->sc_inc.inc_lport;
1368111338Ssilby	add.fport = sc->sc_inc.inc_fport;
1369111338Ssilby	add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1370111338Ssilby	add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1371111338Ssilby	add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1372111338Ssilby	add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1373111338Ssilby	MD5Add(add);
137488180Sjlemon	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1375111338Ssilby	data ^= (md5_buffer[0] & ~SYNCOOKIE_WNDMASK);
137688180Sjlemon	return (data);
137788180Sjlemon}
137888180Sjlemon
137988180Sjlemonstatic struct syncache *
138088180Sjlemonsyncookie_lookup(inc, th, so)
138188180Sjlemon	struct in_conninfo *inc;
138288180Sjlemon	struct tcphdr *th;
138388180Sjlemon	struct socket *so;
138488180Sjlemon{
138588180Sjlemon	u_int32_t md5_buffer[4];
138688180Sjlemon	struct syncache *sc;
138788180Sjlemon	u_int32_t data;
138888180Sjlemon	int wnd, idx;
1389111338Ssilby	struct md5_add add;
139088180Sjlemon
1391122496Ssam	/* NB: single threaded; could add INP_INFO_WLOCK_ASSERT(&tcbinfo) */
1392122496Ssam
139388180Sjlemon	data = (th->th_ack - 1) ^ (th->th_seq - 1);	/* remove ISS */
1394111338Ssilby	idx = data & SYNCOOKIE_WNDMASK;
139588180Sjlemon	if (tcp_secret[idx].ts_expire < ticks ||
139688180Sjlemon	    sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
139788180Sjlemon		return (NULL);
139888180Sjlemon	MD5Init(&syn_ctx);
139988180Sjlemon#ifdef INET6
140088180Sjlemon	if (inc->inc_isipv6) {
140188180Sjlemon		MD5Add(inc->inc6_laddr);
140288180Sjlemon		MD5Add(inc->inc6_faddr);
1403111338Ssilby		add.laddr = 0;
1404111338Ssilby		add.faddr = 0;
140588180Sjlemon	} else
140688180Sjlemon#endif
140788180Sjlemon	{
1408111338Ssilby		add.laddr = inc->inc_laddr.s_addr;
1409111338Ssilby		add.faddr = inc->inc_faddr.s_addr;
141088180Sjlemon	}
1411111338Ssilby	add.lport = inc->inc_lport;
1412111338Ssilby	add.fport = inc->inc_fport;
1413111338Ssilby	add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1414111338Ssilby	add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1415111338Ssilby	add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1416111338Ssilby	add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1417111338Ssilby	MD5Add(add);
141888180Sjlemon	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1419111338Ssilby	data ^= md5_buffer[0];
142088180Sjlemon	if ((data & ~SYNCOOKIE_DATAMASK) != 0)
142188180Sjlemon		return (NULL);
142288180Sjlemon	data = data >> SYNCOOKIE_WNDBITS;
142388180Sjlemon
142492760Sjeff	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
142588180Sjlemon	if (sc == NULL)
142688180Sjlemon		return (NULL);
142788180Sjlemon	/*
142888180Sjlemon	 * Fill in the syncache values.
142988180Sjlemon	 * XXX duplicate code from syncache_add
143088180Sjlemon	 */
143188180Sjlemon	sc->sc_ipopts = NULL;
143288180Sjlemon	sc->sc_inc.inc_fport = inc->inc_fport;
143388180Sjlemon	sc->sc_inc.inc_lport = inc->inc_lport;
143488180Sjlemon#ifdef INET6
143588180Sjlemon	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
143688180Sjlemon	if (inc->inc_isipv6) {
143788180Sjlemon		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
143888180Sjlemon		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
143988180Sjlemon	} else
144088180Sjlemon#endif
144188180Sjlemon	{
144288180Sjlemon		sc->sc_inc.inc_faddr = inc->inc_faddr;
144388180Sjlemon		sc->sc_inc.inc_laddr = inc->inc_laddr;
144488180Sjlemon	}
144588180Sjlemon	sc->sc_irs = th->th_seq - 1;
144688180Sjlemon	sc->sc_iss = th->th_ack - 1;
144788180Sjlemon	wnd = sbspace(&so->so_rcv);
144888180Sjlemon	wnd = imax(wnd, 0);
144988180Sjlemon	wnd = imin(wnd, TCP_MAXWIN);
145088180Sjlemon	sc->sc_wnd = wnd;
145188180Sjlemon	sc->sc_flags = 0;
145288180Sjlemon	sc->sc_rxtslot = 0;
145388180Sjlemon	sc->sc_peer_mss = tcp_msstab[data];
145488180Sjlemon	return (sc);
145588180Sjlemon}
1456