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