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