tcp_syncache.c revision 174558
1/*-
2 * Copyright (c) 2001 McAfee, Inc.
3 * Copyright (c) 2006 Andre Oppermann, Internet Business Solutions AG
4 * All rights reserved.
5 *
6 * This software was developed for the FreeBSD Project by Jonathan Lemon
7 * and McAfee Research, the Security Research Division of McAfee, Inc. under
8 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
9 * DARPA CHATS research program.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: head/sys/netinet/tcp_syncache.c 174558 2007-12-12 20:35:59Z kmacy $");
35
36#include "opt_inet.h"
37#include "opt_inet6.h"
38#include "opt_ipsec.h"
39#include "opt_mac.h"
40
41#include <sys/param.h>
42#include <sys/systm.h>
43#include <sys/kernel.h>
44#include <sys/sysctl.h>
45#include <sys/lock.h>
46#include <sys/mutex.h>
47#include <sys/malloc.h>
48#include <sys/mbuf.h>
49#include <sys/md5.h>
50#include <sys/proc.h>		/* for proc0 declaration */
51#include <sys/random.h>
52#include <sys/socket.h>
53#include <sys/socketvar.h>
54#include <sys/syslog.h>
55
56#include <vm/uma.h>
57
58#include <net/if.h>
59#include <net/route.h>
60
61#include <netinet/in.h>
62#include <netinet/in_systm.h>
63#include <netinet/ip.h>
64#include <netinet/in_var.h>
65#include <netinet/in_pcb.h>
66#include <netinet/ip_var.h>
67#include <netinet/ip_options.h>
68#ifdef INET6
69#include <netinet/ip6.h>
70#include <netinet/icmp6.h>
71#include <netinet6/nd6.h>
72#include <netinet6/ip6_var.h>
73#include <netinet6/in6_pcb.h>
74#endif
75#include <netinet/tcp.h>
76#include <netinet/tcp_fsm.h>
77#include <netinet/tcp_seq.h>
78#include <netinet/tcp_timer.h>
79#include <netinet/tcp_var.h>
80#include <netinet/tcp_syncache.h>
81#include <netinet/tcp_ofld.h>
82#ifdef INET6
83#include <netinet6/tcp6_var.h>
84#endif
85
86#ifdef IPSEC
87#include <netipsec/ipsec.h>
88#ifdef INET6
89#include <netipsec/ipsec6.h>
90#endif
91#include <netipsec/key.h>
92#endif /*IPSEC*/
93
94#include <machine/in_cksum.h>
95
96#include <security/mac/mac_framework.h>
97
98static int tcp_syncookies = 1;
99SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
100    &tcp_syncookies, 0,
101    "Use TCP SYN cookies if the syncache overflows");
102
103static int tcp_syncookiesonly = 0;
104SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies_only, CTLFLAG_RW,
105    &tcp_syncookiesonly, 0,
106    "Use only TCP SYN cookies");
107
108#define	SYNCOOKIE_SECRET_SIZE	8	/* dwords */
109#define	SYNCOOKIE_LIFETIME	16	/* seconds */
110
111struct syncache {
112	TAILQ_ENTRY(syncache)	sc_hash;
113	struct		in_conninfo sc_inc;	/* addresses */
114	u_long		sc_rxttime;		/* retransmit time */
115	u_int16_t	sc_rxmits;		/* retransmit counter */
116
117	u_int32_t	sc_tsreflect;		/* timestamp to reflect */
118	u_int32_t	sc_ts;			/* our timestamp to send */
119	u_int32_t	sc_tsoff;		/* ts offset w/ syncookies */
120	u_int32_t	sc_flowlabel;		/* IPv6 flowlabel */
121	tcp_seq		sc_irs;			/* seq from peer */
122	tcp_seq		sc_iss;			/* our ISS */
123	struct		mbuf *sc_ipopts;	/* source route */
124
125	u_int16_t	sc_peer_mss;		/* peer's MSS */
126	u_int16_t	sc_wnd;			/* advertised window */
127	u_int8_t	sc_ip_ttl;		/* IPv4 TTL */
128	u_int8_t	sc_ip_tos;		/* IPv4 TOS */
129	u_int8_t	sc_requested_s_scale:4,
130			sc_requested_r_scale:4;
131	u_int8_t	sc_flags;
132#define SCF_NOOPT	0x01			/* no TCP options */
133#define SCF_WINSCALE	0x02			/* negotiated window scaling */
134#define SCF_TIMESTAMP	0x04			/* negotiated timestamps */
135						/* MSS is implicit */
136#define SCF_UNREACH	0x10			/* icmp unreachable received */
137#define SCF_SIGNATURE	0x20			/* send MD5 digests */
138#define SCF_SACK	0x80			/* send SACK option */
139#ifndef DISABLE_TCP_OFFLOAD
140	struct toe_usrreqs *sc_tu;		/* TOE operations */
141	void 		*sc_toepcb;		/* TOE protocol block */
142#endif
143#ifdef MAC
144	struct label	*sc_label;		/* MAC label reference */
145#endif
146};
147
148struct syncache_head {
149	struct mtx	sch_mtx;
150	TAILQ_HEAD(sch_head, syncache)	sch_bucket;
151	struct callout	sch_timer;
152	int		sch_nextc;
153	u_int		sch_length;
154	u_int		sch_oddeven;
155	u_int32_t	sch_secbits_odd[SYNCOOKIE_SECRET_SIZE];
156	u_int32_t	sch_secbits_even[SYNCOOKIE_SECRET_SIZE];
157	u_int		sch_reseed;		/* time_uptime, seconds */
158};
159
160static void	 syncache_drop(struct syncache *, struct syncache_head *);
161static void	 syncache_free(struct syncache *);
162static void	 syncache_insert(struct syncache *, struct syncache_head *);
163struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
164static int	 syncache_respond(struct syncache *);
165static struct	 socket *syncache_socket(struct syncache *, struct socket *,
166		    struct mbuf *m);
167static void	 syncache_timeout(struct syncache *sc, struct syncache_head *sch,
168		    int docallout);
169static void	 syncache_timer(void *);
170static void	 syncookie_generate(struct syncache_head *, struct syncache *,
171		    u_int32_t *);
172static struct syncache
173		*syncookie_lookup(struct in_conninfo *, struct syncache_head *,
174		    struct syncache *, struct tcpopt *, struct tcphdr *,
175		    struct socket *);
176
177/*
178 * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
179 * 3 retransmits corresponds to a timeout of (1 + 2 + 4 + 8 == 15) seconds,
180 * the odds are that the user has given up attempting to connect by then.
181 */
182#define SYNCACHE_MAXREXMTS		3
183
184/* Arbitrary values */
185#define TCP_SYNCACHE_HASHSIZE		512
186#define TCP_SYNCACHE_BUCKETLIMIT	30
187
188struct tcp_syncache {
189	struct	syncache_head *hashbase;
190	uma_zone_t zone;
191	u_int	hashsize;
192	u_int	hashmask;
193	u_int	bucket_limit;
194	u_int	cache_count;		/* XXX: unprotected */
195	u_int	cache_limit;
196	u_int	rexmt_limit;
197	u_int	hash_secret;
198};
199static struct tcp_syncache tcp_syncache;
200
201SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
202
203SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RDTUN,
204     &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
205
206SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RDTUN,
207     &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
208
209SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
210     &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
211
212SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RDTUN,
213     &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
214
215SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
216     &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
217
218int	tcp_sc_rst_sock_fail = 1;
219SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rst_on_sock_fail, CTLFLAG_RW,
220     &tcp_sc_rst_sock_fail, 0, "Send reset on socket allocation failure");
221
222static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
223
224#define SYNCACHE_HASH(inc, mask)					\
225	((tcp_syncache.hash_secret ^					\
226	  (inc)->inc_faddr.s_addr ^					\
227	  ((inc)->inc_faddr.s_addr >> 16) ^				\
228	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
229
230#define SYNCACHE_HASH6(inc, mask)					\
231	((tcp_syncache.hash_secret ^					\
232	  (inc)->inc6_faddr.s6_addr32[0] ^				\
233	  (inc)->inc6_faddr.s6_addr32[3] ^				\
234	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
235
236#define ENDPTS_EQ(a, b) (						\
237	(a)->ie_fport == (b)->ie_fport &&				\
238	(a)->ie_lport == (b)->ie_lport &&				\
239	(a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&			\
240	(a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr			\
241)
242
243#define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
244
245#define	SCH_LOCK(sch)		mtx_lock(&(sch)->sch_mtx)
246#define	SCH_UNLOCK(sch)		mtx_unlock(&(sch)->sch_mtx)
247#define	SCH_LOCK_ASSERT(sch)	mtx_assert(&(sch)->sch_mtx, MA_OWNED)
248
249/*
250 * Requires the syncache entry to be already removed from the bucket list.
251 */
252static void
253syncache_free(struct syncache *sc)
254{
255	if (sc->sc_ipopts)
256		(void) m_free(sc->sc_ipopts);
257#ifdef MAC
258	mac_syncache_destroy(&sc->sc_label);
259#endif
260
261	uma_zfree(tcp_syncache.zone, sc);
262}
263
264void
265syncache_init(void)
266{
267	int i;
268
269	tcp_syncache.cache_count = 0;
270	tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
271	tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
272	tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
273	tcp_syncache.hash_secret = arc4random();
274
275	TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
276	    &tcp_syncache.hashsize);
277	TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
278	    &tcp_syncache.bucket_limit);
279	if (!powerof2(tcp_syncache.hashsize) || tcp_syncache.hashsize == 0) {
280		printf("WARNING: syncache hash size is not a power of 2.\n");
281		tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
282	}
283	tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
284
285	/* Set limits. */
286	tcp_syncache.cache_limit =
287	    tcp_syncache.hashsize * tcp_syncache.bucket_limit;
288	TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
289	    &tcp_syncache.cache_limit);
290
291	/* Allocate the hash table. */
292	MALLOC(tcp_syncache.hashbase, struct syncache_head *,
293	    tcp_syncache.hashsize * sizeof(struct syncache_head),
294	    M_SYNCACHE, M_WAITOK | M_ZERO);
295
296	/* Initialize the hash buckets. */
297	for (i = 0; i < tcp_syncache.hashsize; i++) {
298		TAILQ_INIT(&tcp_syncache.hashbase[i].sch_bucket);
299		mtx_init(&tcp_syncache.hashbase[i].sch_mtx, "tcp_sc_head",
300			 NULL, MTX_DEF);
301		callout_init_mtx(&tcp_syncache.hashbase[i].sch_timer,
302			 &tcp_syncache.hashbase[i].sch_mtx, 0);
303		tcp_syncache.hashbase[i].sch_length = 0;
304	}
305
306	/* Create the syncache entry zone. */
307	tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
308	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
309	uma_zone_set_max(tcp_syncache.zone, tcp_syncache.cache_limit);
310}
311
312/*
313 * Inserts a syncache entry into the specified bucket row.
314 * Locks and unlocks the syncache_head autonomously.
315 */
316static void
317syncache_insert(struct syncache *sc, struct syncache_head *sch)
318{
319	struct syncache *sc2;
320
321	SCH_LOCK(sch);
322
323	/*
324	 * Make sure that we don't overflow the per-bucket limit.
325	 * If the bucket is full, toss the oldest element.
326	 */
327	if (sch->sch_length >= tcp_syncache.bucket_limit) {
328		KASSERT(!TAILQ_EMPTY(&sch->sch_bucket),
329			("sch->sch_length incorrect"));
330		sc2 = TAILQ_LAST(&sch->sch_bucket, sch_head);
331		syncache_drop(sc2, sch);
332		tcpstat.tcps_sc_bucketoverflow++;
333	}
334
335	/* Put it into the bucket. */
336	TAILQ_INSERT_HEAD(&sch->sch_bucket, sc, sc_hash);
337	sch->sch_length++;
338
339	/* Reinitialize the bucket row's timer. */
340	syncache_timeout(sc, sch, 1);
341
342	SCH_UNLOCK(sch);
343
344	tcp_syncache.cache_count++;
345	tcpstat.tcps_sc_added++;
346}
347
348/*
349 * Remove and free entry from syncache bucket row.
350 * Expects locked syncache head.
351 */
352static void
353syncache_drop(struct syncache *sc, struct syncache_head *sch)
354{
355
356	SCH_LOCK_ASSERT(sch);
357
358	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
359	sch->sch_length--;
360
361#ifndef DISABLE_TCP_OFFLOAD
362	if (sc->sc_tu)
363		sc->sc_tu->tu_syncache_event(SC_DROP, sc->sc_toepcb);
364#endif
365	syncache_free(sc);
366	tcp_syncache.cache_count--;
367}
368
369/*
370 * Engage/reengage time on bucket row.
371 */
372static void
373syncache_timeout(struct syncache *sc, struct syncache_head *sch, int docallout)
374{
375	sc->sc_rxttime = ticks +
376		TCPTV_RTOBASE * (tcp_backoff[sc->sc_rxmits]);
377	sc->sc_rxmits++;
378	if (sch->sch_nextc > sc->sc_rxttime)
379		sch->sch_nextc = sc->sc_rxttime;
380	if (!TAILQ_EMPTY(&sch->sch_bucket) && docallout)
381		callout_reset(&sch->sch_timer, sch->sch_nextc - ticks,
382		    syncache_timer, (void *)sch);
383}
384
385/*
386 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
387 * If we have retransmitted an entry the maximum number of times, expire it.
388 * One separate timer for each bucket row.
389 */
390static void
391syncache_timer(void *xsch)
392{
393	struct syncache_head *sch = (struct syncache_head *)xsch;
394	struct syncache *sc, *nsc;
395	int tick = ticks;
396	char *s;
397
398	/* NB: syncache_head has already been locked by the callout. */
399	SCH_LOCK_ASSERT(sch);
400
401	TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) {
402		/*
403		 * We do not check if the listen socket still exists
404		 * and accept the case where the listen socket may be
405		 * gone by the time we resend the SYN/ACK.  We do
406		 * not expect this to happens often. If it does,
407		 * then the RST will be sent by the time the remote
408		 * host does the SYN/ACK->ACK.
409		 */
410		if (sc->sc_rxttime > tick) {
411			if (sc->sc_rxttime < sch->sch_nextc)
412				sch->sch_nextc = sc->sc_rxttime;
413			continue;
414		}
415		if (sc->sc_rxmits > tcp_syncache.rexmt_limit) {
416			if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
417				log(LOG_DEBUG, "%s; %s: Retransmits exhausted, "
418				    "giving up and removing syncache entry\n",
419				    s, __func__);
420				free(s, M_TCPLOG);
421			}
422			syncache_drop(sc, sch);
423			tcpstat.tcps_sc_stale++;
424			continue;
425		}
426		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
427			log(LOG_DEBUG, "%s; %s: Response timeout, "
428			    "retransmitting (%u) SYN|ACK\n",
429			    s, __func__, sc->sc_rxmits);
430			free(s, M_TCPLOG);
431		}
432
433		(void) syncache_respond(sc);
434		tcpstat.tcps_sc_retransmitted++;
435		syncache_timeout(sc, sch, 0);
436	}
437	if (!TAILQ_EMPTY(&(sch)->sch_bucket))
438		callout_reset(&(sch)->sch_timer, (sch)->sch_nextc - tick,
439			syncache_timer, (void *)(sch));
440}
441
442/*
443 * Find an entry in the syncache.
444 * Returns always with locked syncache_head plus a matching entry or NULL.
445 */
446struct syncache *
447syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
448{
449	struct syncache *sc;
450	struct syncache_head *sch;
451
452#ifdef INET6
453	if (inc->inc_isipv6) {
454		sch = &tcp_syncache.hashbase[
455		    SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
456		*schp = sch;
457
458		SCH_LOCK(sch);
459
460		/* Circle through bucket row to find matching entry. */
461		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
462			if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
463				return (sc);
464		}
465	} else
466#endif
467	{
468		sch = &tcp_syncache.hashbase[
469		    SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
470		*schp = sch;
471
472		SCH_LOCK(sch);
473
474		/* Circle through bucket row to find matching entry. */
475		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
476#ifdef INET6
477			if (sc->sc_inc.inc_isipv6)
478				continue;
479#endif
480			if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
481				return (sc);
482		}
483	}
484	SCH_LOCK_ASSERT(*schp);
485	return (NULL);			/* always returns with locked sch */
486}
487
488/*
489 * This function is called when we get a RST for a
490 * non-existent connection, so that we can see if the
491 * connection is in the syn cache.  If it is, zap it.
492 */
493void
494syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th)
495{
496	struct syncache *sc;
497	struct syncache_head *sch;
498	char *s = NULL;
499
500	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
501	SCH_LOCK_ASSERT(sch);
502
503	/*
504	 * Any RST to our SYN|ACK must not carry ACK, SYN or FIN flags.
505	 * See RFC 793 page 65, section SEGMENT ARRIVES.
506	 */
507	if (th->th_flags & (TH_ACK|TH_SYN|TH_FIN)) {
508		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
509			log(LOG_DEBUG, "%s; %s: Spurious RST with ACK, SYN or "
510			    "FIN flag set, segment ignored\n", s, __func__);
511		tcpstat.tcps_badrst++;
512		goto done;
513	}
514
515	/*
516	 * No corresponding connection was found in syncache.
517	 * If syncookies are enabled and possibly exclusively
518	 * used, or we are under memory pressure, a valid RST
519	 * may not find a syncache entry.  In that case we're
520	 * done and no SYN|ACK retransmissions will happen.
521	 * Otherwise the the RST was misdirected or spoofed.
522	 */
523	if (sc == NULL) {
524		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
525			log(LOG_DEBUG, "%s; %s: Spurious RST without matching "
526			    "syncache entry (possibly syncookie only), "
527			    "segment ignored\n", s, __func__);
528		tcpstat.tcps_badrst++;
529		goto done;
530	}
531
532	/*
533	 * If the RST bit is set, check the sequence number to see
534	 * if this is a valid reset segment.
535	 * RFC 793 page 37:
536	 *   In all states except SYN-SENT, all reset (RST) segments
537	 *   are validated by checking their SEQ-fields.  A reset is
538	 *   valid if its sequence number is in the window.
539	 *
540	 *   The sequence number in the reset segment is normally an
541	 *   echo of our outgoing acknowlegement numbers, but some hosts
542	 *   send a reset with the sequence number at the rightmost edge
543	 *   of our receive window, and we have to handle this case.
544	 */
545	if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
546	    SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
547		syncache_drop(sc, sch);
548		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
549			log(LOG_DEBUG, "%s; %s: Our SYN|ACK was rejected, "
550			    "connection attempt aborted by remote endpoint\n",
551			    s, __func__);
552		tcpstat.tcps_sc_reset++;
553	} else if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
554		log(LOG_DEBUG, "%s; %s: RST with invalid SEQ %u != IRS %u "
555		    "(+WND %u), segment ignored\n",
556		    s, __func__, th->th_seq, sc->sc_irs, sc->sc_wnd);
557		tcpstat.tcps_badrst++;
558	}
559
560done:
561	if (s != NULL)
562		free(s, M_TCPLOG);
563	SCH_UNLOCK(sch);
564}
565
566void
567syncache_badack(struct in_conninfo *inc)
568{
569	struct syncache *sc;
570	struct syncache_head *sch;
571
572	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
573	SCH_LOCK_ASSERT(sch);
574	if (sc != NULL) {
575		syncache_drop(sc, sch);
576		tcpstat.tcps_sc_badack++;
577	}
578	SCH_UNLOCK(sch);
579}
580
581void
582syncache_unreach(struct in_conninfo *inc, struct tcphdr *th)
583{
584	struct syncache *sc;
585	struct syncache_head *sch;
586
587	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
588	SCH_LOCK_ASSERT(sch);
589	if (sc == NULL)
590		goto done;
591
592	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
593	if (ntohl(th->th_seq) != sc->sc_iss)
594		goto done;
595
596	/*
597	 * If we've rertransmitted 3 times and this is our second error,
598	 * we remove the entry.  Otherwise, we allow it to continue on.
599	 * This prevents us from incorrectly nuking an entry during a
600	 * spurious network outage.
601	 *
602	 * See tcp_notify().
603	 */
604	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxmits < 3 + 1) {
605		sc->sc_flags |= SCF_UNREACH;
606		goto done;
607	}
608	syncache_drop(sc, sch);
609	tcpstat.tcps_sc_unreach++;
610done:
611	SCH_UNLOCK(sch);
612}
613
614/*
615 * Build a new TCP socket structure from a syncache entry.
616 */
617static struct socket *
618syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m)
619{
620	struct inpcb *inp = NULL;
621	struct socket *so;
622	struct tcpcb *tp;
623	char *s;
624
625	INP_INFO_WLOCK_ASSERT(&tcbinfo);
626
627	/*
628	 * Ok, create the full blown connection, and set things up
629	 * as they would have been set up if we had created the
630	 * connection when the SYN arrived.  If we can't create
631	 * the connection, abort it.
632	 */
633	so = sonewconn(lso, SS_ISCONNECTED);
634	if (so == NULL) {
635		/*
636		 * Drop the connection; we will either send a RST or
637		 * have the peer retransmit its SYN again after its
638		 * RTO and try again.
639		 */
640		tcpstat.tcps_listendrop++;
641		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
642			log(LOG_DEBUG, "%s; %s: Socket create failed "
643			    "due to limits or memory shortage\n",
644			    s, __func__);
645			free(s, M_TCPLOG);
646		}
647		goto abort2;
648	}
649#ifdef MAC
650	SOCK_LOCK(so);
651	mac_socketpeer_set_from_mbuf(m, so);
652	SOCK_UNLOCK(so);
653#endif
654
655	inp = sotoinpcb(so);
656	INP_LOCK(inp);
657
658	/* Insert new socket into PCB hash list. */
659	inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
660#ifdef INET6
661	if (sc->sc_inc.inc_isipv6) {
662		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
663	} else {
664		inp->inp_vflag &= ~INP_IPV6;
665		inp->inp_vflag |= INP_IPV4;
666#endif
667		inp->inp_laddr = sc->sc_inc.inc_laddr;
668#ifdef INET6
669	}
670#endif
671	inp->inp_lport = sc->sc_inc.inc_lport;
672	if (in_pcbinshash(inp) != 0) {
673		/*
674		 * Undo the assignments above if we failed to
675		 * put the PCB on the hash lists.
676		 */
677#ifdef INET6
678		if (sc->sc_inc.inc_isipv6)
679			inp->in6p_laddr = in6addr_any;
680		else
681#endif
682			inp->inp_laddr.s_addr = INADDR_ANY;
683		inp->inp_lport = 0;
684		goto abort;
685	}
686#ifdef IPSEC
687	/* Copy old policy into new socket's. */
688	if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
689		printf("syncache_socket: could not copy policy\n");
690#endif
691#ifdef INET6
692	if (sc->sc_inc.inc_isipv6) {
693		struct inpcb *oinp = sotoinpcb(lso);
694		struct in6_addr laddr6;
695		struct sockaddr_in6 sin6;
696		/*
697		 * Inherit socket options from the listening socket.
698		 * Note that in6p_inputopts are not (and should not be)
699		 * copied, since it stores previously received options and is
700		 * used to detect if each new option is different than the
701		 * previous one and hence should be passed to a user.
702		 * If we copied in6p_inputopts, a user would not be able to
703		 * receive options just after calling the accept system call.
704		 */
705		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
706		if (oinp->in6p_outputopts)
707			inp->in6p_outputopts =
708			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
709
710		sin6.sin6_family = AF_INET6;
711		sin6.sin6_len = sizeof(sin6);
712		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
713		sin6.sin6_port = sc->sc_inc.inc_fport;
714		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
715		laddr6 = inp->in6p_laddr;
716		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
717			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
718		if (in6_pcbconnect(inp, (struct sockaddr *)&sin6,
719		    thread0.td_ucred)) {
720			inp->in6p_laddr = laddr6;
721			goto abort;
722		}
723		/* Override flowlabel from in6_pcbconnect. */
724		inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
725		inp->in6p_flowinfo |= sc->sc_flowlabel;
726	} else
727#endif
728	{
729		struct in_addr laddr;
730		struct sockaddr_in sin;
731
732		inp->inp_options = ip_srcroute(m);
733		if (inp->inp_options == NULL) {
734			inp->inp_options = sc->sc_ipopts;
735			sc->sc_ipopts = NULL;
736		}
737
738		sin.sin_family = AF_INET;
739		sin.sin_len = sizeof(sin);
740		sin.sin_addr = sc->sc_inc.inc_faddr;
741		sin.sin_port = sc->sc_inc.inc_fport;
742		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
743		laddr = inp->inp_laddr;
744		if (inp->inp_laddr.s_addr == INADDR_ANY)
745			inp->inp_laddr = sc->sc_inc.inc_laddr;
746		if (in_pcbconnect(inp, (struct sockaddr *)&sin,
747		    thread0.td_ucred)) {
748			inp->inp_laddr = laddr;
749			goto abort;
750		}
751	}
752	tp = intotcpcb(inp);
753	tp->t_state = TCPS_SYN_RECEIVED;
754	tp->iss = sc->sc_iss;
755	tp->irs = sc->sc_irs;
756	tcp_rcvseqinit(tp);
757	tcp_sendseqinit(tp);
758	tp->snd_wl1 = sc->sc_irs;
759	tp->snd_max = tp->iss + 1;
760	tp->snd_nxt = tp->iss + 1;
761	tp->rcv_up = sc->sc_irs + 1;
762	tp->rcv_wnd = sc->sc_wnd;
763	tp->rcv_adv += tp->rcv_wnd;
764	tp->last_ack_sent = tp->rcv_nxt;
765
766	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
767	if (sc->sc_flags & SCF_NOOPT)
768		tp->t_flags |= TF_NOOPT;
769	else {
770		if (sc->sc_flags & SCF_WINSCALE) {
771			tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
772			tp->snd_scale = sc->sc_requested_s_scale;
773			tp->request_r_scale = sc->sc_requested_r_scale;
774		}
775		if (sc->sc_flags & SCF_TIMESTAMP) {
776			tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
777			tp->ts_recent = sc->sc_tsreflect;
778			tp->ts_recent_age = ticks;
779			tp->ts_offset = sc->sc_tsoff;
780		}
781#ifdef TCP_SIGNATURE
782		if (sc->sc_flags & SCF_SIGNATURE)
783			tp->t_flags |= TF_SIGNATURE;
784#endif
785		if (sc->sc_flags & SCF_SACK)
786			tp->t_flags |= TF_SACK_PERMIT;
787	}
788
789	/*
790	 * Set up MSS and get cached values from tcp_hostcache.
791	 * This might overwrite some of the defaults we just set.
792	 */
793	tcp_mss(tp, sc->sc_peer_mss);
794
795	/*
796	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
797	 */
798	if (sc->sc_rxmits)
799		tp->snd_cwnd = tp->t_maxseg;
800	tcp_timer_activate(tp, TT_KEEP, tcp_keepinit);
801
802	INP_UNLOCK(inp);
803
804	tcpstat.tcps_accepts++;
805	return (so);
806
807abort:
808	INP_UNLOCK(inp);
809abort2:
810	if (so != NULL)
811		soabort(so);
812	return (NULL);
813}
814
815/*
816 * This function gets called when we receive an ACK for a
817 * socket in the LISTEN state.  We look up the connection
818 * in the syncache, and if its there, we pull it out of
819 * the cache and turn it into a full-blown connection in
820 * the SYN-RECEIVED state.
821 */
822int
823syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
824    struct socket **lsop, struct mbuf *m)
825{
826	struct syncache *sc;
827	struct syncache_head *sch;
828	struct syncache scs;
829	char *s;
830
831	/*
832	 * Global TCP locks are held because we manipulate the PCB lists
833	 * and create a new socket.
834	 */
835	INP_INFO_WLOCK_ASSERT(&tcbinfo);
836	KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK,
837	    ("%s: can handle only ACK", __func__));
838
839	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
840	SCH_LOCK_ASSERT(sch);
841	if (sc == NULL) {
842		/*
843		 * There is no syncache entry, so see if this ACK is
844		 * a returning syncookie.  To do this, first:
845		 *  A. See if this socket has had a syncache entry dropped in
846		 *     the past.  We don't want to accept a bogus syncookie
847		 *     if we've never received a SYN.
848		 *  B. check that the syncookie is valid.  If it is, then
849		 *     cobble up a fake syncache entry, and return.
850		 */
851		if (!tcp_syncookies) {
852			SCH_UNLOCK(sch);
853			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
854				log(LOG_DEBUG, "%s; %s: Spurious ACK, "
855				    "segment rejected (syncookies disabled)\n",
856				    s, __func__);
857			goto failed;
858		}
859		bzero(&scs, sizeof(scs));
860		sc = syncookie_lookup(inc, sch, &scs, to, th, *lsop);
861		SCH_UNLOCK(sch);
862		if (sc == NULL) {
863			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
864				log(LOG_DEBUG, "%s; %s: Segment failed "
865				    "SYNCOOKIE authentication, segment rejected "
866				    "(probably spoofed)\n", s, __func__);
867			goto failed;
868		}
869	} else {
870		/* Pull out the entry to unlock the bucket row. */
871		TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
872		sch->sch_length--;
873		tcp_syncache.cache_count--;
874		SCH_UNLOCK(sch);
875	}
876
877	/*
878	 * Segment validation:
879	 * ACK must match our initial sequence number + 1 (the SYN|ACK).
880	 */
881	if (th->th_ack != sc->sc_iss + 1 && sc->sc_toepcb == NULL) {
882		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
883			log(LOG_DEBUG, "%s; %s: ACK %u != ISS+1 %u, segment "
884			    "rejected\n", s, __func__, th->th_ack, sc->sc_iss);
885		goto failed;
886	}
887	/*
888	 * The SEQ must match the received initial receive sequence
889	 * number + 1 (the SYN) because we didn't ACK any data that
890	 * may have come with the SYN.
891	 */
892	if (th->th_seq != sc->sc_irs + 1 && sc->sc_toepcb == NULL) {
893		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
894			log(LOG_DEBUG, "%s; %s: SEQ %u != IRS+1 %u, segment "
895			    "rejected\n", s, __func__, th->th_seq, sc->sc_irs);
896		goto failed;
897	}
898
899	if (!(sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS)) {
900		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
901			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
902			    "segment rejected\n", s, __func__);
903		goto failed;
904	}
905	/*
906	 * If timestamps were negotiated the reflected timestamp
907	 * must be equal to what we actually sent in the SYN|ACK.
908	 */
909	if ((to->to_flags & TOF_TS) && to->to_tsecr != sc->sc_ts &&
910	    sc->sc_toepcb == NULL) {
911		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
912			log(LOG_DEBUG, "%s; %s: TSECR %u != TS %u, "
913			    "segment rejected\n",
914			    s, __func__, to->to_tsecr, sc->sc_ts);
915		goto failed;
916	}
917
918	*lsop = syncache_socket(sc, *lsop, m);
919
920	if (*lsop == NULL)
921		tcpstat.tcps_sc_aborted++;
922	else
923		tcpstat.tcps_sc_completed++;
924
925	if (sc != &scs)
926		syncache_free(sc);
927	return (1);
928failed:
929	if (sc != NULL && sc != &scs)
930		syncache_free(sc);
931	if (s != NULL)
932		free(s, M_TCPLOG);
933	*lsop = NULL;
934	return (0);
935}
936
937/*
938 * Given a LISTEN socket and an inbound SYN request, add
939 * this to the syn cache, and send back a segment:
940 *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
941 * to the source.
942 *
943 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
944 * Doing so would require that we hold onto the data and deliver it
945 * to the application.  However, if we are the target of a SYN-flood
946 * DoS attack, an attacker could send data which would eventually
947 * consume all available buffer space if it were ACKed.  By not ACKing
948 * the data, we avoid this DoS scenario.
949 */
950static void
951_syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
952    struct inpcb *inp, struct socket **lsop, struct mbuf *m,
953    struct toe_usrreqs *tu, void *toepcb)
954{
955	struct tcpcb *tp;
956	struct socket *so;
957	struct syncache *sc = NULL;
958	struct syncache_head *sch;
959	struct mbuf *ipopts = NULL;
960	u_int32_t flowtmp;
961	int win, sb_hiwat, ip_ttl, ip_tos, noopt;
962	char *s;
963#ifdef INET6
964	int autoflowlabel = 0;
965#endif
966#ifdef MAC
967	struct label *maclabel;
968#endif
969	struct syncache scs;
970
971	INP_INFO_WLOCK_ASSERT(&tcbinfo);
972	INP_LOCK_ASSERT(inp);			/* listen socket */
973	KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN,
974	    ("%s: unexpected tcp flags", __func__));
975
976	/*
977	 * Combine all so/tp operations very early to drop the INP lock as
978	 * soon as possible.
979	 */
980	so = *lsop;
981	tp = sototcpcb(so);
982
983#ifdef INET6
984	if (inc->inc_isipv6 &&
985	    (inp->in6p_flags & IN6P_AUTOFLOWLABEL))
986		autoflowlabel = 1;
987#endif
988	ip_ttl = inp->inp_ip_ttl;
989	ip_tos = inp->inp_ip_tos;
990	win = sbspace(&so->so_rcv);
991	sb_hiwat = so->so_rcv.sb_hiwat;
992	noopt = (tp->t_flags & TF_NOOPT);
993
994	so = NULL;
995	tp = NULL;
996
997#ifdef MAC
998	if (mac_syncache_init(&maclabel) != 0) {
999		INP_UNLOCK(inp);
1000		INP_INFO_WUNLOCK(&tcbinfo);
1001		goto done;
1002	} else
1003		mac_syncache_create(maclabel, inp);
1004#endif
1005	INP_UNLOCK(inp);
1006	INP_INFO_WUNLOCK(&tcbinfo);
1007
1008	/*
1009	 * Remember the IP options, if any.
1010	 */
1011#ifdef INET6
1012	if (!inc->inc_isipv6)
1013#endif
1014		ipopts = ip_srcroute(m);
1015
1016	/*
1017	 * See if we already have an entry for this connection.
1018	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
1019	 *
1020	 * XXX: should the syncache be re-initialized with the contents
1021	 * of the new SYN here (which may have different options?)
1022	 *
1023	 * XXX: We do not check the sequence number to see if this is a
1024	 * real retransmit or a new connection attempt.  The question is
1025	 * how to handle such a case; either ignore it as spoofed, or
1026	 * drop the current entry and create a new one?
1027	 */
1028	sc = syncache_lookup(inc, &sch);	/* returns locked entry */
1029	SCH_LOCK_ASSERT(sch);
1030	if (sc != NULL) {
1031#ifndef DISABLE_TCP_OFFLOAD
1032		if (sc->sc_tu)
1033			sc->sc_tu->tu_syncache_event(SC_ENTRY_PRESENT,
1034			    sc->sc_toepcb);
1035#endif
1036		tcpstat.tcps_sc_dupsyn++;
1037		if (ipopts) {
1038			/*
1039			 * If we were remembering a previous source route,
1040			 * forget it and use the new one we've been given.
1041			 */
1042			if (sc->sc_ipopts)
1043				(void) m_free(sc->sc_ipopts);
1044			sc->sc_ipopts = ipopts;
1045		}
1046		/*
1047		 * Update timestamp if present.
1048		 */
1049		if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS))
1050			sc->sc_tsreflect = to->to_tsval;
1051		else
1052			sc->sc_flags &= ~SCF_TIMESTAMP;
1053#ifdef MAC
1054		/*
1055		 * Since we have already unconditionally allocated label
1056		 * storage, free it up.  The syncache entry will already
1057		 * have an initialized label we can use.
1058		 */
1059		mac_syncache_destroy(&maclabel);
1060		KASSERT(sc->sc_label != NULL,
1061		    ("%s: label not initialized", __func__));
1062#endif
1063		/* Retransmit SYN|ACK and reset retransmit count. */
1064		if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) {
1065			log(LOG_DEBUG, "%s; %s: Received duplicate SYN, "
1066			    "resetting timer and retransmitting SYN|ACK\n",
1067			    s, __func__);
1068			free(s, M_TCPLOG);
1069		}
1070		if ((sc->sc_toepcb == NULL) && syncache_respond(sc) == 0) {
1071			sc->sc_rxmits = 0;
1072			syncache_timeout(sc, sch, 1);
1073			tcpstat.tcps_sndacks++;
1074			tcpstat.tcps_sndtotal++;
1075		}
1076		SCH_UNLOCK(sch);
1077		goto done;
1078	}
1079
1080	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
1081	if (sc == NULL) {
1082		/*
1083		 * The zone allocator couldn't provide more entries.
1084		 * Treat this as if the cache was full; drop the oldest
1085		 * entry and insert the new one.
1086		 */
1087		tcpstat.tcps_sc_zonefail++;
1088		if ((sc = TAILQ_LAST(&sch->sch_bucket, sch_head)) != NULL)
1089			syncache_drop(sc, sch);
1090		sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
1091		if (sc == NULL) {
1092			if (tcp_syncookies) {
1093				bzero(&scs, sizeof(scs));
1094				sc = &scs;
1095			} else {
1096				SCH_UNLOCK(sch);
1097				if (ipopts)
1098					(void) m_free(ipopts);
1099				goto done;
1100			}
1101		}
1102	}
1103
1104	/*
1105	 * Fill in the syncache values.
1106	 */
1107#ifdef MAC
1108	sc->sc_label = maclabel;
1109#endif
1110	sc->sc_ipopts = ipopts;
1111	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1112#ifdef INET6
1113	if (!inc->inc_isipv6)
1114#endif
1115	{
1116		sc->sc_ip_tos = ip_tos;
1117		sc->sc_ip_ttl = ip_ttl;
1118	}
1119#ifndef DISABLE_TCP_OFFLOAD
1120	sc->sc_tu = tu;
1121	sc->sc_toepcb = toepcb;
1122#endif
1123	sc->sc_irs = th->th_seq;
1124	sc->sc_iss = arc4random();
1125	sc->sc_flags = 0;
1126	sc->sc_flowlabel = 0;
1127
1128	/*
1129	 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
1130	 * win was derived from socket earlier in the function.
1131	 */
1132	win = imax(win, 0);
1133	win = imin(win, TCP_MAXWIN);
1134	sc->sc_wnd = win;
1135
1136	if (tcp_do_rfc1323) {
1137		/*
1138		 * A timestamp received in a SYN makes
1139		 * it ok to send timestamp requests and replies.
1140		 */
1141		if (to->to_flags & TOF_TS) {
1142			sc->sc_tsreflect = to->to_tsval;
1143			sc->sc_ts = ticks;
1144			sc->sc_flags |= SCF_TIMESTAMP;
1145		}
1146		if (to->to_flags & TOF_SCALE) {
1147			int wscale = 0;
1148
1149			/*
1150			 * Pick the smallest possible scaling factor that
1151			 * will still allow us to scale up to sb_max, aka
1152			 * kern.ipc.maxsockbuf.
1153			 *
1154			 * We do this because there are broken firewalls that
1155			 * will corrupt the window scale option, leading to
1156			 * the other endpoint believing that our advertised
1157			 * window is unscaled.  At scale factors larger than
1158			 * 5 the unscaled window will drop below 1500 bytes,
1159			 * leading to serious problems when traversing these
1160			 * broken firewalls.
1161			 *
1162			 * With the default maxsockbuf of 256K, a scale factor
1163			 * of 3 will be chosen by this algorithm.  Those who
1164			 * choose a larger maxsockbuf should watch out
1165			 * for the compatiblity problems mentioned above.
1166			 *
1167			 * RFC1323: The Window field in a SYN (i.e., a <SYN>
1168			 * or <SYN,ACK>) segment itself is never scaled.
1169			 */
1170			while (wscale < TCP_MAX_WINSHIFT &&
1171			    (TCP_MAXWIN << wscale) < sb_max)
1172				wscale++;
1173			sc->sc_requested_r_scale = wscale;
1174			sc->sc_requested_s_scale = to->to_wscale;
1175			sc->sc_flags |= SCF_WINSCALE;
1176		}
1177	}
1178#ifdef TCP_SIGNATURE
1179	/*
1180	 * If listening socket requested TCP digests, and received SYN
1181	 * contains the option, flag this in the syncache so that
1182	 * syncache_respond() will do the right thing with the SYN+ACK.
1183	 * XXX: Currently we always record the option by default and will
1184	 * attempt to use it in syncache_respond().
1185	 */
1186	if (to->to_flags & TOF_SIGNATURE)
1187		sc->sc_flags |= SCF_SIGNATURE;
1188#endif
1189	if (to->to_flags & TOF_SACKPERM)
1190		sc->sc_flags |= SCF_SACK;
1191	if (to->to_flags & TOF_MSS)
1192		sc->sc_peer_mss = to->to_mss;	/* peer mss may be zero */
1193	if (noopt)
1194		sc->sc_flags |= SCF_NOOPT;
1195
1196	if (tcp_syncookies) {
1197		syncookie_generate(sch, sc, &flowtmp);
1198#ifdef INET6
1199		if (autoflowlabel)
1200			sc->sc_flowlabel = flowtmp;
1201#endif
1202	} else {
1203#ifdef INET6
1204		if (autoflowlabel)
1205			sc->sc_flowlabel =
1206			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1207#endif
1208	}
1209	SCH_UNLOCK(sch);
1210
1211	/*
1212	 * Do a standard 3-way handshake.
1213	 */
1214	if (sc->sc_toepcb || syncache_respond(sc) == 0) {
1215		if (tcp_syncookies && tcp_syncookiesonly && sc != &scs)
1216			syncache_free(sc);
1217		else if (sc != &scs)
1218			syncache_insert(sc, sch);   /* locks and unlocks sch */
1219		tcpstat.tcps_sndacks++;
1220		tcpstat.tcps_sndtotal++;
1221	} else {
1222		if (sc != &scs)
1223			syncache_free(sc);
1224		tcpstat.tcps_sc_dropped++;
1225	}
1226
1227done:
1228#ifdef MAC
1229	if (sc == &scs)
1230		mac_syncache_destroy(&maclabel);
1231#endif
1232	if (m) {
1233
1234		*lsop = NULL;
1235		m_freem(m);
1236	}
1237	return;
1238}
1239
1240static int
1241syncache_respond(struct syncache *sc)
1242{
1243	struct ip *ip = NULL;
1244	struct mbuf *m;
1245	struct tcphdr *th;
1246	int optlen, error;
1247	u_int16_t hlen, tlen, mssopt;
1248	struct tcpopt to;
1249#ifdef INET6
1250	struct ip6_hdr *ip6 = NULL;
1251#endif
1252
1253	hlen =
1254#ifdef INET6
1255	       (sc->sc_inc.inc_isipv6) ? sizeof(struct ip6_hdr) :
1256#endif
1257		sizeof(struct ip);
1258	tlen = hlen + sizeof(struct tcphdr);
1259
1260	/* Determine MSS we advertize to other end of connection. */
1261	mssopt = tcp_mssopt(&sc->sc_inc);
1262	if (sc->sc_peer_mss)
1263		mssopt = max( min(sc->sc_peer_mss, mssopt), tcp_minmss);
1264
1265	/* XXX: Assume that the entire packet will fit in a header mbuf. */
1266	KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN,
1267	    ("syncache: mbuf too small"));
1268
1269	/* Create the IP+TCP header from scratch. */
1270	m = m_gethdr(M_DONTWAIT, MT_DATA);
1271	if (m == NULL)
1272		return (ENOBUFS);
1273#ifdef MAC
1274	mac_syncache_create_mbuf(sc->sc_label, m);
1275#endif
1276	m->m_data += max_linkhdr;
1277	m->m_len = tlen;
1278	m->m_pkthdr.len = tlen;
1279	m->m_pkthdr.rcvif = NULL;
1280
1281#ifdef INET6
1282	if (sc->sc_inc.inc_isipv6) {
1283		ip6 = mtod(m, struct ip6_hdr *);
1284		ip6->ip6_vfc = IPV6_VERSION;
1285		ip6->ip6_nxt = IPPROTO_TCP;
1286		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1287		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1288		ip6->ip6_plen = htons(tlen - hlen);
1289		/* ip6_hlim is set after checksum */
1290		ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
1291		ip6->ip6_flow |= sc->sc_flowlabel;
1292
1293		th = (struct tcphdr *)(ip6 + 1);
1294	} else
1295#endif
1296	{
1297		ip = mtod(m, struct ip *);
1298		ip->ip_v = IPVERSION;
1299		ip->ip_hl = sizeof(struct ip) >> 2;
1300		ip->ip_len = tlen;
1301		ip->ip_id = 0;
1302		ip->ip_off = 0;
1303		ip->ip_sum = 0;
1304		ip->ip_p = IPPROTO_TCP;
1305		ip->ip_src = sc->sc_inc.inc_laddr;
1306		ip->ip_dst = sc->sc_inc.inc_faddr;
1307		ip->ip_ttl = sc->sc_ip_ttl;
1308		ip->ip_tos = sc->sc_ip_tos;
1309
1310		/*
1311		 * See if we should do MTU discovery.  Route lookups are
1312		 * expensive, so we will only unset the DF bit if:
1313		 *
1314		 *	1) path_mtu_discovery is disabled
1315		 *	2) the SCF_UNREACH flag has been set
1316		 */
1317		if (path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1318		       ip->ip_off |= IP_DF;
1319
1320		th = (struct tcphdr *)(ip + 1);
1321	}
1322	th->th_sport = sc->sc_inc.inc_lport;
1323	th->th_dport = sc->sc_inc.inc_fport;
1324
1325	th->th_seq = htonl(sc->sc_iss);
1326	th->th_ack = htonl(sc->sc_irs + 1);
1327	th->th_off = sizeof(struct tcphdr) >> 2;
1328	th->th_x2 = 0;
1329	th->th_flags = TH_SYN|TH_ACK;
1330	th->th_win = htons(sc->sc_wnd);
1331	th->th_urp = 0;
1332
1333	/* Tack on the TCP options. */
1334	if ((sc->sc_flags & SCF_NOOPT) == 0) {
1335		to.to_flags = 0;
1336
1337		to.to_mss = mssopt;
1338		to.to_flags = TOF_MSS;
1339		if (sc->sc_flags & SCF_WINSCALE) {
1340			to.to_wscale = sc->sc_requested_r_scale;
1341			to.to_flags |= TOF_SCALE;
1342		}
1343		if (sc->sc_flags & SCF_TIMESTAMP) {
1344			/* Virgin timestamp or TCP cookie enhanced one. */
1345			to.to_tsval = sc->sc_ts;
1346			to.to_tsecr = sc->sc_tsreflect;
1347			to.to_flags |= TOF_TS;
1348		}
1349		if (sc->sc_flags & SCF_SACK)
1350			to.to_flags |= TOF_SACKPERM;
1351#ifdef TCP_SIGNATURE
1352		if (sc->sc_flags & SCF_SIGNATURE)
1353			to.to_flags |= TOF_SIGNATURE;
1354#endif
1355		optlen = tcp_addoptions(&to, (u_char *)(th + 1));
1356
1357		/* Adjust headers by option size. */
1358		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1359		m->m_len += optlen;
1360		m->m_pkthdr.len += optlen;
1361
1362#ifdef TCP_SIGNATURE
1363		if (sc->sc_flags & SCF_SIGNATURE)
1364			tcp_signature_compute(m, sizeof(struct ip), 0, optlen,
1365			    to.to_signature, IPSEC_DIR_OUTBOUND);
1366#endif
1367#ifdef INET6
1368		if (sc->sc_inc.inc_isipv6)
1369			ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen);
1370		else
1371#endif
1372			ip->ip_len += optlen;
1373	} else
1374		optlen = 0;
1375
1376#ifdef INET6
1377	if (sc->sc_inc.inc_isipv6) {
1378		th->th_sum = 0;
1379		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen,
1380				       tlen + optlen - hlen);
1381		ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
1382		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1383	} else
1384#endif
1385	{
1386		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1387		    htons(tlen + optlen - hlen + IPPROTO_TCP));
1388		m->m_pkthdr.csum_flags = CSUM_TCP;
1389		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1390		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
1391	}
1392	return (error);
1393}
1394
1395void
1396syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1397    struct inpcb *inp, struct socket **lsop, struct mbuf *m)
1398{
1399	_syncache_add(inc, to, th, inp, lsop, m, NULL, NULL);
1400}
1401
1402void
1403syncache_offload_add(struct in_conninfo *inc, struct tcpopt *to,
1404    struct tcphdr *th, struct inpcb *inp, struct socket **lsop,
1405    struct toe_usrreqs *tu, void *toepcb)
1406{
1407	_syncache_add(inc, to, th, inp, lsop, NULL, tu, toepcb);
1408}
1409
1410/*
1411 * The purpose of SYN cookies is to avoid keeping track of all SYN's we
1412 * receive and to be able to handle SYN floods from bogus source addresses
1413 * (where we will never receive any reply).  SYN floods try to exhaust all
1414 * our memory and available slots in the SYN cache table to cause a denial
1415 * of service to legitimate users of the local host.
1416 *
1417 * The idea of SYN cookies is to encode and include all necessary information
1418 * about the connection setup state within the SYN-ACK we send back and thus
1419 * to get along without keeping any local state until the ACK to the SYN-ACK
1420 * arrives (if ever).  Everything we need to know should be available from
1421 * the information we encoded in the SYN-ACK.
1422 *
1423 * More information about the theory behind SYN cookies and its first
1424 * discussion and specification can be found at:
1425 *  http://cr.yp.to/syncookies.html    (overview)
1426 *  http://cr.yp.to/syncookies/archive (gory details)
1427 *
1428 * This implementation extends the orginal idea and first implementation
1429 * of FreeBSD by using not only the initial sequence number field to store
1430 * information but also the timestamp field if present.  This way we can
1431 * keep track of the entire state we need to know to recreate the session in
1432 * its original form.  Almost all TCP speakers implement RFC1323 timestamps
1433 * these days.  For those that do not we still have to live with the known
1434 * shortcomings of the ISN only SYN cookies.
1435 *
1436 * Cookie layers:
1437 *
1438 * Initial sequence number we send:
1439 * 31|................................|0
1440 *    DDDDDDDDDDDDDDDDDDDDDDDDDMMMRRRP
1441 *    D = MD5 Digest (first dword)
1442 *    M = MSS index
1443 *    R = Rotation of secret
1444 *    P = Odd or Even secret
1445 *
1446 * The MD5 Digest is computed with over following parameters:
1447 *  a) randomly rotated secret
1448 *  b) struct in_conninfo containing the remote/local ip/port (IPv4&IPv6)
1449 *  c) the received initial sequence number from remote host
1450 *  d) the rotation offset and odd/even bit
1451 *
1452 * Timestamp we send:
1453 * 31|................................|0
1454 *    DDDDDDDDDDDDDDDDDDDDDDSSSSRRRRA5
1455 *    D = MD5 Digest (third dword) (only as filler)
1456 *    S = Requested send window scale
1457 *    R = Requested receive window scale
1458 *    A = SACK allowed
1459 *    5 = TCP-MD5 enabled (not implemented yet)
1460 *    XORed with MD5 Digest (forth dword)
1461 *
1462 * The timestamp isn't cryptographically secure and doesn't need to be.
1463 * The double use of the MD5 digest dwords ties it to a specific remote/
1464 * local host/port, remote initial sequence number and our local time
1465 * limited secret.  A received timestamp is reverted (XORed) and then
1466 * the contained MD5 dword is compared to the computed one to ensure the
1467 * timestamp belongs to the SYN-ACK we sent.  The other parameters may
1468 * have been tampered with but this isn't different from supplying bogus
1469 * values in the SYN in the first place.
1470 *
1471 * Some problems with SYN cookies remain however:
1472 * Consider the problem of a recreated (and retransmitted) cookie.  If the
1473 * original SYN was accepted, the connection is established.  The second
1474 * SYN is inflight, and if it arrives with an ISN that falls within the
1475 * receive window, the connection is killed.
1476 *
1477 * Notes:
1478 * A heuristic to determine when to accept syn cookies is not necessary.
1479 * An ACK flood would cause the syncookie verification to be attempted,
1480 * but a SYN flood causes syncookies to be generated.  Both are of equal
1481 * cost, so there's no point in trying to optimize the ACK flood case.
1482 * Also, if you don't process certain ACKs for some reason, then all someone
1483 * would have to do is launch a SYN and ACK flood at the same time, which
1484 * would stop cookie verification and defeat the entire purpose of syncookies.
1485 */
1486static int tcp_sc_msstab[] = { 0, 256, 468, 536, 996, 1452, 1460, 8960 };
1487
1488static void
1489syncookie_generate(struct syncache_head *sch, struct syncache *sc,
1490    u_int32_t *flowlabel)
1491{
1492	MD5_CTX ctx;
1493	u_int32_t md5_buffer[MD5_DIGEST_LENGTH / sizeof(u_int32_t)];
1494	u_int32_t data;
1495	u_int32_t *secbits;
1496	u_int off, pmss, mss;
1497	int i;
1498
1499	SCH_LOCK_ASSERT(sch);
1500
1501	/* Which of the two secrets to use. */
1502	secbits = sch->sch_oddeven ?
1503			sch->sch_secbits_odd : sch->sch_secbits_even;
1504
1505	/* Reseed secret if too old. */
1506	if (sch->sch_reseed < time_uptime) {
1507		sch->sch_oddeven = sch->sch_oddeven ? 0 : 1;	/* toggle */
1508		secbits = sch->sch_oddeven ?
1509				sch->sch_secbits_odd : sch->sch_secbits_even;
1510		for (i = 0; i < SYNCOOKIE_SECRET_SIZE; i++)
1511			secbits[i] = arc4random();
1512		sch->sch_reseed = time_uptime + SYNCOOKIE_LIFETIME;
1513	}
1514
1515	/* Secret rotation offset. */
1516	off = sc->sc_iss & 0x7;			/* iss was randomized before */
1517
1518	/* Maximum segment size calculation. */
1519	pmss = max( min(sc->sc_peer_mss, tcp_mssopt(&sc->sc_inc)), tcp_minmss);
1520	for (mss = sizeof(tcp_sc_msstab) / sizeof(int) - 1; mss > 0; mss--)
1521		if (tcp_sc_msstab[mss] <= pmss)
1522			break;
1523
1524	/* Fold parameters and MD5 digest into the ISN we will send. */
1525	data = sch->sch_oddeven;/* odd or even secret, 1 bit */
1526	data |= off << 1;	/* secret offset, derived from iss, 3 bits */
1527	data |= mss << 4;	/* mss, 3 bits */
1528
1529	MD5Init(&ctx);
1530	MD5Update(&ctx, ((u_int8_t *)secbits) + off,
1531	    SYNCOOKIE_SECRET_SIZE * sizeof(*secbits) - off);
1532	MD5Update(&ctx, secbits, off);
1533	MD5Update(&ctx, &sc->sc_inc, sizeof(sc->sc_inc));
1534	MD5Update(&ctx, &sc->sc_irs, sizeof(sc->sc_irs));
1535	MD5Update(&ctx, &data, sizeof(data));
1536	MD5Final((u_int8_t *)&md5_buffer, &ctx);
1537
1538	data |= (md5_buffer[0] << 7);
1539	sc->sc_iss = data;
1540
1541#ifdef INET6
1542	*flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1543#endif
1544
1545	/* Additional parameters are stored in the timestamp if present. */
1546	if (sc->sc_flags & SCF_TIMESTAMP) {
1547		data =  ((sc->sc_flags & SCF_SIGNATURE) ? 1 : 0); /* TCP-MD5, 1 bit */
1548		data |= ((sc->sc_flags & SCF_SACK) ? 1 : 0) << 1; /* SACK, 1 bit */
1549		data |= sc->sc_requested_s_scale << 2;  /* SWIN scale, 4 bits */
1550		data |= sc->sc_requested_r_scale << 6;  /* RWIN scale, 4 bits */
1551		data |= md5_buffer[2] << 10;		/* more digest bits */
1552		data ^= md5_buffer[3];
1553		sc->sc_ts = data;
1554		sc->sc_tsoff = data - ticks;		/* after XOR */
1555	}
1556
1557	tcpstat.tcps_sc_sendcookie++;
1558	return;
1559}
1560
1561static struct syncache *
1562syncookie_lookup(struct in_conninfo *inc, struct syncache_head *sch,
1563    struct syncache *sc, struct tcpopt *to, struct tcphdr *th,
1564    struct socket *so)
1565{
1566	MD5_CTX ctx;
1567	u_int32_t md5_buffer[MD5_DIGEST_LENGTH / sizeof(u_int32_t)];
1568	u_int32_t data = 0;
1569	u_int32_t *secbits;
1570	tcp_seq ack, seq;
1571	int off, mss, wnd, flags;
1572
1573	SCH_LOCK_ASSERT(sch);
1574
1575	/*
1576	 * Pull information out of SYN-ACK/ACK and
1577	 * revert sequence number advances.
1578	 */
1579	ack = th->th_ack - 1;
1580	seq = th->th_seq - 1;
1581	off = (ack >> 1) & 0x7;
1582	mss = (ack >> 4) & 0x7;
1583	flags = ack & 0x7f;
1584
1585	/* Which of the two secrets to use. */
1586	secbits = (flags & 0x1) ? sch->sch_secbits_odd : sch->sch_secbits_even;
1587
1588	/*
1589	 * The secret wasn't updated for the lifetime of a syncookie,
1590	 * so this SYN-ACK/ACK is either too old (replay) or totally bogus.
1591	 */
1592	if (sch->sch_reseed < time_uptime) {
1593		return (NULL);
1594	}
1595
1596	/* Recompute the digest so we can compare it. */
1597	MD5Init(&ctx);
1598	MD5Update(&ctx, ((u_int8_t *)secbits) + off,
1599	    SYNCOOKIE_SECRET_SIZE * sizeof(*secbits) - off);
1600	MD5Update(&ctx, secbits, off);
1601	MD5Update(&ctx, inc, sizeof(*inc));
1602	MD5Update(&ctx, &seq, sizeof(seq));
1603	MD5Update(&ctx, &flags, sizeof(flags));
1604	MD5Final((u_int8_t *)&md5_buffer, &ctx);
1605
1606	/* Does the digest part of or ACK'ed ISS match? */
1607	if ((ack & (~0x7f)) != (md5_buffer[0] << 7))
1608		return (NULL);
1609
1610	/* Does the digest part of our reflected timestamp match? */
1611	if (to->to_flags & TOF_TS) {
1612		data = md5_buffer[3] ^ to->to_tsecr;
1613		if ((data & (~0x3ff)) != (md5_buffer[2] << 10))
1614			return (NULL);
1615	}
1616
1617	/* Fill in the syncache values. */
1618	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1619	sc->sc_ipopts = NULL;
1620
1621	sc->sc_irs = seq;
1622	sc->sc_iss = ack;
1623
1624#ifdef INET6
1625	if (inc->inc_isipv6) {
1626		if (sotoinpcb(so)->in6p_flags & IN6P_AUTOFLOWLABEL)
1627			sc->sc_flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1628	} else
1629#endif
1630	{
1631		sc->sc_ip_ttl = sotoinpcb(so)->inp_ip_ttl;
1632		sc->sc_ip_tos = sotoinpcb(so)->inp_ip_tos;
1633	}
1634
1635	/* Additional parameters that were encoded in the timestamp. */
1636	if (data) {
1637		sc->sc_flags |= SCF_TIMESTAMP;
1638		sc->sc_tsreflect = to->to_tsval;
1639		sc->sc_ts = to->to_tsecr;
1640		sc->sc_tsoff = to->to_tsecr - ticks;
1641		sc->sc_flags |= (data & 0x1) ? SCF_SIGNATURE : 0;
1642		sc->sc_flags |= ((data >> 1) & 0x1) ? SCF_SACK : 0;
1643		sc->sc_requested_s_scale = min((data >> 2) & 0xf,
1644		    TCP_MAX_WINSHIFT);
1645		sc->sc_requested_r_scale = min((data >> 6) & 0xf,
1646		    TCP_MAX_WINSHIFT);
1647		if (sc->sc_requested_s_scale || sc->sc_requested_r_scale)
1648			sc->sc_flags |= SCF_WINSCALE;
1649	} else
1650		sc->sc_flags |= SCF_NOOPT;
1651
1652	wnd = sbspace(&so->so_rcv);
1653	wnd = imax(wnd, 0);
1654	wnd = imin(wnd, TCP_MAXWIN);
1655	sc->sc_wnd = wnd;
1656
1657	sc->sc_rxmits = 0;
1658	sc->sc_peer_mss = tcp_sc_msstab[mss];
1659
1660	tcpstat.tcps_sc_recvcookie++;
1661	return (sc);
1662}
1663
1664/*
1665 * Returns the current number of syncache entries.  This number
1666 * will probably change before you get around to calling
1667 * syncache_pcblist.
1668 */
1669
1670int
1671syncache_pcbcount(void)
1672{
1673	struct syncache_head *sch;
1674	int count, i;
1675
1676	for (count = 0, i = 0; i < tcp_syncache.hashsize; i++) {
1677		/* No need to lock for a read. */
1678		sch = &tcp_syncache.hashbase[i];
1679		count += sch->sch_length;
1680	}
1681	return count;
1682}
1683
1684/*
1685 * Exports the syncache entries to userland so that netstat can display
1686 * them alongside the other sockets.  This function is intended to be
1687 * called only from tcp_pcblist.
1688 *
1689 * Due to concurrency on an active system, the number of pcbs exported
1690 * may have no relation to max_pcbs.  max_pcbs merely indicates the
1691 * amount of space the caller allocated for this function to use.
1692 */
1693int
1694syncache_pcblist(struct sysctl_req *req, int max_pcbs, int *pcbs_exported)
1695{
1696	struct xtcpcb xt;
1697	struct syncache *sc;
1698	struct syncache_head *sch;
1699	int count, error, i;
1700
1701	for (count = 0, error = 0, i = 0; i < tcp_syncache.hashsize; i++) {
1702		sch = &tcp_syncache.hashbase[i];
1703		SCH_LOCK(sch);
1704		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
1705			if (count >= max_pcbs) {
1706				SCH_UNLOCK(sch);
1707				goto exit;
1708			}
1709			bzero(&xt, sizeof(xt));
1710			xt.xt_len = sizeof(xt);
1711			if (sc->sc_inc.inc_isipv6)
1712				xt.xt_inp.inp_vflag = INP_IPV6;
1713			else
1714				xt.xt_inp.inp_vflag = INP_IPV4;
1715			bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc, sizeof (struct in_conninfo));
1716			xt.xt_tp.t_inpcb = &xt.xt_inp;
1717			xt.xt_tp.t_state = TCPS_SYN_RECEIVED;
1718			xt.xt_socket.xso_protocol = IPPROTO_TCP;
1719			xt.xt_socket.xso_len = sizeof (struct xsocket);
1720			xt.xt_socket.so_type = SOCK_STREAM;
1721			xt.xt_socket.so_state = SS_ISCONNECTING;
1722			error = SYSCTL_OUT(req, &xt, sizeof xt);
1723			if (error) {
1724				SCH_UNLOCK(sch);
1725				goto exit;
1726			}
1727			count++;
1728		}
1729		SCH_UNLOCK(sch);
1730	}
1731exit:
1732	*pcbs_exported = count;
1733	return error;
1734}
1735