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