xref: /freebsd/sys/netinet/tcp_syncache.c (revision 0bee4d631a16bddf55b44beff1bba5fab1c08f11)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2001 McAfee, Inc.
5  * Copyright (c) 2006,2013 Andre Oppermann, Internet Business Solutions AG
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Jonathan Lemon
9  * and McAfee Research, the Security Research Division of McAfee, Inc. under
10  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
11  * DARPA CHATS research program. [2001 McAfee, Inc.]
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41 #include "opt_pcbgroup.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/hash.h>
46 #include <sys/refcount.h>
47 #include <sys/kernel.h>
48 #include <sys/sysctl.h>
49 #include <sys/limits.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/malloc.h>
53 #include <sys/mbuf.h>
54 #include <sys/proc.h>		/* for proc0 declaration */
55 #include <sys/random.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <sys/syslog.h>
59 #include <sys/ucred.h>
60 
61 #include <sys/md5.h>
62 #include <crypto/siphash/siphash.h>
63 
64 #include <vm/uma.h>
65 
66 #include <net/if.h>
67 #include <net/if_var.h>
68 #include <net/route.h>
69 #include <net/vnet.h>
70 
71 #include <netinet/in.h>
72 #include <netinet/in_kdtrace.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/in_var.h>
76 #include <netinet/in_pcb.h>
77 #include <netinet/ip_var.h>
78 #include <netinet/ip_options.h>
79 #ifdef INET6
80 #include <netinet/ip6.h>
81 #include <netinet/icmp6.h>
82 #include <netinet6/nd6.h>
83 #include <netinet6/ip6_var.h>
84 #include <netinet6/in6_pcb.h>
85 #endif
86 #include <netinet/tcp.h>
87 #include <netinet/tcp_fastopen.h>
88 #include <netinet/tcp_fsm.h>
89 #include <netinet/tcp_seq.h>
90 #include <netinet/tcp_timer.h>
91 #include <netinet/tcp_var.h>
92 #include <netinet/tcp_syncache.h>
93 #ifdef INET6
94 #include <netinet6/tcp6_var.h>
95 #endif
96 #ifdef TCP_OFFLOAD
97 #include <netinet/toecore.h>
98 #endif
99 
100 #include <netipsec/ipsec_support.h>
101 
102 #include <machine/in_cksum.h>
103 
104 #include <security/mac/mac_framework.h>
105 
106 VNET_DEFINE_STATIC(int, tcp_syncookies) = 1;
107 #define	V_tcp_syncookies		VNET(tcp_syncookies)
108 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_VNET | CTLFLAG_RW,
109     &VNET_NAME(tcp_syncookies), 0,
110     "Use TCP SYN cookies if the syncache overflows");
111 
112 VNET_DEFINE_STATIC(int, tcp_syncookiesonly) = 0;
113 #define	V_tcp_syncookiesonly		VNET(tcp_syncookiesonly)
114 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies_only, CTLFLAG_VNET | CTLFLAG_RW,
115     &VNET_NAME(tcp_syncookiesonly), 0,
116     "Use only TCP SYN cookies");
117 
118 VNET_DEFINE_STATIC(int, functions_inherit_listen_socket_stack) = 1;
119 #define V_functions_inherit_listen_socket_stack \
120     VNET(functions_inherit_listen_socket_stack)
121 SYSCTL_INT(_net_inet_tcp, OID_AUTO, functions_inherit_listen_socket_stack,
122     CTLFLAG_VNET | CTLFLAG_RW,
123     &VNET_NAME(functions_inherit_listen_socket_stack), 0,
124     "Inherit listen socket's stack");
125 
126 #ifdef TCP_OFFLOAD
127 #define ADDED_BY_TOE(sc) ((sc)->sc_tod != NULL)
128 #endif
129 
130 static void	 syncache_drop(struct syncache *, struct syncache_head *);
131 static void	 syncache_free(struct syncache *);
132 static void	 syncache_insert(struct syncache *, struct syncache_head *);
133 static int	 syncache_respond(struct syncache *, const struct mbuf *, int);
134 static struct	 socket *syncache_socket(struct syncache *, struct socket *,
135 		    struct mbuf *m);
136 static void	 syncache_timeout(struct syncache *sc, struct syncache_head *sch,
137 		    int docallout);
138 static void	 syncache_timer(void *);
139 
140 static uint32_t	 syncookie_mac(struct in_conninfo *, tcp_seq, uint8_t,
141 		    uint8_t *, uintptr_t);
142 static tcp_seq	 syncookie_generate(struct syncache_head *, struct syncache *);
143 static struct syncache
144 		*syncookie_lookup(struct in_conninfo *, struct syncache_head *,
145 		    struct syncache *, struct tcphdr *, struct tcpopt *,
146 		    struct socket *);
147 static void	 syncookie_reseed(void *);
148 #ifdef INVARIANTS
149 static int	 syncookie_cmp(struct in_conninfo *inc, struct syncache_head *sch,
150 		    struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
151 		    struct socket *lso);
152 #endif
153 
154 /*
155  * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
156  * 3 retransmits corresponds to a timeout with default values of
157  * tcp_rexmit_initial * (             1 +
158  *                       tcp_backoff[1] +
159  *                       tcp_backoff[2] +
160  *                       tcp_backoff[3]) + 3 * tcp_rexmit_slop,
161  * 1000 ms * (1 + 2 + 4 + 8) +  3 * 200 ms = 15600 ms,
162  * the odds are that the user has given up attempting to connect by then.
163  */
164 #define SYNCACHE_MAXREXMTS		3
165 
166 /* Arbitrary values */
167 #define TCP_SYNCACHE_HASHSIZE		512
168 #define TCP_SYNCACHE_BUCKETLIMIT	30
169 
170 VNET_DEFINE_STATIC(struct tcp_syncache, tcp_syncache);
171 #define	V_tcp_syncache			VNET(tcp_syncache)
172 
173 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0,
174     "TCP SYN cache");
175 
176 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_VNET | CTLFLAG_RDTUN,
177     &VNET_NAME(tcp_syncache.bucket_limit), 0,
178     "Per-bucket hash limit for syncache");
179 
180 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_VNET | CTLFLAG_RDTUN,
181     &VNET_NAME(tcp_syncache.cache_limit), 0,
182     "Overall entry limit for syncache");
183 
184 SYSCTL_UMA_CUR(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_VNET,
185     &VNET_NAME(tcp_syncache.zone), "Current number of entries in syncache");
186 
187 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN,
188     &VNET_NAME(tcp_syncache.hashsize), 0,
189     "Size of TCP syncache hashtable");
190 
191 static int
192 sysctl_net_inet_tcp_syncache_rexmtlimit_check(SYSCTL_HANDLER_ARGS)
193 {
194 	int error;
195 	u_int new;
196 
197 	new = V_tcp_syncache.rexmt_limit;
198 	error = sysctl_handle_int(oidp, &new, 0, req);
199 	if ((error == 0) && (req->newptr != NULL)) {
200 		if (new > TCP_MAXRXTSHIFT)
201 			error = EINVAL;
202 		else
203 			V_tcp_syncache.rexmt_limit = new;
204 	}
205 	return (error);
206 }
207 
208 SYSCTL_PROC(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit,
209     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW,
210     &VNET_NAME(tcp_syncache.rexmt_limit), 0,
211     sysctl_net_inet_tcp_syncache_rexmtlimit_check, "UI",
212     "Limit on SYN/ACK retransmissions");
213 
214 VNET_DEFINE(int, tcp_sc_rst_sock_fail) = 1;
215 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rst_on_sock_fail,
216     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_sc_rst_sock_fail), 0,
217     "Send reset on socket allocation failure");
218 
219 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
220 
221 #define	SCH_LOCK(sch)		mtx_lock(&(sch)->sch_mtx)
222 #define	SCH_UNLOCK(sch)		mtx_unlock(&(sch)->sch_mtx)
223 #define	SCH_LOCK_ASSERT(sch)	mtx_assert(&(sch)->sch_mtx, MA_OWNED)
224 
225 /*
226  * Requires the syncache entry to be already removed from the bucket list.
227  */
228 static void
229 syncache_free(struct syncache *sc)
230 {
231 
232 	if (sc->sc_ipopts)
233 		(void) m_free(sc->sc_ipopts);
234 	if (sc->sc_cred)
235 		crfree(sc->sc_cred);
236 #ifdef MAC
237 	mac_syncache_destroy(&sc->sc_label);
238 #endif
239 
240 	uma_zfree(V_tcp_syncache.zone, sc);
241 }
242 
243 void
244 syncache_init(void)
245 {
246 	int i;
247 
248 	V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
249 	V_tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
250 	V_tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
251 	V_tcp_syncache.hash_secret = arc4random();
252 
253 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
254 	    &V_tcp_syncache.hashsize);
255 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
256 	    &V_tcp_syncache.bucket_limit);
257 	if (!powerof2(V_tcp_syncache.hashsize) ||
258 	    V_tcp_syncache.hashsize == 0) {
259 		printf("WARNING: syncache hash size is not a power of 2.\n");
260 		V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
261 	}
262 	V_tcp_syncache.hashmask = V_tcp_syncache.hashsize - 1;
263 
264 	/* Set limits. */
265 	V_tcp_syncache.cache_limit =
266 	    V_tcp_syncache.hashsize * V_tcp_syncache.bucket_limit;
267 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
268 	    &V_tcp_syncache.cache_limit);
269 
270 	/* Allocate the hash table. */
271 	V_tcp_syncache.hashbase = malloc(V_tcp_syncache.hashsize *
272 	    sizeof(struct syncache_head), M_SYNCACHE, M_WAITOK | M_ZERO);
273 
274 #ifdef VIMAGE
275 	V_tcp_syncache.vnet = curvnet;
276 #endif
277 
278 	/* Initialize the hash buckets. */
279 	for (i = 0; i < V_tcp_syncache.hashsize; i++) {
280 		TAILQ_INIT(&V_tcp_syncache.hashbase[i].sch_bucket);
281 		mtx_init(&V_tcp_syncache.hashbase[i].sch_mtx, "tcp_sc_head",
282 			 NULL, MTX_DEF);
283 		callout_init_mtx(&V_tcp_syncache.hashbase[i].sch_timer,
284 			 &V_tcp_syncache.hashbase[i].sch_mtx, 0);
285 		V_tcp_syncache.hashbase[i].sch_length = 0;
286 		V_tcp_syncache.hashbase[i].sch_sc = &V_tcp_syncache;
287 		V_tcp_syncache.hashbase[i].sch_last_overflow =
288 		    -(SYNCOOKIE_LIFETIME + 1);
289 	}
290 
291 	/* Create the syncache entry zone. */
292 	V_tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
293 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
294 	V_tcp_syncache.cache_limit = uma_zone_set_max(V_tcp_syncache.zone,
295 	    V_tcp_syncache.cache_limit);
296 
297 	/* Start the SYN cookie reseeder callout. */
298 	callout_init(&V_tcp_syncache.secret.reseed, 1);
299 	arc4rand(V_tcp_syncache.secret.key[0], SYNCOOKIE_SECRET_SIZE, 0);
300 	arc4rand(V_tcp_syncache.secret.key[1], SYNCOOKIE_SECRET_SIZE, 0);
301 	callout_reset(&V_tcp_syncache.secret.reseed, SYNCOOKIE_LIFETIME * hz,
302 	    syncookie_reseed, &V_tcp_syncache);
303 }
304 
305 #ifdef VIMAGE
306 void
307 syncache_destroy(void)
308 {
309 	struct syncache_head *sch;
310 	struct syncache *sc, *nsc;
311 	int i;
312 
313 	/*
314 	 * Stop the re-seed timer before freeing resources.  No need to
315 	 * possibly schedule it another time.
316 	 */
317 	callout_drain(&V_tcp_syncache.secret.reseed);
318 
319 	/* Cleanup hash buckets: stop timers, free entries, destroy locks. */
320 	for (i = 0; i < V_tcp_syncache.hashsize; i++) {
321 
322 		sch = &V_tcp_syncache.hashbase[i];
323 		callout_drain(&sch->sch_timer);
324 
325 		SCH_LOCK(sch);
326 		TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc)
327 			syncache_drop(sc, sch);
328 		SCH_UNLOCK(sch);
329 		KASSERT(TAILQ_EMPTY(&sch->sch_bucket),
330 		    ("%s: sch->sch_bucket not empty", __func__));
331 		KASSERT(sch->sch_length == 0, ("%s: sch->sch_length %d not 0",
332 		    __func__, sch->sch_length));
333 		mtx_destroy(&sch->sch_mtx);
334 	}
335 
336 	KASSERT(uma_zone_get_cur(V_tcp_syncache.zone) == 0,
337 	    ("%s: cache_count not 0", __func__));
338 
339 	/* Free the allocated global resources. */
340 	uma_zdestroy(V_tcp_syncache.zone);
341 	free(V_tcp_syncache.hashbase, M_SYNCACHE);
342 }
343 #endif
344 
345 /*
346  * Inserts a syncache entry into the specified bucket row.
347  * Locks and unlocks the syncache_head autonomously.
348  */
349 static void
350 syncache_insert(struct syncache *sc, struct syncache_head *sch)
351 {
352 	struct syncache *sc2;
353 
354 	SCH_LOCK(sch);
355 
356 	/*
357 	 * Make sure that we don't overflow the per-bucket limit.
358 	 * If the bucket is full, toss the oldest element.
359 	 */
360 	if (sch->sch_length >= V_tcp_syncache.bucket_limit) {
361 		KASSERT(!TAILQ_EMPTY(&sch->sch_bucket),
362 			("sch->sch_length incorrect"));
363 		sc2 = TAILQ_LAST(&sch->sch_bucket, sch_head);
364 		sch->sch_last_overflow = time_uptime;
365 		syncache_drop(sc2, sch);
366 		TCPSTAT_INC(tcps_sc_bucketoverflow);
367 	}
368 
369 	/* Put it into the bucket. */
370 	TAILQ_INSERT_HEAD(&sch->sch_bucket, sc, sc_hash);
371 	sch->sch_length++;
372 
373 #ifdef TCP_OFFLOAD
374 	if (ADDED_BY_TOE(sc)) {
375 		struct toedev *tod = sc->sc_tod;
376 
377 		tod->tod_syncache_added(tod, sc->sc_todctx);
378 	}
379 #endif
380 
381 	/* Reinitialize the bucket row's timer. */
382 	if (sch->sch_length == 1)
383 		sch->sch_nextc = ticks + INT_MAX;
384 	syncache_timeout(sc, sch, 1);
385 
386 	SCH_UNLOCK(sch);
387 
388 	TCPSTATES_INC(TCPS_SYN_RECEIVED);
389 	TCPSTAT_INC(tcps_sc_added);
390 }
391 
392 /*
393  * Remove and free entry from syncache bucket row.
394  * Expects locked syncache head.
395  */
396 static void
397 syncache_drop(struct syncache *sc, struct syncache_head *sch)
398 {
399 
400 	SCH_LOCK_ASSERT(sch);
401 
402 	TCPSTATES_DEC(TCPS_SYN_RECEIVED);
403 	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
404 	sch->sch_length--;
405 
406 #ifdef TCP_OFFLOAD
407 	if (ADDED_BY_TOE(sc)) {
408 		struct toedev *tod = sc->sc_tod;
409 
410 		tod->tod_syncache_removed(tod, sc->sc_todctx);
411 	}
412 #endif
413 
414 	syncache_free(sc);
415 }
416 
417 /*
418  * Engage/reengage time on bucket row.
419  */
420 static void
421 syncache_timeout(struct syncache *sc, struct syncache_head *sch, int docallout)
422 {
423 	int rexmt;
424 
425 	if (sc->sc_rxmits == 0)
426 		rexmt = tcp_rexmit_initial;
427 	else
428 		TCPT_RANGESET(rexmt,
429 		    tcp_rexmit_initial * tcp_backoff[sc->sc_rxmits],
430 		    tcp_rexmit_min, TCPTV_REXMTMAX);
431 	sc->sc_rxttime = ticks + rexmt;
432 	sc->sc_rxmits++;
433 	if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc)) {
434 		sch->sch_nextc = sc->sc_rxttime;
435 		if (docallout)
436 			callout_reset(&sch->sch_timer, sch->sch_nextc - ticks,
437 			    syncache_timer, (void *)sch);
438 	}
439 }
440 
441 /*
442  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
443  * If we have retransmitted an entry the maximum number of times, expire it.
444  * One separate timer for each bucket row.
445  */
446 static void
447 syncache_timer(void *xsch)
448 {
449 	struct syncache_head *sch = (struct syncache_head *)xsch;
450 	struct syncache *sc, *nsc;
451 	int tick = ticks;
452 	char *s;
453 
454 	CURVNET_SET(sch->sch_sc->vnet);
455 
456 	/* NB: syncache_head has already been locked by the callout. */
457 	SCH_LOCK_ASSERT(sch);
458 
459 	/*
460 	 * In the following cycle we may remove some entries and/or
461 	 * advance some timeouts, so re-initialize the bucket timer.
462 	 */
463 	sch->sch_nextc = tick + INT_MAX;
464 
465 	TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) {
466 		/*
467 		 * We do not check if the listen socket still exists
468 		 * and accept the case where the listen socket may be
469 		 * gone by the time we resend the SYN/ACK.  We do
470 		 * not expect this to happens often. If it does,
471 		 * then the RST will be sent by the time the remote
472 		 * host does the SYN/ACK->ACK.
473 		 */
474 		if (TSTMP_GT(sc->sc_rxttime, tick)) {
475 			if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc))
476 				sch->sch_nextc = sc->sc_rxttime;
477 			continue;
478 		}
479 		if (sc->sc_rxmits > V_tcp_syncache.rexmt_limit) {
480 			if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
481 				log(LOG_DEBUG, "%s; %s: Retransmits exhausted, "
482 				    "giving up and removing syncache entry\n",
483 				    s, __func__);
484 				free(s, M_TCPLOG);
485 			}
486 			syncache_drop(sc, sch);
487 			TCPSTAT_INC(tcps_sc_stale);
488 			continue;
489 		}
490 		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
491 			log(LOG_DEBUG, "%s; %s: Response timeout, "
492 			    "retransmitting (%u) SYN|ACK\n",
493 			    s, __func__, sc->sc_rxmits);
494 			free(s, M_TCPLOG);
495 		}
496 
497 		syncache_respond(sc, NULL, TH_SYN|TH_ACK);
498 		TCPSTAT_INC(tcps_sc_retransmitted);
499 		syncache_timeout(sc, sch, 0);
500 	}
501 	if (!TAILQ_EMPTY(&(sch)->sch_bucket))
502 		callout_reset(&(sch)->sch_timer, (sch)->sch_nextc - tick,
503 			syncache_timer, (void *)(sch));
504 	CURVNET_RESTORE();
505 }
506 
507 /*
508  * Find an entry in the syncache.
509  * Returns always with locked syncache_head plus a matching entry or NULL.
510  */
511 static struct syncache *
512 syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
513 {
514 	struct syncache *sc;
515 	struct syncache_head *sch;
516 	uint32_t hash;
517 
518 	/*
519 	 * The hash is built on foreign port + local port + foreign address.
520 	 * We rely on the fact that struct in_conninfo starts with 16 bits
521 	 * of foreign port, then 16 bits of local port then followed by 128
522 	 * bits of foreign address.  In case of IPv4 address, the first 3
523 	 * 32-bit words of the address always are zeroes.
524 	 */
525 	hash = jenkins_hash32((uint32_t *)&inc->inc_ie, 5,
526 	    V_tcp_syncache.hash_secret) & V_tcp_syncache.hashmask;
527 
528 	sch = &V_tcp_syncache.hashbase[hash];
529 	*schp = sch;
530 	SCH_LOCK(sch);
531 
532 	/* Circle through bucket row to find matching entry. */
533 	TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash)
534 		if (bcmp(&inc->inc_ie, &sc->sc_inc.inc_ie,
535 		    sizeof(struct in_endpoints)) == 0)
536 			break;
537 
538 	return (sc);	/* Always returns with locked sch. */
539 }
540 
541 /*
542  * This function is called when we get a RST for a
543  * non-existent connection, so that we can see if the
544  * connection is in the syn cache.  If it is, zap it.
545  * If required send a challenge ACK.
546  */
547 void
548 syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th, struct mbuf *m)
549 {
550 	struct syncache *sc;
551 	struct syncache_head *sch;
552 	char *s = NULL;
553 
554 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
555 	SCH_LOCK_ASSERT(sch);
556 
557 	/*
558 	 * Any RST to our SYN|ACK must not carry ACK, SYN or FIN flags.
559 	 * See RFC 793 page 65, section SEGMENT ARRIVES.
560 	 */
561 	if (th->th_flags & (TH_ACK|TH_SYN|TH_FIN)) {
562 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
563 			log(LOG_DEBUG, "%s; %s: Spurious RST with ACK, SYN or "
564 			    "FIN flag set, segment ignored\n", s, __func__);
565 		TCPSTAT_INC(tcps_badrst);
566 		goto done;
567 	}
568 
569 	/*
570 	 * No corresponding connection was found in syncache.
571 	 * If syncookies are enabled and possibly exclusively
572 	 * used, or we are under memory pressure, a valid RST
573 	 * may not find a syncache entry.  In that case we're
574 	 * done and no SYN|ACK retransmissions will happen.
575 	 * Otherwise the RST was misdirected or spoofed.
576 	 */
577 	if (sc == NULL) {
578 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
579 			log(LOG_DEBUG, "%s; %s: Spurious RST without matching "
580 			    "syncache entry (possibly syncookie only), "
581 			    "segment ignored\n", s, __func__);
582 		TCPSTAT_INC(tcps_badrst);
583 		goto done;
584 	}
585 
586 	/*
587 	 * If the RST bit is set, check the sequence number to see
588 	 * if this is a valid reset segment.
589 	 *
590 	 * RFC 793 page 37:
591 	 *   In all states except SYN-SENT, all reset (RST) segments
592 	 *   are validated by checking their SEQ-fields.  A reset is
593 	 *   valid if its sequence number is in the window.
594 	 *
595 	 * RFC 793 page 69:
596 	 *   There are four cases for the acceptability test for an incoming
597 	 *   segment:
598 	 *
599 	 * Segment Receive  Test
600 	 * Length  Window
601 	 * ------- -------  -------------------------------------------
602 	 *    0       0     SEG.SEQ = RCV.NXT
603 	 *    0      >0     RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
604 	 *   >0       0     not acceptable
605 	 *   >0      >0     RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
606 	 *               or RCV.NXT =< SEG.SEQ+SEG.LEN-1 < RCV.NXT+RCV.WND
607 	 *
608 	 * Note that when receiving a SYN segment in the LISTEN state,
609 	 * IRS is set to SEG.SEQ and RCV.NXT is set to SEG.SEQ+1, as
610 	 * described in RFC 793, page 66.
611 	 */
612 	if ((SEQ_GEQ(th->th_seq, sc->sc_irs + 1) &&
613 	    SEQ_LT(th->th_seq, sc->sc_irs + 1 + sc->sc_wnd)) ||
614 	    (sc->sc_wnd == 0 && th->th_seq == sc->sc_irs + 1)) {
615 		if (V_tcp_insecure_rst ||
616 		    th->th_seq == sc->sc_irs + 1) {
617 			syncache_drop(sc, sch);
618 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
619 				log(LOG_DEBUG,
620 				    "%s; %s: Our SYN|ACK was rejected, "
621 				    "connection attempt aborted by remote "
622 				    "endpoint\n",
623 				    s, __func__);
624 			TCPSTAT_INC(tcps_sc_reset);
625 		} else {
626 			TCPSTAT_INC(tcps_badrst);
627 			/* Send challenge ACK. */
628 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
629 				log(LOG_DEBUG, "%s; %s: RST with invalid "
630 				    " SEQ %u != NXT %u (+WND %u), "
631 				    "sending challenge ACK\n",
632 				    s, __func__,
633 				    th->th_seq, sc->sc_irs + 1, sc->sc_wnd);
634 			syncache_respond(sc, m, TH_ACK);
635 		}
636 	} else {
637 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
638 			log(LOG_DEBUG, "%s; %s: RST with invalid SEQ %u != "
639 			    "NXT %u (+WND %u), segment ignored\n",
640 			    s, __func__,
641 			    th->th_seq, sc->sc_irs + 1, sc->sc_wnd);
642 		TCPSTAT_INC(tcps_badrst);
643 	}
644 
645 done:
646 	if (s != NULL)
647 		free(s, M_TCPLOG);
648 	SCH_UNLOCK(sch);
649 }
650 
651 void
652 syncache_badack(struct in_conninfo *inc)
653 {
654 	struct syncache *sc;
655 	struct syncache_head *sch;
656 
657 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
658 	SCH_LOCK_ASSERT(sch);
659 	if (sc != NULL) {
660 		syncache_drop(sc, sch);
661 		TCPSTAT_INC(tcps_sc_badack);
662 	}
663 	SCH_UNLOCK(sch);
664 }
665 
666 void
667 syncache_unreach(struct in_conninfo *inc, tcp_seq th_seq)
668 {
669 	struct syncache *sc;
670 	struct syncache_head *sch;
671 
672 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
673 	SCH_LOCK_ASSERT(sch);
674 	if (sc == NULL)
675 		goto done;
676 
677 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
678 	if (ntohl(th_seq) != sc->sc_iss)
679 		goto done;
680 
681 	/*
682 	 * If we've rertransmitted 3 times and this is our second error,
683 	 * we remove the entry.  Otherwise, we allow it to continue on.
684 	 * This prevents us from incorrectly nuking an entry during a
685 	 * spurious network outage.
686 	 *
687 	 * See tcp_notify().
688 	 */
689 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxmits < 3 + 1) {
690 		sc->sc_flags |= SCF_UNREACH;
691 		goto done;
692 	}
693 	syncache_drop(sc, sch);
694 	TCPSTAT_INC(tcps_sc_unreach);
695 done:
696 	SCH_UNLOCK(sch);
697 }
698 
699 /*
700  * Build a new TCP socket structure from a syncache entry.
701  *
702  * On success return the newly created socket with its underlying inp locked.
703  */
704 static struct socket *
705 syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m)
706 {
707 	struct tcp_function_block *blk;
708 	struct inpcb *inp = NULL;
709 	struct socket *so;
710 	struct tcpcb *tp;
711 	int error;
712 	char *s;
713 
714 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
715 
716 	/*
717 	 * Ok, create the full blown connection, and set things up
718 	 * as they would have been set up if we had created the
719 	 * connection when the SYN arrived.  If we can't create
720 	 * the connection, abort it.
721 	 */
722 	so = sonewconn(lso, 0);
723 	if (so == NULL) {
724 		/*
725 		 * Drop the connection; we will either send a RST or
726 		 * have the peer retransmit its SYN again after its
727 		 * RTO and try again.
728 		 */
729 		TCPSTAT_INC(tcps_listendrop);
730 		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
731 			log(LOG_DEBUG, "%s; %s: Socket create failed "
732 			    "due to limits or memory shortage\n",
733 			    s, __func__);
734 			free(s, M_TCPLOG);
735 		}
736 		goto abort2;
737 	}
738 #ifdef MAC
739 	mac_socketpeer_set_from_mbuf(m, so);
740 #endif
741 
742 	inp = sotoinpcb(so);
743 	inp->inp_inc.inc_fibnum = so->so_fibnum;
744 	INP_WLOCK(inp);
745 	/*
746 	 * Exclusive pcbinfo lock is not required in syncache socket case even
747 	 * if two inpcb locks can be acquired simultaneously:
748 	 *  - the inpcb in LISTEN state,
749 	 *  - the newly created inp.
750 	 *
751 	 * In this case, an inp cannot be at same time in LISTEN state and
752 	 * just created by an accept() call.
753 	 */
754 	INP_HASH_WLOCK(&V_tcbinfo);
755 
756 	/* Insert new socket into PCB hash list. */
757 	inp->inp_inc.inc_flags = sc->sc_inc.inc_flags;
758 #ifdef INET6
759 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
760 		inp->inp_vflag &= ~INP_IPV4;
761 		inp->inp_vflag |= INP_IPV6;
762 		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
763 	} else {
764 		inp->inp_vflag &= ~INP_IPV6;
765 		inp->inp_vflag |= INP_IPV4;
766 #endif
767 		inp->inp_laddr = sc->sc_inc.inc_laddr;
768 #ifdef INET6
769 	}
770 #endif
771 
772 	/*
773 	 * If there's an mbuf and it has a flowid, then let's initialise the
774 	 * inp with that particular flowid.
775 	 */
776 	if (m != NULL && M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
777 		inp->inp_flowid = m->m_pkthdr.flowid;
778 		inp->inp_flowtype = M_HASHTYPE_GET(m);
779 #ifdef NUMA
780 		inp->inp_numa_domain = m->m_pkthdr.numa_domain;
781 #endif
782 	}
783 
784 	/*
785 	 * Install in the reservation hash table for now, but don't yet
786 	 * install a connection group since the full 4-tuple isn't yet
787 	 * configured.
788 	 */
789 	inp->inp_lport = sc->sc_inc.inc_lport;
790 	if ((error = in_pcbinshash_nopcbgroup(inp)) != 0) {
791 		/*
792 		 * Undo the assignments above if we failed to
793 		 * put the PCB on the hash lists.
794 		 */
795 #ifdef INET6
796 		if (sc->sc_inc.inc_flags & INC_ISIPV6)
797 			inp->in6p_laddr = in6addr_any;
798 		else
799 #endif
800 			inp->inp_laddr.s_addr = INADDR_ANY;
801 		inp->inp_lport = 0;
802 		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
803 			log(LOG_DEBUG, "%s; %s: in_pcbinshash failed "
804 			    "with error %i\n",
805 			    s, __func__, error);
806 			free(s, M_TCPLOG);
807 		}
808 		INP_HASH_WUNLOCK(&V_tcbinfo);
809 		goto abort;
810 	}
811 #ifdef INET6
812 	if (inp->inp_vflag & INP_IPV6PROTO) {
813 		struct inpcb *oinp = sotoinpcb(lso);
814 
815 		/*
816 		 * Inherit socket options from the listening socket.
817 		 * Note that in6p_inputopts are not (and should not be)
818 		 * copied, since it stores previously received options and is
819 		 * used to detect if each new option is different than the
820 		 * previous one and hence should be passed to a user.
821 		 * If we copied in6p_inputopts, a user would not be able to
822 		 * receive options just after calling the accept system call.
823 		 */
824 		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
825 		if (oinp->in6p_outputopts)
826 			inp->in6p_outputopts =
827 			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
828 	}
829 
830 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
831 		struct in6_addr laddr6;
832 		struct sockaddr_in6 sin6;
833 
834 		sin6.sin6_family = AF_INET6;
835 		sin6.sin6_len = sizeof(sin6);
836 		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
837 		sin6.sin6_port = sc->sc_inc.inc_fport;
838 		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
839 		laddr6 = inp->in6p_laddr;
840 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
841 			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
842 		if ((error = in6_pcbconnect_mbuf(inp, (struct sockaddr *)&sin6,
843 		    thread0.td_ucred, m)) != 0) {
844 			inp->in6p_laddr = laddr6;
845 			if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
846 				log(LOG_DEBUG, "%s; %s: in6_pcbconnect failed "
847 				    "with error %i\n",
848 				    s, __func__, error);
849 				free(s, M_TCPLOG);
850 			}
851 			INP_HASH_WUNLOCK(&V_tcbinfo);
852 			goto abort;
853 		}
854 		/* Override flowlabel from in6_pcbconnect. */
855 		inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
856 		inp->inp_flow |= sc->sc_flowlabel;
857 	}
858 #endif /* INET6 */
859 #if defined(INET) && defined(INET6)
860 	else
861 #endif
862 #ifdef INET
863 	{
864 		struct in_addr laddr;
865 		struct sockaddr_in sin;
866 
867 		inp->inp_options = (m) ? ip_srcroute(m) : NULL;
868 
869 		if (inp->inp_options == NULL) {
870 			inp->inp_options = sc->sc_ipopts;
871 			sc->sc_ipopts = NULL;
872 		}
873 
874 		sin.sin_family = AF_INET;
875 		sin.sin_len = sizeof(sin);
876 		sin.sin_addr = sc->sc_inc.inc_faddr;
877 		sin.sin_port = sc->sc_inc.inc_fport;
878 		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
879 		laddr = inp->inp_laddr;
880 		if (inp->inp_laddr.s_addr == INADDR_ANY)
881 			inp->inp_laddr = sc->sc_inc.inc_laddr;
882 		if ((error = in_pcbconnect_mbuf(inp, (struct sockaddr *)&sin,
883 		    thread0.td_ucred, m)) != 0) {
884 			inp->inp_laddr = laddr;
885 			if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
886 				log(LOG_DEBUG, "%s; %s: in_pcbconnect failed "
887 				    "with error %i\n",
888 				    s, __func__, error);
889 				free(s, M_TCPLOG);
890 			}
891 			INP_HASH_WUNLOCK(&V_tcbinfo);
892 			goto abort;
893 		}
894 	}
895 #endif /* INET */
896 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
897 	/* Copy old policy into new socket's. */
898 	if (ipsec_copy_pcbpolicy(sotoinpcb(lso), inp) != 0)
899 		printf("syncache_socket: could not copy policy\n");
900 #endif
901 	INP_HASH_WUNLOCK(&V_tcbinfo);
902 	tp = intotcpcb(inp);
903 	tcp_state_change(tp, TCPS_SYN_RECEIVED);
904 	tp->iss = sc->sc_iss;
905 	tp->irs = sc->sc_irs;
906 	tcp_rcvseqinit(tp);
907 	tcp_sendseqinit(tp);
908 	blk = sototcpcb(lso)->t_fb;
909 	if (V_functions_inherit_listen_socket_stack && blk != tp->t_fb) {
910 		/*
911 		 * Our parents t_fb was not the default,
912 		 * we need to release our ref on tp->t_fb and
913 		 * pickup one on the new entry.
914 		 */
915 		struct tcp_function_block *rblk;
916 
917 		rblk = find_and_ref_tcp_fb(blk);
918 		KASSERT(rblk != NULL,
919 		    ("cannot find blk %p out of syncache?", blk));
920 		if (tp->t_fb->tfb_tcp_fb_fini)
921 			(*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
922 		refcount_release(&tp->t_fb->tfb_refcnt);
923 		tp->t_fb = rblk;
924 		/*
925 		 * XXXrrs this is quite dangerous, it is possible
926 		 * for the new function to fail to init. We also
927 		 * are not asking if the handoff_is_ok though at
928 		 * the very start thats probalbly ok.
929 		 */
930 		if (tp->t_fb->tfb_tcp_fb_init) {
931 			(*tp->t_fb->tfb_tcp_fb_init)(tp);
932 		}
933 	}
934 	tp->snd_wl1 = sc->sc_irs;
935 	tp->snd_max = tp->iss + 1;
936 	tp->snd_nxt = tp->iss + 1;
937 	tp->rcv_up = sc->sc_irs + 1;
938 	tp->rcv_wnd = sc->sc_wnd;
939 	tp->rcv_adv += tp->rcv_wnd;
940 	tp->last_ack_sent = tp->rcv_nxt;
941 
942 	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
943 	if (sc->sc_flags & SCF_NOOPT)
944 		tp->t_flags |= TF_NOOPT;
945 	else {
946 		if (sc->sc_flags & SCF_WINSCALE) {
947 			tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
948 			tp->snd_scale = sc->sc_requested_s_scale;
949 			tp->request_r_scale = sc->sc_requested_r_scale;
950 		}
951 		if (sc->sc_flags & SCF_TIMESTAMP) {
952 			tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
953 			tp->ts_recent = sc->sc_tsreflect;
954 			tp->ts_recent_age = tcp_ts_getticks();
955 			tp->ts_offset = sc->sc_tsoff;
956 		}
957 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
958 		if (sc->sc_flags & SCF_SIGNATURE)
959 			tp->t_flags |= TF_SIGNATURE;
960 #endif
961 		if (sc->sc_flags & SCF_SACK)
962 			tp->t_flags |= TF_SACK_PERMIT;
963 	}
964 
965 	if (sc->sc_flags & SCF_ECN)
966 		tp->t_flags |= TF_ECN_PERMIT;
967 
968 	/*
969 	 * Set up MSS and get cached values from tcp_hostcache.
970 	 * This might overwrite some of the defaults we just set.
971 	 */
972 	tcp_mss(tp, sc->sc_peer_mss);
973 
974 	/*
975 	 * If the SYN,ACK was retransmitted, indicate that CWND to be
976 	 * limited to one segment in cc_conn_init().
977 	 * NB: sc_rxmits counts all SYN,ACK transmits, not just retransmits.
978 	 */
979 	if (sc->sc_rxmits > 1)
980 		tp->snd_cwnd = 1;
981 
982 #ifdef TCP_OFFLOAD
983 	/*
984 	 * Allow a TOE driver to install its hooks.  Note that we hold the
985 	 * pcbinfo lock too and that prevents tcp_usr_accept from accepting a
986 	 * new connection before the TOE driver has done its thing.
987 	 */
988 	if (ADDED_BY_TOE(sc)) {
989 		struct toedev *tod = sc->sc_tod;
990 
991 		tod->tod_offload_socket(tod, sc->sc_todctx, so);
992 	}
993 #endif
994 	/*
995 	 * Copy and activate timers.
996 	 */
997 	tp->t_keepinit = sototcpcb(lso)->t_keepinit;
998 	tp->t_keepidle = sototcpcb(lso)->t_keepidle;
999 	tp->t_keepintvl = sototcpcb(lso)->t_keepintvl;
1000 	tp->t_keepcnt = sototcpcb(lso)->t_keepcnt;
1001 	tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
1002 
1003 	TCPSTAT_INC(tcps_accepts);
1004 	return (so);
1005 
1006 abort:
1007 	INP_WUNLOCK(inp);
1008 abort2:
1009 	if (so != NULL)
1010 		soabort(so);
1011 	return (NULL);
1012 }
1013 
1014 /*
1015  * This function gets called when we receive an ACK for a
1016  * socket in the LISTEN state.  We look up the connection
1017  * in the syncache, and if its there, we pull it out of
1018  * the cache and turn it into a full-blown connection in
1019  * the SYN-RECEIVED state.
1020  *
1021  * On syncache_socket() success the newly created socket
1022  * has its underlying inp locked.
1023  */
1024 int
1025 syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1026     struct socket **lsop, struct mbuf *m)
1027 {
1028 	struct syncache *sc;
1029 	struct syncache_head *sch;
1030 	struct syncache scs;
1031 	char *s;
1032 
1033 	/*
1034 	 * Global TCP locks are held because we manipulate the PCB lists
1035 	 * and create a new socket.
1036 	 */
1037 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1038 	KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK,
1039 	    ("%s: can handle only ACK", __func__));
1040 
1041 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
1042 	SCH_LOCK_ASSERT(sch);
1043 
1044 #ifdef INVARIANTS
1045 	/*
1046 	 * Test code for syncookies comparing the syncache stored
1047 	 * values with the reconstructed values from the cookie.
1048 	 */
1049 	if (sc != NULL)
1050 		syncookie_cmp(inc, sch, sc, th, to, *lsop);
1051 #endif
1052 
1053 	if (sc == NULL) {
1054 		/*
1055 		 * There is no syncache entry, so see if this ACK is
1056 		 * a returning syncookie.  To do this, first:
1057 		 *  A. Check if syncookies are used in case of syncache
1058 		 *     overflows
1059 		 *  B. See if this socket has had a syncache entry dropped in
1060 		 *     the recent past. We don't want to accept a bogus
1061 		 *     syncookie if we've never received a SYN or accept it
1062 		 *     twice.
1063 		 *  C. check that the syncookie is valid.  If it is, then
1064 		 *     cobble up a fake syncache entry, and return.
1065 		 */
1066 		if (!V_tcp_syncookies) {
1067 			SCH_UNLOCK(sch);
1068 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1069 				log(LOG_DEBUG, "%s; %s: Spurious ACK, "
1070 				    "segment rejected (syncookies disabled)\n",
1071 				    s, __func__);
1072 			goto failed;
1073 		}
1074 		if (!V_tcp_syncookiesonly &&
1075 		    sch->sch_last_overflow < time_uptime - SYNCOOKIE_LIFETIME) {
1076 			SCH_UNLOCK(sch);
1077 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1078 				log(LOG_DEBUG, "%s; %s: Spurious ACK, "
1079 				    "segment rejected (no syncache entry)\n",
1080 				    s, __func__);
1081 			goto failed;
1082 		}
1083 		bzero(&scs, sizeof(scs));
1084 		sc = syncookie_lookup(inc, sch, &scs, th, to, *lsop);
1085 		SCH_UNLOCK(sch);
1086 		if (sc == NULL) {
1087 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1088 				log(LOG_DEBUG, "%s; %s: Segment failed "
1089 				    "SYNCOOKIE authentication, segment rejected "
1090 				    "(probably spoofed)\n", s, __func__);
1091 			goto failed;
1092 		}
1093 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1094 		/* If received ACK has MD5 signature, check it. */
1095 		if ((to->to_flags & TOF_SIGNATURE) != 0 &&
1096 		    (!TCPMD5_ENABLED() ||
1097 		    TCPMD5_INPUT(m, th, to->to_signature) != 0)) {
1098 			/* Drop the ACK. */
1099 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1100 				log(LOG_DEBUG, "%s; %s: Segment rejected, "
1101 				    "MD5 signature doesn't match.\n",
1102 				    s, __func__);
1103 				free(s, M_TCPLOG);
1104 			}
1105 			TCPSTAT_INC(tcps_sig_err_sigopt);
1106 			return (-1); /* Do not send RST */
1107 		}
1108 #endif /* TCP_SIGNATURE */
1109 	} else {
1110 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1111 		/*
1112 		 * If listening socket requested TCP digests, check that
1113 		 * received ACK has signature and it is correct.
1114 		 * If not, drop the ACK and leave sc entry in th cache,
1115 		 * because SYN was received with correct signature.
1116 		 */
1117 		if (sc->sc_flags & SCF_SIGNATURE) {
1118 			if ((to->to_flags & TOF_SIGNATURE) == 0) {
1119 				/* No signature */
1120 				TCPSTAT_INC(tcps_sig_err_nosigopt);
1121 				SCH_UNLOCK(sch);
1122 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1123 					log(LOG_DEBUG, "%s; %s: Segment "
1124 					    "rejected, MD5 signature wasn't "
1125 					    "provided.\n", s, __func__);
1126 					free(s, M_TCPLOG);
1127 				}
1128 				return (-1); /* Do not send RST */
1129 			}
1130 			if (!TCPMD5_ENABLED() ||
1131 			    TCPMD5_INPUT(m, th, to->to_signature) != 0) {
1132 				/* Doesn't match or no SA */
1133 				SCH_UNLOCK(sch);
1134 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1135 					log(LOG_DEBUG, "%s; %s: Segment "
1136 					    "rejected, MD5 signature doesn't "
1137 					    "match.\n", s, __func__);
1138 					free(s, M_TCPLOG);
1139 				}
1140 				return (-1); /* Do not send RST */
1141 			}
1142 		}
1143 #endif /* TCP_SIGNATURE */
1144 
1145 		/*
1146 		 * RFC 7323 PAWS: If we have a timestamp on this segment and
1147 		 * it's less than ts_recent, drop it.
1148 		 * XXXMT: RFC 7323 also requires to send an ACK.
1149 		 *        In tcp_input.c this is only done for TCP segments
1150 		 *        with user data, so be consistent here and just drop
1151 		 *        the segment.
1152 		 */
1153 		if (sc->sc_flags & SCF_TIMESTAMP && to->to_flags & TOF_TS &&
1154 		    TSTMP_LT(to->to_tsval, sc->sc_tsreflect)) {
1155 			SCH_UNLOCK(sch);
1156 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1157 				log(LOG_DEBUG,
1158 				    "%s; %s: SEG.TSval %u < TS.Recent %u, "
1159 				    "segment dropped\n", s, __func__,
1160 				    to->to_tsval, sc->sc_tsreflect);
1161 				free(s, M_TCPLOG);
1162 			}
1163 			return (-1);  /* Do not send RST */
1164 		}
1165 
1166 		/*
1167 		 * Pull out the entry to unlock the bucket row.
1168 		 *
1169 		 * NOTE: We must decrease TCPS_SYN_RECEIVED count here, not
1170 		 * tcp_state_change().  The tcpcb is not existent at this
1171 		 * moment.  A new one will be allocated via syncache_socket->
1172 		 * sonewconn->tcp_usr_attach in TCPS_CLOSED state, then
1173 		 * syncache_socket() will change it to TCPS_SYN_RECEIVED.
1174 		 */
1175 		TCPSTATES_DEC(TCPS_SYN_RECEIVED);
1176 		TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
1177 		sch->sch_length--;
1178 #ifdef TCP_OFFLOAD
1179 		if (ADDED_BY_TOE(sc)) {
1180 			struct toedev *tod = sc->sc_tod;
1181 
1182 			tod->tod_syncache_removed(tod, sc->sc_todctx);
1183 		}
1184 #endif
1185 		SCH_UNLOCK(sch);
1186 	}
1187 
1188 	/*
1189 	 * Segment validation:
1190 	 * ACK must match our initial sequence number + 1 (the SYN|ACK).
1191 	 */
1192 	if (th->th_ack != sc->sc_iss + 1) {
1193 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1194 			log(LOG_DEBUG, "%s; %s: ACK %u != ISS+1 %u, segment "
1195 			    "rejected\n", s, __func__, th->th_ack, sc->sc_iss);
1196 		goto failed;
1197 	}
1198 
1199 	/*
1200 	 * The SEQ must fall in the window starting at the received
1201 	 * initial receive sequence number + 1 (the SYN).
1202 	 */
1203 	if (SEQ_LEQ(th->th_seq, sc->sc_irs) ||
1204 	    SEQ_GT(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
1205 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1206 			log(LOG_DEBUG, "%s; %s: SEQ %u != IRS+1 %u, segment "
1207 			    "rejected\n", s, __func__, th->th_seq, sc->sc_irs);
1208 		goto failed;
1209 	}
1210 
1211 	/*
1212 	 * If timestamps were not negotiated during SYN/ACK they
1213 	 * must not appear on any segment during this session.
1214 	 */
1215 	if (!(sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS)) {
1216 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1217 			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1218 			    "segment rejected\n", s, __func__);
1219 		goto failed;
1220 	}
1221 
1222 	/*
1223 	 * If timestamps were negotiated during SYN/ACK they should
1224 	 * appear on every segment during this session.
1225 	 * XXXAO: This is only informal as there have been unverified
1226 	 * reports of non-compliants stacks.
1227 	 */
1228 	if ((sc->sc_flags & SCF_TIMESTAMP) && !(to->to_flags & TOF_TS)) {
1229 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1230 			log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1231 			    "no action\n", s, __func__);
1232 			free(s, M_TCPLOG);
1233 			s = NULL;
1234 		}
1235 	}
1236 
1237 	*lsop = syncache_socket(sc, *lsop, m);
1238 
1239 	if (*lsop == NULL)
1240 		TCPSTAT_INC(tcps_sc_aborted);
1241 	else
1242 		TCPSTAT_INC(tcps_sc_completed);
1243 
1244 /* how do we find the inp for the new socket? */
1245 	if (sc != &scs)
1246 		syncache_free(sc);
1247 	return (1);
1248 failed:
1249 	if (sc != NULL && sc != &scs)
1250 		syncache_free(sc);
1251 	if (s != NULL)
1252 		free(s, M_TCPLOG);
1253 	*lsop = NULL;
1254 	return (0);
1255 }
1256 
1257 static void
1258 syncache_tfo_expand(struct syncache *sc, struct socket **lsop, struct mbuf *m,
1259     uint64_t response_cookie)
1260 {
1261 	struct inpcb *inp;
1262 	struct tcpcb *tp;
1263 	unsigned int *pending_counter;
1264 
1265 	/*
1266 	 * Global TCP locks are held because we manipulate the PCB lists
1267 	 * and create a new socket.
1268 	 */
1269 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1270 
1271 	pending_counter = intotcpcb(sotoinpcb(*lsop))->t_tfo_pending;
1272 	*lsop = syncache_socket(sc, *lsop, m);
1273 	if (*lsop == NULL) {
1274 		TCPSTAT_INC(tcps_sc_aborted);
1275 		atomic_subtract_int(pending_counter, 1);
1276 	} else {
1277 		soisconnected(*lsop);
1278 		inp = sotoinpcb(*lsop);
1279 		tp = intotcpcb(inp);
1280 		tp->t_flags |= TF_FASTOPEN;
1281 		tp->t_tfo_cookie.server = response_cookie;
1282 		tp->snd_max = tp->iss;
1283 		tp->snd_nxt = tp->iss;
1284 		tp->t_tfo_pending = pending_counter;
1285 		TCPSTAT_INC(tcps_sc_completed);
1286 	}
1287 }
1288 
1289 /*
1290  * Given a LISTEN socket and an inbound SYN request, add
1291  * this to the syn cache, and send back a segment:
1292  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1293  * to the source.
1294  *
1295  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
1296  * Doing so would require that we hold onto the data and deliver it
1297  * to the application.  However, if we are the target of a SYN-flood
1298  * DoS attack, an attacker could send data which would eventually
1299  * consume all available buffer space if it were ACKed.  By not ACKing
1300  * the data, we avoid this DoS scenario.
1301  *
1302  * The exception to the above is when a SYN with a valid TCP Fast Open (TFO)
1303  * cookie is processed and a new socket is created.  In this case, any data
1304  * accompanying the SYN will be queued to the socket by tcp_input() and will
1305  * be ACKed either when the application sends response data or the delayed
1306  * ACK timer expires, whichever comes first.
1307  */
1308 int
1309 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1310     struct inpcb *inp, struct socket **lsop, struct mbuf *m, void *tod,
1311     void *todctx)
1312 {
1313 	struct tcpcb *tp;
1314 	struct socket *so;
1315 	struct syncache *sc = NULL;
1316 	struct syncache_head *sch;
1317 	struct mbuf *ipopts = NULL;
1318 	u_int ltflags;
1319 	int win, ip_ttl, ip_tos;
1320 	char *s;
1321 	int rv = 0;
1322 #ifdef INET6
1323 	int autoflowlabel = 0;
1324 #endif
1325 #ifdef MAC
1326 	struct label *maclabel;
1327 #endif
1328 	struct syncache scs;
1329 	struct ucred *cred;
1330 	uint64_t tfo_response_cookie;
1331 	unsigned int *tfo_pending = NULL;
1332 	int tfo_cookie_valid = 0;
1333 	int tfo_response_cookie_valid = 0;
1334 
1335 	INP_WLOCK_ASSERT(inp);			/* listen socket */
1336 	KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN,
1337 	    ("%s: unexpected tcp flags", __func__));
1338 
1339 	/*
1340 	 * Combine all so/tp operations very early to drop the INP lock as
1341 	 * soon as possible.
1342 	 */
1343 	so = *lsop;
1344 	KASSERT(SOLISTENING(so), ("%s: %p not listening", __func__, so));
1345 	tp = sototcpcb(so);
1346 	cred = crhold(so->so_cred);
1347 
1348 #ifdef INET6
1349 	if ((inc->inc_flags & INC_ISIPV6) &&
1350 	    (inp->inp_flags & IN6P_AUTOFLOWLABEL))
1351 		autoflowlabel = 1;
1352 #endif
1353 	ip_ttl = inp->inp_ip_ttl;
1354 	ip_tos = inp->inp_ip_tos;
1355 	win = so->sol_sbrcv_hiwat;
1356 	ltflags = (tp->t_flags & (TF_NOOPT | TF_SIGNATURE));
1357 
1358 	if (V_tcp_fastopen_server_enable && IS_FASTOPEN(tp->t_flags) &&
1359 	    (tp->t_tfo_pending != NULL) &&
1360 	    (to->to_flags & TOF_FASTOPEN)) {
1361 		/*
1362 		 * Limit the number of pending TFO connections to
1363 		 * approximately half of the queue limit.  This prevents TFO
1364 		 * SYN floods from starving the service by filling the
1365 		 * listen queue with bogus TFO connections.
1366 		 */
1367 		if (atomic_fetchadd_int(tp->t_tfo_pending, 1) <=
1368 		    (so->sol_qlimit / 2)) {
1369 			int result;
1370 
1371 			result = tcp_fastopen_check_cookie(inc,
1372 			    to->to_tfo_cookie, to->to_tfo_len,
1373 			    &tfo_response_cookie);
1374 			tfo_cookie_valid = (result > 0);
1375 			tfo_response_cookie_valid = (result >= 0);
1376 		}
1377 
1378 		/*
1379 		 * Remember the TFO pending counter as it will have to be
1380 		 * decremented below if we don't make it to syncache_tfo_expand().
1381 		 */
1382 		tfo_pending = tp->t_tfo_pending;
1383 	}
1384 
1385 	/* By the time we drop the lock these should no longer be used. */
1386 	so = NULL;
1387 	tp = NULL;
1388 
1389 #ifdef MAC
1390 	if (mac_syncache_init(&maclabel) != 0) {
1391 		INP_WUNLOCK(inp);
1392 		goto done;
1393 	} else
1394 		mac_syncache_create(maclabel, inp);
1395 #endif
1396 	if (!tfo_cookie_valid)
1397 		INP_WUNLOCK(inp);
1398 
1399 	/*
1400 	 * Remember the IP options, if any.
1401 	 */
1402 #ifdef INET6
1403 	if (!(inc->inc_flags & INC_ISIPV6))
1404 #endif
1405 #ifdef INET
1406 		ipopts = (m) ? ip_srcroute(m) : NULL;
1407 #else
1408 		ipopts = NULL;
1409 #endif
1410 
1411 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1412 	/*
1413 	 * If listening socket requested TCP digests, check that received
1414 	 * SYN has signature and it is correct. If signature doesn't match
1415 	 * or TCP_SIGNATURE support isn't enabled, drop the packet.
1416 	 */
1417 	if (ltflags & TF_SIGNATURE) {
1418 		if ((to->to_flags & TOF_SIGNATURE) == 0) {
1419 			TCPSTAT_INC(tcps_sig_err_nosigopt);
1420 			goto done;
1421 		}
1422 		if (!TCPMD5_ENABLED() ||
1423 		    TCPMD5_INPUT(m, th, to->to_signature) != 0)
1424 			goto done;
1425 	}
1426 #endif	/* TCP_SIGNATURE */
1427 	/*
1428 	 * See if we already have an entry for this connection.
1429 	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
1430 	 *
1431 	 * XXX: should the syncache be re-initialized with the contents
1432 	 * of the new SYN here (which may have different options?)
1433 	 *
1434 	 * XXX: We do not check the sequence number to see if this is a
1435 	 * real retransmit or a new connection attempt.  The question is
1436 	 * how to handle such a case; either ignore it as spoofed, or
1437 	 * drop the current entry and create a new one?
1438 	 */
1439 	sc = syncache_lookup(inc, &sch);	/* returns locked entry */
1440 	SCH_LOCK_ASSERT(sch);
1441 	if (sc != NULL) {
1442 		if (tfo_cookie_valid)
1443 			INP_WUNLOCK(inp);
1444 		TCPSTAT_INC(tcps_sc_dupsyn);
1445 		if (ipopts) {
1446 			/*
1447 			 * If we were remembering a previous source route,
1448 			 * forget it and use the new one we've been given.
1449 			 */
1450 			if (sc->sc_ipopts)
1451 				(void) m_free(sc->sc_ipopts);
1452 			sc->sc_ipopts = ipopts;
1453 		}
1454 		/*
1455 		 * Update timestamp if present.
1456 		 */
1457 		if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS))
1458 			sc->sc_tsreflect = to->to_tsval;
1459 		else
1460 			sc->sc_flags &= ~SCF_TIMESTAMP;
1461 #ifdef MAC
1462 		/*
1463 		 * Since we have already unconditionally allocated label
1464 		 * storage, free it up.  The syncache entry will already
1465 		 * have an initialized label we can use.
1466 		 */
1467 		mac_syncache_destroy(&maclabel);
1468 #endif
1469 		TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1470 		/* Retransmit SYN|ACK and reset retransmit count. */
1471 		if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) {
1472 			log(LOG_DEBUG, "%s; %s: Received duplicate SYN, "
1473 			    "resetting timer and retransmitting SYN|ACK\n",
1474 			    s, __func__);
1475 			free(s, M_TCPLOG);
1476 		}
1477 		if (syncache_respond(sc, m, TH_SYN|TH_ACK) == 0) {
1478 			sc->sc_rxmits = 0;
1479 			syncache_timeout(sc, sch, 1);
1480 			TCPSTAT_INC(tcps_sndacks);
1481 			TCPSTAT_INC(tcps_sndtotal);
1482 		}
1483 		SCH_UNLOCK(sch);
1484 		goto donenoprobe;
1485 	}
1486 
1487 	if (tfo_cookie_valid) {
1488 		bzero(&scs, sizeof(scs));
1489 		sc = &scs;
1490 		goto skip_alloc;
1491 	}
1492 
1493 	sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1494 	if (sc == NULL) {
1495 		/*
1496 		 * The zone allocator couldn't provide more entries.
1497 		 * Treat this as if the cache was full; drop the oldest
1498 		 * entry and insert the new one.
1499 		 */
1500 		TCPSTAT_INC(tcps_sc_zonefail);
1501 		if ((sc = TAILQ_LAST(&sch->sch_bucket, sch_head)) != NULL) {
1502 			sch->sch_last_overflow = time_uptime;
1503 			syncache_drop(sc, sch);
1504 		}
1505 		sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1506 		if (sc == NULL) {
1507 			if (V_tcp_syncookies) {
1508 				bzero(&scs, sizeof(scs));
1509 				sc = &scs;
1510 			} else {
1511 				SCH_UNLOCK(sch);
1512 				if (ipopts)
1513 					(void) m_free(ipopts);
1514 				goto done;
1515 			}
1516 		}
1517 	}
1518 
1519 skip_alloc:
1520 	if (!tfo_cookie_valid && tfo_response_cookie_valid)
1521 		sc->sc_tfo_cookie = &tfo_response_cookie;
1522 
1523 	/*
1524 	 * Fill in the syncache values.
1525 	 */
1526 #ifdef MAC
1527 	sc->sc_label = maclabel;
1528 #endif
1529 	sc->sc_cred = cred;
1530 	cred = NULL;
1531 	sc->sc_ipopts = ipopts;
1532 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1533 #ifdef INET6
1534 	if (!(inc->inc_flags & INC_ISIPV6))
1535 #endif
1536 	{
1537 		sc->sc_ip_tos = ip_tos;
1538 		sc->sc_ip_ttl = ip_ttl;
1539 	}
1540 #ifdef TCP_OFFLOAD
1541 	sc->sc_tod = tod;
1542 	sc->sc_todctx = todctx;
1543 #endif
1544 	sc->sc_irs = th->th_seq;
1545 	sc->sc_flags = 0;
1546 	sc->sc_flowlabel = 0;
1547 
1548 	/*
1549 	 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
1550 	 * win was derived from socket earlier in the function.
1551 	 */
1552 	win = imax(win, 0);
1553 	win = imin(win, TCP_MAXWIN);
1554 	sc->sc_wnd = win;
1555 
1556 	if (V_tcp_do_rfc1323) {
1557 		/*
1558 		 * A timestamp received in a SYN makes
1559 		 * it ok to send timestamp requests and replies.
1560 		 */
1561 		if (to->to_flags & TOF_TS) {
1562 			sc->sc_tsreflect = to->to_tsval;
1563 			sc->sc_flags |= SCF_TIMESTAMP;
1564 			sc->sc_tsoff = tcp_new_ts_offset(inc);
1565 		}
1566 		if (to->to_flags & TOF_SCALE) {
1567 			int wscale = 0;
1568 
1569 			/*
1570 			 * Pick the smallest possible scaling factor that
1571 			 * will still allow us to scale up to sb_max, aka
1572 			 * kern.ipc.maxsockbuf.
1573 			 *
1574 			 * We do this because there are broken firewalls that
1575 			 * will corrupt the window scale option, leading to
1576 			 * the other endpoint believing that our advertised
1577 			 * window is unscaled.  At scale factors larger than
1578 			 * 5 the unscaled window will drop below 1500 bytes,
1579 			 * leading to serious problems when traversing these
1580 			 * broken firewalls.
1581 			 *
1582 			 * With the default maxsockbuf of 256K, a scale factor
1583 			 * of 3 will be chosen by this algorithm.  Those who
1584 			 * choose a larger maxsockbuf should watch out
1585 			 * for the compatibility problems mentioned above.
1586 			 *
1587 			 * RFC1323: The Window field in a SYN (i.e., a <SYN>
1588 			 * or <SYN,ACK>) segment itself is never scaled.
1589 			 */
1590 			while (wscale < TCP_MAX_WINSHIFT &&
1591 			    (TCP_MAXWIN << wscale) < sb_max)
1592 				wscale++;
1593 			sc->sc_requested_r_scale = wscale;
1594 			sc->sc_requested_s_scale = to->to_wscale;
1595 			sc->sc_flags |= SCF_WINSCALE;
1596 		}
1597 	}
1598 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1599 	/*
1600 	 * If listening socket requested TCP digests, flag this in the
1601 	 * syncache so that syncache_respond() will do the right thing
1602 	 * with the SYN+ACK.
1603 	 */
1604 	if (ltflags & TF_SIGNATURE)
1605 		sc->sc_flags |= SCF_SIGNATURE;
1606 #endif	/* TCP_SIGNATURE */
1607 	if (to->to_flags & TOF_SACKPERM)
1608 		sc->sc_flags |= SCF_SACK;
1609 	if (to->to_flags & TOF_MSS)
1610 		sc->sc_peer_mss = to->to_mss;	/* peer mss may be zero */
1611 	if (ltflags & TF_NOOPT)
1612 		sc->sc_flags |= SCF_NOOPT;
1613 	if ((th->th_flags & (TH_ECE|TH_CWR)) && V_tcp_do_ecn)
1614 		sc->sc_flags |= SCF_ECN;
1615 
1616 	if (V_tcp_syncookies)
1617 		sc->sc_iss = syncookie_generate(sch, sc);
1618 	else
1619 		sc->sc_iss = arc4random();
1620 #ifdef INET6
1621 	if (autoflowlabel) {
1622 		if (V_tcp_syncookies)
1623 			sc->sc_flowlabel = sc->sc_iss;
1624 		else
1625 			sc->sc_flowlabel = ip6_randomflowlabel();
1626 		sc->sc_flowlabel = htonl(sc->sc_flowlabel) & IPV6_FLOWLABEL_MASK;
1627 	}
1628 #endif
1629 	SCH_UNLOCK(sch);
1630 
1631 	if (tfo_cookie_valid) {
1632 		syncache_tfo_expand(sc, lsop, m, tfo_response_cookie);
1633 		/* INP_WUNLOCK(inp) will be performed by the caller */
1634 		rv = 1;
1635 		goto tfo_expanded;
1636 	}
1637 
1638 	TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1639 	/*
1640 	 * Do a standard 3-way handshake.
1641 	 */
1642 	if (syncache_respond(sc, m, TH_SYN|TH_ACK) == 0) {
1643 		if (V_tcp_syncookies && V_tcp_syncookiesonly && sc != &scs)
1644 			syncache_free(sc);
1645 		else if (sc != &scs)
1646 			syncache_insert(sc, sch);   /* locks and unlocks sch */
1647 		TCPSTAT_INC(tcps_sndacks);
1648 		TCPSTAT_INC(tcps_sndtotal);
1649 	} else {
1650 		if (sc != &scs)
1651 			syncache_free(sc);
1652 		TCPSTAT_INC(tcps_sc_dropped);
1653 	}
1654 	goto donenoprobe;
1655 
1656 done:
1657 	TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1658 donenoprobe:
1659 	if (m) {
1660 		*lsop = NULL;
1661 		m_freem(m);
1662 	}
1663 	/*
1664 	 * If tfo_pending is not NULL here, then a TFO SYN that did not
1665 	 * result in a new socket was processed and the associated pending
1666 	 * counter has not yet been decremented.  All such TFO processing paths
1667 	 * transit this point.
1668 	 */
1669 	if (tfo_pending != NULL)
1670 		tcp_fastopen_decrement_counter(tfo_pending);
1671 
1672 tfo_expanded:
1673 	if (cred != NULL)
1674 		crfree(cred);
1675 #ifdef MAC
1676 	if (sc == &scs)
1677 		mac_syncache_destroy(&maclabel);
1678 #endif
1679 	return (rv);
1680 }
1681 
1682 /*
1683  * Send SYN|ACK or ACK to the peer.  Either in response to a peer's segment,
1684  * i.e. m0 != NULL, or upon 3WHS ACK timeout, i.e. m0 == NULL.
1685  */
1686 static int
1687 syncache_respond(struct syncache *sc, const struct mbuf *m0, int flags)
1688 {
1689 	struct ip *ip = NULL;
1690 	struct mbuf *m;
1691 	struct tcphdr *th = NULL;
1692 	int optlen, error = 0;	/* Make compiler happy */
1693 	u_int16_t hlen, tlen, mssopt;
1694 	struct tcpopt to;
1695 #ifdef INET6
1696 	struct ip6_hdr *ip6 = NULL;
1697 #endif
1698 	hlen =
1699 #ifdef INET6
1700 	       (sc->sc_inc.inc_flags & INC_ISIPV6) ? sizeof(struct ip6_hdr) :
1701 #endif
1702 		sizeof(struct ip);
1703 	tlen = hlen + sizeof(struct tcphdr);
1704 
1705 	/* Determine MSS we advertize to other end of connection. */
1706 	mssopt = max(tcp_mssopt(&sc->sc_inc), V_tcp_minmss);
1707 
1708 	/* XXX: Assume that the entire packet will fit in a header mbuf. */
1709 	KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN,
1710 	    ("syncache: mbuf too small"));
1711 
1712 	/* Create the IP+TCP header from scratch. */
1713 	m = m_gethdr(M_NOWAIT, MT_DATA);
1714 	if (m == NULL)
1715 		return (ENOBUFS);
1716 #ifdef MAC
1717 	mac_syncache_create_mbuf(sc->sc_label, m);
1718 #endif
1719 	m->m_data += max_linkhdr;
1720 	m->m_len = tlen;
1721 	m->m_pkthdr.len = tlen;
1722 	m->m_pkthdr.rcvif = NULL;
1723 
1724 #ifdef INET6
1725 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
1726 		ip6 = mtod(m, struct ip6_hdr *);
1727 		ip6->ip6_vfc = IPV6_VERSION;
1728 		ip6->ip6_nxt = IPPROTO_TCP;
1729 		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1730 		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1731 		ip6->ip6_plen = htons(tlen - hlen);
1732 		/* ip6_hlim is set after checksum */
1733 		ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
1734 		ip6->ip6_flow |= sc->sc_flowlabel;
1735 
1736 		th = (struct tcphdr *)(ip6 + 1);
1737 	}
1738 #endif
1739 #if defined(INET6) && defined(INET)
1740 	else
1741 #endif
1742 #ifdef INET
1743 	{
1744 		ip = mtod(m, struct ip *);
1745 		ip->ip_v = IPVERSION;
1746 		ip->ip_hl = sizeof(struct ip) >> 2;
1747 		ip->ip_len = htons(tlen);
1748 		ip->ip_id = 0;
1749 		ip->ip_off = 0;
1750 		ip->ip_sum = 0;
1751 		ip->ip_p = IPPROTO_TCP;
1752 		ip->ip_src = sc->sc_inc.inc_laddr;
1753 		ip->ip_dst = sc->sc_inc.inc_faddr;
1754 		ip->ip_ttl = sc->sc_ip_ttl;
1755 		ip->ip_tos = sc->sc_ip_tos;
1756 
1757 		/*
1758 		 * See if we should do MTU discovery.  Route lookups are
1759 		 * expensive, so we will only unset the DF bit if:
1760 		 *
1761 		 *	1) path_mtu_discovery is disabled
1762 		 *	2) the SCF_UNREACH flag has been set
1763 		 */
1764 		if (V_path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1765 		       ip->ip_off |= htons(IP_DF);
1766 
1767 		th = (struct tcphdr *)(ip + 1);
1768 	}
1769 #endif /* INET */
1770 	th->th_sport = sc->sc_inc.inc_lport;
1771 	th->th_dport = sc->sc_inc.inc_fport;
1772 
1773 	if (flags & TH_SYN)
1774 		th->th_seq = htonl(sc->sc_iss);
1775 	else
1776 		th->th_seq = htonl(sc->sc_iss + 1);
1777 	th->th_ack = htonl(sc->sc_irs + 1);
1778 	th->th_off = sizeof(struct tcphdr) >> 2;
1779 	th->th_x2 = 0;
1780 	th->th_flags = flags;
1781 	th->th_win = htons(sc->sc_wnd);
1782 	th->th_urp = 0;
1783 
1784 	if ((flags & TH_SYN) && (sc->sc_flags & SCF_ECN)) {
1785 		th->th_flags |= TH_ECE;
1786 		TCPSTAT_INC(tcps_ecn_shs);
1787 	}
1788 
1789 	/* Tack on the TCP options. */
1790 	if ((sc->sc_flags & SCF_NOOPT) == 0) {
1791 		to.to_flags = 0;
1792 
1793 		if (flags & TH_SYN) {
1794 			to.to_mss = mssopt;
1795 			to.to_flags = TOF_MSS;
1796 			if (sc->sc_flags & SCF_WINSCALE) {
1797 				to.to_wscale = sc->sc_requested_r_scale;
1798 				to.to_flags |= TOF_SCALE;
1799 			}
1800 			if (sc->sc_flags & SCF_SACK)
1801 				to.to_flags |= TOF_SACKPERM;
1802 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1803 			if (sc->sc_flags & SCF_SIGNATURE)
1804 				to.to_flags |= TOF_SIGNATURE;
1805 #endif
1806 			if (sc->sc_tfo_cookie) {
1807 				to.to_flags |= TOF_FASTOPEN;
1808 				to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
1809 				to.to_tfo_cookie = sc->sc_tfo_cookie;
1810 				/* don't send cookie again when retransmitting response */
1811 				sc->sc_tfo_cookie = NULL;
1812 			}
1813 		}
1814 		if (sc->sc_flags & SCF_TIMESTAMP) {
1815 			to.to_tsval = sc->sc_tsoff + tcp_ts_getticks();
1816 			to.to_tsecr = sc->sc_tsreflect;
1817 			to.to_flags |= TOF_TS;
1818 		}
1819 		optlen = tcp_addoptions(&to, (u_char *)(th + 1));
1820 
1821 		/* Adjust headers by option size. */
1822 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1823 		m->m_len += optlen;
1824 		m->m_pkthdr.len += optlen;
1825 #ifdef INET6
1826 		if (sc->sc_inc.inc_flags & INC_ISIPV6)
1827 			ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen);
1828 		else
1829 #endif
1830 			ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
1831 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1832 		if (sc->sc_flags & SCF_SIGNATURE) {
1833 			KASSERT(to.to_flags & TOF_SIGNATURE,
1834 			    ("tcp_addoptions() didn't set tcp_signature"));
1835 
1836 			/* NOTE: to.to_signature is inside of mbuf */
1837 			if (!TCPMD5_ENABLED() ||
1838 			    TCPMD5_OUTPUT(m, th, to.to_signature) != 0) {
1839 				m_freem(m);
1840 				return (EACCES);
1841 			}
1842 		}
1843 #endif
1844 	} else
1845 		optlen = 0;
1846 
1847 	M_SETFIB(m, sc->sc_inc.inc_fibnum);
1848 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1849 	/*
1850 	 * If we have peer's SYN and it has a flowid, then let's assign it to
1851 	 * our SYN|ACK.  ip6_output() and ip_output() will not assign flowid
1852 	 * to SYN|ACK due to lack of inp here.
1853 	 */
1854 	if (m0 != NULL && M_HASHTYPE_GET(m0) != M_HASHTYPE_NONE) {
1855 		m->m_pkthdr.flowid = m0->m_pkthdr.flowid;
1856 		M_HASHTYPE_SET(m, M_HASHTYPE_GET(m0));
1857 	}
1858 #ifdef INET6
1859 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
1860 		m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
1861 		th->th_sum = in6_cksum_pseudo(ip6, tlen + optlen - hlen,
1862 		    IPPROTO_TCP, 0);
1863 		ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
1864 #ifdef TCP_OFFLOAD
1865 		if (ADDED_BY_TOE(sc)) {
1866 			struct toedev *tod = sc->sc_tod;
1867 
1868 			error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
1869 
1870 			return (error);
1871 		}
1872 #endif
1873 		TCP_PROBE5(send, NULL, NULL, ip6, NULL, th);
1874 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1875 	}
1876 #endif
1877 #if defined(INET6) && defined(INET)
1878 	else
1879 #endif
1880 #ifdef INET
1881 	{
1882 		m->m_pkthdr.csum_flags = CSUM_TCP;
1883 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1884 		    htons(tlen + optlen - hlen + IPPROTO_TCP));
1885 #ifdef TCP_OFFLOAD
1886 		if (ADDED_BY_TOE(sc)) {
1887 			struct toedev *tod = sc->sc_tod;
1888 
1889 			error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
1890 
1891 			return (error);
1892 		}
1893 #endif
1894 		TCP_PROBE5(send, NULL, NULL, ip, NULL, th);
1895 		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
1896 	}
1897 #endif
1898 	return (error);
1899 }
1900 
1901 /*
1902  * The purpose of syncookies is to handle spoofed SYN flooding DoS attacks
1903  * that exceed the capacity of the syncache by avoiding the storage of any
1904  * of the SYNs we receive.  Syncookies defend against blind SYN flooding
1905  * attacks where the attacker does not have access to our responses.
1906  *
1907  * Syncookies encode and include all necessary information about the
1908  * connection setup within the SYN|ACK that we send back.  That way we
1909  * can avoid keeping any local state until the ACK to our SYN|ACK returns
1910  * (if ever).  Normally the syncache and syncookies are running in parallel
1911  * with the latter taking over when the former is exhausted.  When matching
1912  * syncache entry is found the syncookie is ignored.
1913  *
1914  * The only reliable information persisting the 3WHS is our initial sequence
1915  * number ISS of 32 bits.  Syncookies embed a cryptographically sufficient
1916  * strong hash (MAC) value and a few bits of TCP SYN options in the ISS
1917  * of our SYN|ACK.  The MAC can be recomputed when the ACK to our SYN|ACK
1918  * returns and signifies a legitimate connection if it matches the ACK.
1919  *
1920  * The available space of 32 bits to store the hash and to encode the SYN
1921  * option information is very tight and we should have at least 24 bits for
1922  * the MAC to keep the number of guesses by blind spoofing reasonably high.
1923  *
1924  * SYN option information we have to encode to fully restore a connection:
1925  * MSS: is imporant to chose an optimal segment size to avoid IP level
1926  *   fragmentation along the path.  The common MSS values can be encoded
1927  *   in a 3-bit table.  Uncommon values are captured by the next lower value
1928  *   in the table leading to a slight increase in packetization overhead.
1929  * WSCALE: is necessary to allow large windows to be used for high delay-
1930  *   bandwidth product links.  Not scaling the window when it was initially
1931  *   negotiated is bad for performance as lack of scaling further decreases
1932  *   the apparent available send window.  We only need to encode the WSCALE
1933  *   we received from the remote end.  Our end can be recalculated at any
1934  *   time.  The common WSCALE values can be encoded in a 3-bit table.
1935  *   Uncommon values are captured by the next lower value in the table
1936  *   making us under-estimate the available window size halving our
1937  *   theoretically possible maximum throughput for that connection.
1938  * SACK: Greatly assists in packet loss recovery and requires 1 bit.
1939  * TIMESTAMP and SIGNATURE is not encoded because they are permanent options
1940  *   that are included in all segments on a connection.  We enable them when
1941  *   the ACK has them.
1942  *
1943  * Security of syncookies and attack vectors:
1944  *
1945  * The MAC is computed over (faddr||laddr||fport||lport||irs||flags||secmod)
1946  * together with the gloabl secret to make it unique per connection attempt.
1947  * Thus any change of any of those parameters results in a different MAC output
1948  * in an unpredictable way unless a collision is encountered.  24 bits of the
1949  * MAC are embedded into the ISS.
1950  *
1951  * To prevent replay attacks two rotating global secrets are updated with a
1952  * new random value every 15 seconds.  The life-time of a syncookie is thus
1953  * 15-30 seconds.
1954  *
1955  * Vector 1: Attacking the secret.  This requires finding a weakness in the
1956  * MAC itself or the way it is used here.  The attacker can do a chosen plain
1957  * text attack by varying and testing the all parameters under his control.
1958  * The strength depends on the size and randomness of the secret, and the
1959  * cryptographic security of the MAC function.  Due to the constant updating
1960  * of the secret the attacker has at most 29.999 seconds to find the secret
1961  * and launch spoofed connections.  After that he has to start all over again.
1962  *
1963  * Vector 2: Collision attack on the MAC of a single ACK.  With a 24 bit MAC
1964  * size an average of 4,823 attempts are required for a 50% chance of success
1965  * to spoof a single syncookie (birthday collision paradox).  However the
1966  * attacker is blind and doesn't know if one of his attempts succeeded unless
1967  * he has a side channel to interfere success from.  A single connection setup
1968  * success average of 90% requires 8,790 packets, 99.99% requires 17,578 packets.
1969  * This many attempts are required for each one blind spoofed connection.  For
1970  * every additional spoofed connection he has to launch another N attempts.
1971  * Thus for a sustained rate 100 spoofed connections per second approximately
1972  * 1,800,000 packets per second would have to be sent.
1973  *
1974  * NB: The MAC function should be fast so that it doesn't become a CPU
1975  * exhaustion attack vector itself.
1976  *
1977  * References:
1978  *  RFC4987 TCP SYN Flooding Attacks and Common Mitigations
1979  *  SYN cookies were first proposed by cryptographer Dan J. Bernstein in 1996
1980  *   http://cr.yp.to/syncookies.html    (overview)
1981  *   http://cr.yp.to/syncookies/archive (details)
1982  *
1983  *
1984  * Schematic construction of a syncookie enabled Initial Sequence Number:
1985  *  0        1         2         3
1986  *  12345678901234567890123456789012
1987  * |xxxxxxxxxxxxxxxxxxxxxxxxWWWMMMSP|
1988  *
1989  *  x 24 MAC (truncated)
1990  *  W  3 Send Window Scale index
1991  *  M  3 MSS index
1992  *  S  1 SACK permitted
1993  *  P  1 Odd/even secret
1994  */
1995 
1996 /*
1997  * Distribution and probability of certain MSS values.  Those in between are
1998  * rounded down to the next lower one.
1999  * [An Analysis of TCP Maximum Segment Sizes, S. Alcock and R. Nelson, 2011]
2000  *                            .2%  .3%   5%    7%    7%    20%   15%   45%
2001  */
2002 static int tcp_sc_msstab[] = { 216, 536, 1200, 1360, 1400, 1440, 1452, 1460 };
2003 
2004 /*
2005  * Distribution and probability of certain WSCALE values.  We have to map the
2006  * (send) window scale (shift) option with a range of 0-14 from 4 bits into 3
2007  * bits based on prevalence of certain values.  Where we don't have an exact
2008  * match for are rounded down to the next lower one letting us under-estimate
2009  * the true available window.  At the moment this would happen only for the
2010  * very uncommon values 3, 5 and those above 8 (more than 16MB socket buffer
2011  * and window size).  The absence of the WSCALE option (no scaling in either
2012  * direction) is encoded with index zero.
2013  * [WSCALE values histograms, Allman, 2012]
2014  *                            X 10 10 35  5  6 14 10%   by host
2015  *                            X 11  4  5  5 18 49  3%   by connections
2016  */
2017 static int tcp_sc_wstab[] = { 0, 0, 1, 2, 4, 6, 7, 8 };
2018 
2019 /*
2020  * Compute the MAC for the SYN cookie.  SIPHASH-2-4 is chosen for its speed
2021  * and good cryptographic properties.
2022  */
2023 static uint32_t
2024 syncookie_mac(struct in_conninfo *inc, tcp_seq irs, uint8_t flags,
2025     uint8_t *secbits, uintptr_t secmod)
2026 {
2027 	SIPHASH_CTX ctx;
2028 	uint32_t siphash[2];
2029 
2030 	SipHash24_Init(&ctx);
2031 	SipHash_SetKey(&ctx, secbits);
2032 	switch (inc->inc_flags & INC_ISIPV6) {
2033 #ifdef INET
2034 	case 0:
2035 		SipHash_Update(&ctx, &inc->inc_faddr, sizeof(inc->inc_faddr));
2036 		SipHash_Update(&ctx, &inc->inc_laddr, sizeof(inc->inc_laddr));
2037 		break;
2038 #endif
2039 #ifdef INET6
2040 	case INC_ISIPV6:
2041 		SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(inc->inc6_faddr));
2042 		SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(inc->inc6_laddr));
2043 		break;
2044 #endif
2045 	}
2046 	SipHash_Update(&ctx, &inc->inc_fport, sizeof(inc->inc_fport));
2047 	SipHash_Update(&ctx, &inc->inc_lport, sizeof(inc->inc_lport));
2048 	SipHash_Update(&ctx, &irs, sizeof(irs));
2049 	SipHash_Update(&ctx, &flags, sizeof(flags));
2050 	SipHash_Update(&ctx, &secmod, sizeof(secmod));
2051 	SipHash_Final((u_int8_t *)&siphash, &ctx);
2052 
2053 	return (siphash[0] ^ siphash[1]);
2054 }
2055 
2056 static tcp_seq
2057 syncookie_generate(struct syncache_head *sch, struct syncache *sc)
2058 {
2059 	u_int i, secbit, wscale;
2060 	uint32_t iss, hash;
2061 	uint8_t *secbits;
2062 	union syncookie cookie;
2063 
2064 	cookie.cookie = 0;
2065 
2066 	/* Map our computed MSS into the 3-bit index. */
2067 	for (i = nitems(tcp_sc_msstab) - 1;
2068 	     tcp_sc_msstab[i] > sc->sc_peer_mss && i > 0;
2069 	     i--)
2070 		;
2071 	cookie.flags.mss_idx = i;
2072 
2073 	/*
2074 	 * Map the send window scale into the 3-bit index but only if
2075 	 * the wscale option was received.
2076 	 */
2077 	if (sc->sc_flags & SCF_WINSCALE) {
2078 		wscale = sc->sc_requested_s_scale;
2079 		for (i = nitems(tcp_sc_wstab) - 1;
2080 		    tcp_sc_wstab[i] > wscale && i > 0;
2081 		     i--)
2082 			;
2083 		cookie.flags.wscale_idx = i;
2084 	}
2085 
2086 	/* Can we do SACK? */
2087 	if (sc->sc_flags & SCF_SACK)
2088 		cookie.flags.sack_ok = 1;
2089 
2090 	/* Which of the two secrets to use. */
2091 	secbit = V_tcp_syncache.secret.oddeven & 0x1;
2092 	cookie.flags.odd_even = secbit;
2093 
2094 	secbits = V_tcp_syncache.secret.key[secbit];
2095 	hash = syncookie_mac(&sc->sc_inc, sc->sc_irs, cookie.cookie, secbits,
2096 	    (uintptr_t)sch);
2097 
2098 	/*
2099 	 * Put the flags into the hash and XOR them to get better ISS number
2100 	 * variance.  This doesn't enhance the cryptographic strength and is
2101 	 * done to prevent the 8 cookie bits from showing up directly on the
2102 	 * wire.
2103 	 */
2104 	iss = hash & ~0xff;
2105 	iss |= cookie.cookie ^ (hash >> 24);
2106 
2107 	TCPSTAT_INC(tcps_sc_sendcookie);
2108 	return (iss);
2109 }
2110 
2111 static struct syncache *
2112 syncookie_lookup(struct in_conninfo *inc, struct syncache_head *sch,
2113     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2114     struct socket *lso)
2115 {
2116 	uint32_t hash;
2117 	uint8_t *secbits;
2118 	tcp_seq ack, seq;
2119 	int wnd, wscale = 0;
2120 	union syncookie cookie;
2121 
2122 	/*
2123 	 * Pull information out of SYN-ACK/ACK and revert sequence number
2124 	 * advances.
2125 	 */
2126 	ack = th->th_ack - 1;
2127 	seq = th->th_seq - 1;
2128 
2129 	/*
2130 	 * Unpack the flags containing enough information to restore the
2131 	 * connection.
2132 	 */
2133 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
2134 
2135 	/* Which of the two secrets to use. */
2136 	secbits = V_tcp_syncache.secret.key[cookie.flags.odd_even];
2137 
2138 	hash = syncookie_mac(inc, seq, cookie.cookie, secbits, (uintptr_t)sch);
2139 
2140 	/* The recomputed hash matches the ACK if this was a genuine cookie. */
2141 	if ((ack & ~0xff) != (hash & ~0xff))
2142 		return (NULL);
2143 
2144 	/* Fill in the syncache values. */
2145 	sc->sc_flags = 0;
2146 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
2147 	sc->sc_ipopts = NULL;
2148 
2149 	sc->sc_irs = seq;
2150 	sc->sc_iss = ack;
2151 
2152 	switch (inc->inc_flags & INC_ISIPV6) {
2153 #ifdef INET
2154 	case 0:
2155 		sc->sc_ip_ttl = sotoinpcb(lso)->inp_ip_ttl;
2156 		sc->sc_ip_tos = sotoinpcb(lso)->inp_ip_tos;
2157 		break;
2158 #endif
2159 #ifdef INET6
2160 	case INC_ISIPV6:
2161 		if (sotoinpcb(lso)->inp_flags & IN6P_AUTOFLOWLABEL)
2162 			sc->sc_flowlabel = sc->sc_iss & IPV6_FLOWLABEL_MASK;
2163 		break;
2164 #endif
2165 	}
2166 
2167 	sc->sc_peer_mss = tcp_sc_msstab[cookie.flags.mss_idx];
2168 
2169 	/* We can simply recompute receive window scale we sent earlier. */
2170 	while (wscale < TCP_MAX_WINSHIFT && (TCP_MAXWIN << wscale) < sb_max)
2171 		wscale++;
2172 
2173 	/* Only use wscale if it was enabled in the orignal SYN. */
2174 	if (cookie.flags.wscale_idx > 0) {
2175 		sc->sc_requested_r_scale = wscale;
2176 		sc->sc_requested_s_scale = tcp_sc_wstab[cookie.flags.wscale_idx];
2177 		sc->sc_flags |= SCF_WINSCALE;
2178 	}
2179 
2180 	wnd = lso->sol_sbrcv_hiwat;
2181 	wnd = imax(wnd, 0);
2182 	wnd = imin(wnd, TCP_MAXWIN);
2183 	sc->sc_wnd = wnd;
2184 
2185 	if (cookie.flags.sack_ok)
2186 		sc->sc_flags |= SCF_SACK;
2187 
2188 	if (to->to_flags & TOF_TS) {
2189 		sc->sc_flags |= SCF_TIMESTAMP;
2190 		sc->sc_tsreflect = to->to_tsval;
2191 		sc->sc_tsoff = tcp_new_ts_offset(inc);
2192 	}
2193 
2194 	if (to->to_flags & TOF_SIGNATURE)
2195 		sc->sc_flags |= SCF_SIGNATURE;
2196 
2197 	sc->sc_rxmits = 0;
2198 
2199 	TCPSTAT_INC(tcps_sc_recvcookie);
2200 	return (sc);
2201 }
2202 
2203 #ifdef INVARIANTS
2204 static int
2205 syncookie_cmp(struct in_conninfo *inc, struct syncache_head *sch,
2206     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2207     struct socket *lso)
2208 {
2209 	struct syncache scs, *scx;
2210 	char *s;
2211 
2212 	bzero(&scs, sizeof(scs));
2213 	scx = syncookie_lookup(inc, sch, &scs, th, to, lso);
2214 
2215 	if ((s = tcp_log_addrs(inc, th, NULL, NULL)) == NULL)
2216 		return (0);
2217 
2218 	if (scx != NULL) {
2219 		if (sc->sc_peer_mss != scx->sc_peer_mss)
2220 			log(LOG_DEBUG, "%s; %s: mss different %i vs %i\n",
2221 			    s, __func__, sc->sc_peer_mss, scx->sc_peer_mss);
2222 
2223 		if (sc->sc_requested_r_scale != scx->sc_requested_r_scale)
2224 			log(LOG_DEBUG, "%s; %s: rwscale different %i vs %i\n",
2225 			    s, __func__, sc->sc_requested_r_scale,
2226 			    scx->sc_requested_r_scale);
2227 
2228 		if (sc->sc_requested_s_scale != scx->sc_requested_s_scale)
2229 			log(LOG_DEBUG, "%s; %s: swscale different %i vs %i\n",
2230 			    s, __func__, sc->sc_requested_s_scale,
2231 			    scx->sc_requested_s_scale);
2232 
2233 		if ((sc->sc_flags & SCF_SACK) != (scx->sc_flags & SCF_SACK))
2234 			log(LOG_DEBUG, "%s; %s: SACK different\n", s, __func__);
2235 	}
2236 
2237 	if (s != NULL)
2238 		free(s, M_TCPLOG);
2239 	return (0);
2240 }
2241 #endif /* INVARIANTS */
2242 
2243 static void
2244 syncookie_reseed(void *arg)
2245 {
2246 	struct tcp_syncache *sc = arg;
2247 	uint8_t *secbits;
2248 	int secbit;
2249 
2250 	/*
2251 	 * Reseeding the secret doesn't have to be protected by a lock.
2252 	 * It only must be ensured that the new random values are visible
2253 	 * to all CPUs in a SMP environment.  The atomic with release
2254 	 * semantics ensures that.
2255 	 */
2256 	secbit = (sc->secret.oddeven & 0x1) ? 0 : 1;
2257 	secbits = sc->secret.key[secbit];
2258 	arc4rand(secbits, SYNCOOKIE_SECRET_SIZE, 0);
2259 	atomic_add_rel_int(&sc->secret.oddeven, 1);
2260 
2261 	/* Reschedule ourself. */
2262 	callout_schedule(&sc->secret.reseed, SYNCOOKIE_LIFETIME * hz);
2263 }
2264 
2265 /*
2266  * Exports the syncache entries to userland so that netstat can display
2267  * them alongside the other sockets.  This function is intended to be
2268  * called only from tcp_pcblist.
2269  *
2270  * Due to concurrency on an active system, the number of pcbs exported
2271  * may have no relation to max_pcbs.  max_pcbs merely indicates the
2272  * amount of space the caller allocated for this function to use.
2273  */
2274 int
2275 syncache_pcblist(struct sysctl_req *req, int max_pcbs, int *pcbs_exported)
2276 {
2277 	struct xtcpcb xt;
2278 	struct syncache *sc;
2279 	struct syncache_head *sch;
2280 	int count, error, i;
2281 
2282 	for (count = 0, error = 0, i = 0; i < V_tcp_syncache.hashsize; i++) {
2283 		sch = &V_tcp_syncache.hashbase[i];
2284 		SCH_LOCK(sch);
2285 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
2286 			if (count >= max_pcbs) {
2287 				SCH_UNLOCK(sch);
2288 				goto exit;
2289 			}
2290 			if (cr_cansee(req->td->td_ucred, sc->sc_cred) != 0)
2291 				continue;
2292 			bzero(&xt, sizeof(xt));
2293 			xt.xt_len = sizeof(xt);
2294 			if (sc->sc_inc.inc_flags & INC_ISIPV6)
2295 				xt.xt_inp.inp_vflag = INP_IPV6;
2296 			else
2297 				xt.xt_inp.inp_vflag = INP_IPV4;
2298 			bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc,
2299 			    sizeof (struct in_conninfo));
2300 			xt.t_state = TCPS_SYN_RECEIVED;
2301 			xt.xt_inp.xi_socket.xso_protocol = IPPROTO_TCP;
2302 			xt.xt_inp.xi_socket.xso_len = sizeof (struct xsocket);
2303 			xt.xt_inp.xi_socket.so_type = SOCK_STREAM;
2304 			xt.xt_inp.xi_socket.so_state = SS_ISCONNECTING;
2305 			error = SYSCTL_OUT(req, &xt, sizeof xt);
2306 			if (error) {
2307 				SCH_UNLOCK(sch);
2308 				goto exit;
2309 			}
2310 			count++;
2311 		}
2312 		SCH_UNLOCK(sch);
2313 	}
2314 exit:
2315 	*pcbs_exported = count;
2316 	return error;
2317 }
2318