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