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