xref: /freebsd/sys/netinet/tcp_syncache.c (revision c2a55efd74cccb3d4e7b9037b240ad062c203bb8)
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 	 * Ok, create the full blown connection, and set things up
776 	 * as they would have been set up if we had created the
777 	 * connection when the SYN arrived.
778 	 */
779 	if ((so = solisten_clone(lso)) == NULL)
780 		goto allocfail;
781 #ifdef MAC
782 	mac_socketpeer_set_from_mbuf(m, so);
783 #endif
784 	error = in_pcballoc(so, &V_tcbinfo);
785 	if (error) {
786 		sodealloc(so);
787 		goto allocfail;
788 	}
789 	inp = sotoinpcb(so);
790 	if ((tp = tcp_newtcpcb(inp, sototcpcb(lso))) == NULL) {
791 		in_pcbfree(inp);
792 		sodealloc(so);
793 		goto allocfail;
794 	}
795 	inp->inp_inc.inc_flags = sc->sc_inc.inc_flags;
796 #ifdef INET6
797 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
798 		inp->inp_vflag &= ~INP_IPV4;
799 		inp->inp_vflag |= INP_IPV6;
800 		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
801 	} else {
802 		inp->inp_vflag &= ~INP_IPV6;
803 		inp->inp_vflag |= INP_IPV4;
804 #endif
805 		inp->inp_ip_ttl = sc->sc_ip_ttl;
806 		inp->inp_ip_tos = sc->sc_ip_tos;
807 		inp->inp_laddr = sc->sc_inc.inc_laddr;
808 #ifdef INET6
809 	}
810 #endif
811 	inp->inp_lport = sc->sc_inc.inc_lport;
812 #ifdef INET6
813 	if (inp->inp_vflag & INP_IPV6PROTO) {
814 		struct inpcb *oinp = sotoinpcb(lso);
815 
816 		/*
817 		 * Inherit socket options from the listening socket.
818 		 * Note that in6p_inputopts are not (and should not be)
819 		 * copied, since it stores previously received options and is
820 		 * used to detect if each new option is different than the
821 		 * previous one and hence should be passed to a user.
822 		 * If we copied in6p_inputopts, a user would not be able to
823 		 * receive options just after calling the accept system call.
824 		 */
825 		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
826 		if (oinp->in6p_outputopts)
827 			inp->in6p_outputopts =
828 			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
829 		inp->in6p_hops = oinp->in6p_hops;
830 	}
831 
832 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
833 		struct sockaddr_in6 sin6;
834 
835 		sin6.sin6_family = AF_INET6;
836 		sin6.sin6_len = sizeof(sin6);
837 		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
838 		sin6.sin6_port = sc->sc_inc.inc_fport;
839 		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
840 		INP_HASH_WLOCK(&V_tcbinfo);
841 		error = in6_pcbconnect(inp, &sin6, thread0.td_ucred, false);
842 		INP_HASH_WUNLOCK(&V_tcbinfo);
843 		if (error != 0)
844 			goto abort;
845 		/* Override flowlabel from in6_pcbconnect. */
846 		inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
847 		inp->inp_flow |= sc->sc_flowlabel;
848 	}
849 #endif /* INET6 */
850 #if defined(INET) && defined(INET6)
851 	else
852 #endif
853 #ifdef INET
854 	{
855 		struct sockaddr_in sin;
856 
857 		inp->inp_options = (m) ? ip_srcroute(m) : NULL;
858 
859 		if (inp->inp_options == NULL) {
860 			inp->inp_options = sc->sc_ipopts;
861 			sc->sc_ipopts = NULL;
862 		}
863 
864 		sin.sin_family = AF_INET;
865 		sin.sin_len = sizeof(sin);
866 		sin.sin_addr = sc->sc_inc.inc_faddr;
867 		sin.sin_port = sc->sc_inc.inc_fport;
868 		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
869 		INP_HASH_WLOCK(&V_tcbinfo);
870 		error = in_pcbconnect(inp, &sin, thread0.td_ucred);
871 		INP_HASH_WUNLOCK(&V_tcbinfo);
872 		if (error != 0)
873 			goto abort;
874 	}
875 #endif /* INET */
876 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
877 	/* Copy old policy into new socket's. */
878 	if (ipsec_copy_pcbpolicy(sotoinpcb(lso), inp) != 0)
879 		printf("syncache_socket: could not copy policy\n");
880 #endif
881 	if (sc->sc_flowtype != M_HASHTYPE_NONE) {
882 		inp->inp_flowid = sc->sc_flowid;
883 		inp->inp_flowtype = sc->sc_flowtype;
884 	} else {
885 		  /* assign flowid by software RSS hash */
886 #ifdef INET6
887 		  if (sc->sc_inc.inc_flags & INC_ISIPV6) {
888 			rss_proto_software_hash_v6(&inp->in6p_faddr,
889 						   &inp->in6p_laddr,
890 						   inp->inp_fport,
891 						   inp->inp_lport,
892 						   IPPROTO_TCP,
893 						   &inp->inp_flowid,
894 						   &inp->inp_flowtype);
895 		  } else
896 #endif	/* INET6 */
897 		  {
898 #ifdef INET
899 			rss_proto_software_hash_v4(inp->inp_faddr,
900 						   inp->inp_laddr,
901 						   inp->inp_fport,
902 						   inp->inp_lport,
903 						   IPPROTO_TCP,
904 						   &inp->inp_flowid,
905 						   &inp->inp_flowtype);
906 #endif /* INET */
907 		  }
908 	}
909 #ifdef NUMA
910 	inp->inp_numa_domain = sc->sc_numa_domain;
911 #endif
912 
913 	tp->t_state = TCPS_SYN_RECEIVED;
914 	tp->iss = sc->sc_iss;
915 	tp->irs = sc->sc_irs;
916 	tp->t_port = sc->sc_port;
917 	tcp_rcvseqinit(tp);
918 	tcp_sendseqinit(tp);
919 	tp->snd_wl1 = sc->sc_irs;
920 	tp->snd_max = tp->iss + 1;
921 	tp->snd_nxt = tp->iss + 1;
922 	tp->rcv_up = sc->sc_irs + 1;
923 	tp->rcv_wnd = sc->sc_wnd;
924 	tp->rcv_adv += tp->rcv_wnd;
925 	tp->last_ack_sent = tp->rcv_nxt;
926 
927 	tp->t_flags = sototcpcb(lso)->t_flags &
928 	    (TF_LRD|TF_NOPUSH|TF_NODELAY);
929 	if (sc->sc_flags & SCF_NOOPT)
930 		tp->t_flags |= TF_NOOPT;
931 	else {
932 		if (sc->sc_flags & SCF_WINSCALE) {
933 			tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
934 			tp->snd_scale = sc->sc_requested_s_scale;
935 			tp->request_r_scale = sc->sc_requested_r_scale;
936 		}
937 		if (sc->sc_flags & SCF_TIMESTAMP) {
938 			tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
939 			tp->ts_recent = sc->sc_tsreflect;
940 			tp->ts_recent_age = tcp_ts_getticks();
941 			tp->ts_offset = sc->sc_tsoff;
942 		}
943 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
944 		if (sc->sc_flags & SCF_SIGNATURE)
945 			tp->t_flags |= TF_SIGNATURE;
946 #endif
947 		if (sc->sc_flags & SCF_SACK)
948 			tp->t_flags |= TF_SACK_PERMIT;
949 	}
950 
951 	tcp_ecn_syncache_socket(tp, sc);
952 
953 	/*
954 	 * Set up MSS and get cached values from tcp_hostcache.
955 	 * This might overwrite some of the defaults we just set.
956 	 */
957 	tcp_mss(tp, sc->sc_peer_mss);
958 
959 	/*
960 	 * If the SYN,ACK was retransmitted, indicate that CWND to be
961 	 * limited to one segment in cc_conn_init().
962 	 * NB: sc_rxmits counts all SYN,ACK transmits, not just retransmits.
963 	 */
964 	if (sc->sc_rxmits > 1)
965 		tp->snd_cwnd = 1;
966 
967 	/* Copy over the challenge ACK state. */
968 	tp->t_challenge_ack_end = sc->sc_challenge_ack_end;
969 	tp->t_challenge_ack_cnt = sc->sc_challenge_ack_cnt;
970 
971 #ifdef TCP_OFFLOAD
972 	/*
973 	 * Allow a TOE driver to install its hooks.  Note that we hold the
974 	 * pcbinfo lock too and that prevents tcp_usr_accept from accepting a
975 	 * new connection before the TOE driver has done its thing.
976 	 */
977 	if (ADDED_BY_TOE(sc)) {
978 		struct toedev *tod = sc->sc_tod;
979 
980 		tod->tod_offload_socket(tod, sc->sc_todctx, so);
981 	}
982 #endif
983 #ifdef TCP_BLACKBOX
984 	/*
985 	 * Inherit the log state from the listening socket, if
986 	 * - the log state of the listening socket is not off and
987 	 * - the listening socket was not auto selected from all sessions and
988 	 * - a log id is not set on the listening socket.
989 	 * This avoids inheriting a log state which was automatically set.
990 	 */
991 	if ((tcp_get_bblog_state(sototcpcb(lso)) != TCP_LOG_STATE_OFF) &&
992 	    ((sototcpcb(lso)->t_flags2 & TF2_LOG_AUTO) == 0) &&
993 	    (sototcpcb(lso)->t_lib == NULL)) {
994 		tcp_log_state_change(tp, tcp_get_bblog_state(sototcpcb(lso)));
995 	}
996 #endif
997 	/*
998 	 * Copy and activate timers.
999 	 */
1000 	tp->t_maxunacktime = sototcpcb(lso)->t_maxunacktime;
1001 	tp->t_keepinit = sototcpcb(lso)->t_keepinit;
1002 	tp->t_keepidle = sototcpcb(lso)->t_keepidle;
1003 	tp->t_keepintvl = sototcpcb(lso)->t_keepintvl;
1004 	tp->t_keepcnt = sototcpcb(lso)->t_keepcnt;
1005 	tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
1006 
1007 	TCPSTAT_INC(tcps_accepts);
1008 	TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, TCPS_LISTEN);
1009 
1010 	if (!solisten_enqueue(so, SS_ISCONNECTED))
1011 		tp->t_flags |= TF_SONOTCONN;
1012 	/* Can we inherit anything from the listener? */
1013 	if (tp->t_fb->tfb_inherit != NULL) {
1014 		(*tp->t_fb->tfb_inherit)(tp, sotoinpcb(lso));
1015 	}
1016 	return (so);
1017 
1018 allocfail:
1019 	/*
1020 	 * Drop the connection; we will either send a RST or have the peer
1021 	 * retransmit its SYN again after its RTO and try again.
1022 	 */
1023 	if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
1024 		log(LOG_DEBUG, "%s; %s: Socket create failed "
1025 		    "due to limits or memory shortage\n",
1026 		    s, __func__);
1027 		free(s, M_TCPLOG);
1028 	}
1029 	TCPSTAT_INC(tcps_listendrop);
1030 	return (NULL);
1031 
1032 abort:
1033 	tcp_discardcb(tp);
1034 	in_pcbfree(inp);
1035 	sodealloc(so);
1036 	if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
1037 		log(LOG_DEBUG, "%s; %s: in%s_pcbconnect failed with error %i\n",
1038 		    s, __func__, (sc->sc_inc.inc_flags & INC_ISIPV6) ? "6" : "",
1039 		    error);
1040 		free(s, M_TCPLOG);
1041 	}
1042 	TCPSTAT_INC(tcps_listendrop);
1043 	return (NULL);
1044 }
1045 
1046 /*
1047  * This function gets called when we receive an ACK for a
1048  * socket in the LISTEN state.  We look up the connection
1049  * in the syncache, and if its there, we pull it out of
1050  * the cache and turn it into a full-blown connection in
1051  * the SYN-RECEIVED state.
1052  *
1053  * On syncache_socket() success the newly created socket
1054  * has its underlying inp locked.
1055  *
1056  * *lsop is updated, if and only if 1 is returned.
1057  */
1058 int
1059 syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1060     struct socket **lsop, struct mbuf *m, uint16_t port)
1061 {
1062 	struct syncache *sc;
1063 	struct syncache_head *sch;
1064 	struct syncache scs;
1065 	char *s;
1066 	bool locked;
1067 
1068 	NET_EPOCH_ASSERT();
1069 	KASSERT((tcp_get_flags(th) & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK,
1070 	    ("%s: can handle only ACK", __func__));
1071 
1072 	if (syncache_cookiesonly()) {
1073 		sc = NULL;
1074 		sch = syncache_hashbucket(inc);
1075 		locked = false;
1076 	} else {
1077 		sc = syncache_lookup(inc, &sch);	/* returns locked sch */
1078 		locked = true;
1079 		SCH_LOCK_ASSERT(sch);
1080 	}
1081 
1082 #ifdef INVARIANTS
1083 	/*
1084 	 * Test code for syncookies comparing the syncache stored
1085 	 * values with the reconstructed values from the cookie.
1086 	 */
1087 	if (sc != NULL)
1088 		syncookie_cmp(inc, sch, sc, th, to, *lsop, port);
1089 #endif
1090 
1091 	if (sc == NULL) {
1092 		if (locked) {
1093 			/*
1094 			 * The syncache is currently in use (neither disabled,
1095 			 * nor paused), but no entry was found.
1096 			 */
1097 			if (!V_tcp_syncookies) {
1098 				/*
1099 				 * Since no syncookies are used in case of
1100 				 * a bucket overflow, don't even check for
1101 				 * a valid syncookie.
1102 				 */
1103 				SCH_UNLOCK(sch);
1104 				TCPSTAT_INC(tcps_sc_spurcookie);
1105 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1106 					log(LOG_DEBUG, "%s; %s: Spurious ACK, "
1107 					    "segment rejected "
1108 					    "(syncookies disabled)\n",
1109 					    s, __func__);
1110 					free(s, M_TCPLOG);
1111 				}
1112 				return (0);
1113 			}
1114 			if (sch->sch_last_overflow <
1115 			    time_uptime - SYNCOOKIE_LIFETIME) {
1116 				/*
1117 				 * Since the bucket did not overflow recently,
1118 				 * don't even check for a valid syncookie.
1119 				 */
1120 				SCH_UNLOCK(sch);
1121 				TCPSTAT_INC(tcps_sc_spurcookie);
1122 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1123 					log(LOG_DEBUG, "%s; %s: Spurious ACK, "
1124 					    "segment rejected "
1125 					    "(no syncache entry)\n",
1126 					    s, __func__);
1127 					free(s, M_TCPLOG);
1128 				}
1129 				return (0);
1130 			}
1131 			SCH_UNLOCK(sch);
1132 		}
1133 		bzero(&scs, sizeof(scs));
1134 		/*
1135 		 * Now check, if the syncookie is valid. If it is, create an on
1136 		 * stack syncache entry.
1137 		 */
1138 		if (syncookie_expand(inc, sch, &scs, th, to, *lsop, port)) {
1139 			sc = &scs;
1140 			TCPSTAT_INC(tcps_sc_recvcookie);
1141 		} else {
1142 			TCPSTAT_INC(tcps_sc_failcookie);
1143 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1144 				log(LOG_DEBUG, "%s; %s: Segment failed "
1145 				    "SYNCOOKIE authentication, segment rejected "
1146 				    "(probably spoofed)\n", s, __func__);
1147 				free(s, M_TCPLOG);
1148 			}
1149 			return (0);
1150 		}
1151 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1152 		/* If received ACK has MD5 signature, check it. */
1153 		if ((to->to_flags & TOF_SIGNATURE) != 0 &&
1154 		    (!TCPMD5_ENABLED() ||
1155 		    TCPMD5_INPUT(m, th, to->to_signature) != 0)) {
1156 			/* Drop the ACK. */
1157 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1158 				log(LOG_DEBUG, "%s; %s: Segment rejected, "
1159 				    "MD5 signature doesn't match.\n",
1160 				    s, __func__);
1161 				free(s, M_TCPLOG);
1162 			}
1163 			TCPSTAT_INC(tcps_sig_err_sigopt);
1164 			return (-1); /* Do not send RST */
1165 		}
1166 #endif /* TCP_SIGNATURE */
1167 		if (m != NULL && M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
1168 			sc->sc_flowid = m->m_pkthdr.flowid;
1169 			sc->sc_flowtype = M_HASHTYPE_GET(m);
1170 		}
1171 #ifdef NUMA
1172 		sc->sc_numa_domain = m ? m->m_pkthdr.numa_domain : M_NODOM;
1173 #endif
1174 		TCPSTATES_INC(TCPS_SYN_RECEIVED);
1175 	} else {
1176 		if (sc->sc_port != port) {
1177 			SCH_UNLOCK(sch);
1178 			return (0);
1179 		}
1180 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1181 		/*
1182 		 * If listening socket requested TCP digests, check that
1183 		 * received ACK has signature and it is correct.
1184 		 * If not, drop the ACK and leave sc entry in the cache,
1185 		 * because SYN was received with correct signature.
1186 		 */
1187 		if (sc->sc_flags & SCF_SIGNATURE) {
1188 			if ((to->to_flags & TOF_SIGNATURE) == 0) {
1189 				/* No signature */
1190 				TCPSTAT_INC(tcps_sig_err_nosigopt);
1191 				SCH_UNLOCK(sch);
1192 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1193 					log(LOG_DEBUG, "%s; %s: Segment "
1194 					    "rejected, MD5 signature wasn't "
1195 					    "provided.\n", s, __func__);
1196 					free(s, M_TCPLOG);
1197 				}
1198 				return (-1); /* Do not send RST */
1199 			}
1200 			if (!TCPMD5_ENABLED() ||
1201 			    TCPMD5_INPUT(m, th, to->to_signature) != 0) {
1202 				/* Doesn't match or no SA */
1203 				SCH_UNLOCK(sch);
1204 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1205 					log(LOG_DEBUG, "%s; %s: Segment "
1206 					    "rejected, MD5 signature doesn't "
1207 					    "match.\n", s, __func__);
1208 					free(s, M_TCPLOG);
1209 				}
1210 				return (-1); /* Do not send RST */
1211 			}
1212 		}
1213 #endif /* TCP_SIGNATURE */
1214 
1215 		/*
1216 		 * RFC 7323 PAWS: If we have a timestamp on this segment and
1217 		 * it's less than ts_recent, drop it.
1218 		 * XXXMT: RFC 7323 also requires to send an ACK.
1219 		 *        In tcp_input.c this is only done for TCP segments
1220 		 *        with user data, so be consistent here and just drop
1221 		 *        the segment.
1222 		 */
1223 		if (sc->sc_flags & SCF_TIMESTAMP && to->to_flags & TOF_TS &&
1224 		    TSTMP_LT(to->to_tsval, sc->sc_tsreflect)) {
1225 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1226 				log(LOG_DEBUG,
1227 				    "%s; %s: SEG.TSval %u < TS.Recent %u, "
1228 				    "segment dropped\n", s, __func__,
1229 				    to->to_tsval, sc->sc_tsreflect);
1230 			}
1231 			SCH_UNLOCK(sch);
1232 			free(s, M_TCPLOG);
1233 			return (-1);  /* Do not send RST */
1234 		}
1235 
1236 		/*
1237 		 * If timestamps were not negotiated during SYN/ACK and a
1238 		 * segment with a timestamp is received, ignore the
1239 		 * timestamp and process the packet normally.
1240 		 * See section 3.2 of RFC 7323.
1241 		 */
1242 		if (!(sc->sc_flags & SCF_TIMESTAMP) &&
1243 		    (to->to_flags & TOF_TS)) {
1244 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1245 				log(LOG_DEBUG, "%s; %s: Timestamp not "
1246 				    "expected, segment processed normally\n",
1247 				    s, __func__);
1248 				free(s, M_TCPLOG);
1249 			}
1250 		}
1251 
1252 		/*
1253 		 * If timestamps were negotiated during SYN/ACK and a
1254 		 * segment without a timestamp is received, silently drop
1255 		 * the segment, unless the missing timestamps are tolerated.
1256 		 * See section 3.2 of RFC 7323.
1257 		 */
1258 		if ((sc->sc_flags & SCF_TIMESTAMP) &&
1259 		    !(to->to_flags & TOF_TS)) {
1260 			if (V_tcp_tolerate_missing_ts) {
1261 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1262 					log(LOG_DEBUG,
1263 					    "%s; %s: Timestamp missing, "
1264 					    "segment processed normally\n",
1265 					    s, __func__);
1266 					free(s, M_TCPLOG);
1267 				}
1268 			} else {
1269 				SCH_UNLOCK(sch);
1270 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1271 					log(LOG_DEBUG,
1272 					    "%s; %s: Timestamp missing, "
1273 					    "segment silently dropped\n",
1274 					    s, __func__);
1275 					free(s, M_TCPLOG);
1276 				}
1277 				return (-1);  /* Do not send RST */
1278 			}
1279 		}
1280 
1281 		/*
1282 		 * SEG.SEQ validation:
1283 		 * The SEG.SEQ must be in the window starting at our
1284 		 * initial receive sequence number + 1.
1285 		 */
1286 		if (SEQ_LEQ(th->th_seq, sc->sc_irs) ||
1287 		    SEQ_GT(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
1288 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1289 				log(LOG_DEBUG, "%s; %s: SEQ %u != IRS+1 %u, "
1290 				    "sending challenge ACK\n",
1291 				    s, __func__, th->th_seq, sc->sc_irs + 1);
1292 			syncache_send_challenge_ack(sc);
1293 			SCH_UNLOCK(sch);
1294 			free(s, M_TCPLOG);
1295 			return (-1);  /* Do not send RST */
1296 		}
1297 
1298 		/*
1299 		 * SEG.ACK validation:
1300 		 * SEG.ACK must match our initial send sequence number + 1.
1301 		 */
1302 		if (th->th_ack != sc->sc_iss + 1) {
1303 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1304 				log(LOG_DEBUG, "%s; %s: ACK %u != ISS+1 %u, "
1305 				    "segment rejected\n",
1306 				    s, __func__, th->th_ack, sc->sc_iss + 1);
1307 			SCH_UNLOCK(sch);
1308 			free(s, M_TCPLOG);
1309 			return (0);  /* Do send RST, do not free sc. */
1310 		}
1311 
1312 		TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
1313 		sch->sch_length--;
1314 #ifdef TCP_OFFLOAD
1315 		if (ADDED_BY_TOE(sc)) {
1316 			struct toedev *tod = sc->sc_tod;
1317 
1318 			tod->tod_syncache_removed(tod, sc->sc_todctx);
1319 		}
1320 #endif
1321 		SCH_UNLOCK(sch);
1322 	}
1323 
1324 	*lsop = syncache_socket(sc, *lsop, m);
1325 
1326 	if (__predict_false(*lsop == NULL)) {
1327 		TCPSTAT_INC(tcps_sc_aborted);
1328 		TCPSTATES_DEC(TCPS_SYN_RECEIVED);
1329 	} else if (sc != &scs)
1330 		TCPSTAT_INC(tcps_sc_completed);
1331 
1332 	if (sc != &scs)
1333 		syncache_free(sc);
1334 	return (1);
1335 }
1336 
1337 static struct socket *
1338 syncache_tfo_expand(struct syncache *sc, struct socket *lso, struct mbuf *m,
1339     uint64_t response_cookie)
1340 {
1341 	struct inpcb *inp;
1342 	struct tcpcb *tp;
1343 	unsigned int *pending_counter;
1344 	struct socket *so;
1345 
1346 	NET_EPOCH_ASSERT();
1347 
1348 	pending_counter = intotcpcb(sotoinpcb(lso))->t_tfo_pending;
1349 	so = syncache_socket(sc, lso, m);
1350 	if (so == NULL) {
1351 		TCPSTAT_INC(tcps_sc_aborted);
1352 		atomic_subtract_int(pending_counter, 1);
1353 	} else {
1354 		soisconnected(so);
1355 		inp = sotoinpcb(so);
1356 		tp = intotcpcb(inp);
1357 		tp->t_flags |= TF_FASTOPEN;
1358 		tp->t_tfo_cookie.server = response_cookie;
1359 		tp->snd_max = tp->iss;
1360 		tp->snd_nxt = tp->iss;
1361 		tp->t_tfo_pending = pending_counter;
1362 		TCPSTATES_INC(TCPS_SYN_RECEIVED);
1363 		TCPSTAT_INC(tcps_sc_completed);
1364 	}
1365 
1366 	return (so);
1367 }
1368 
1369 /*
1370  * Given a LISTEN socket and an inbound SYN request, add
1371  * this to the syn cache, and send back a segment:
1372  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1373  * to the source.
1374  *
1375  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
1376  * Doing so would require that we hold onto the data and deliver it
1377  * to the application.  However, if we are the target of a SYN-flood
1378  * DoS attack, an attacker could send data which would eventually
1379  * consume all available buffer space if it were ACKed.  By not ACKing
1380  * the data, we avoid this DoS scenario.
1381  *
1382  * The exception to the above is when a SYN with a valid TCP Fast Open (TFO)
1383  * cookie is processed and a new socket is created.  In this case, any data
1384  * accompanying the SYN will be queued to the socket by tcp_input() and will
1385  * be ACKed either when the application sends response data or the delayed
1386  * ACK timer expires, whichever comes first.
1387  */
1388 struct socket *
1389 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1390     struct inpcb *inp, struct socket *so, struct mbuf *m, void *tod,
1391     void *todctx, uint8_t iptos, uint16_t port)
1392 {
1393 	struct tcpcb *tp;
1394 	struct socket *rv = NULL;
1395 	struct syncache *sc = NULL;
1396 	struct ucred *cred;
1397 	struct syncache_head *sch;
1398 	struct mbuf *ipopts = NULL;
1399 	u_int ltflags;
1400 	int win, ip_ttl, ip_tos;
1401 	char *s;
1402 #ifdef INET6
1403 	int autoflowlabel = 0;
1404 #endif
1405 #ifdef MAC
1406 	struct label *maclabel = NULL;
1407 #endif
1408 	struct syncache scs;
1409 	uint64_t tfo_response_cookie;
1410 	unsigned int *tfo_pending = NULL;
1411 	int tfo_cookie_valid = 0;
1412 	int tfo_response_cookie_valid = 0;
1413 	bool locked;
1414 
1415 	INP_RLOCK_ASSERT(inp);			/* listen socket */
1416 	KASSERT((tcp_get_flags(th) & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN,
1417 	    ("%s: unexpected tcp flags", __func__));
1418 
1419 	/*
1420 	 * Combine all so/tp operations very early to drop the INP lock as
1421 	 * soon as possible.
1422 	 */
1423 	KASSERT(SOLISTENING(so), ("%s: %p not listening", __func__, so));
1424 	tp = sototcpcb(so);
1425 	cred = V_tcp_syncache.see_other ? NULL : crhold(so->so_cred);
1426 
1427 #ifdef INET6
1428 	if (inc->inc_flags & INC_ISIPV6) {
1429 		if (inp->inp_flags & IN6P_AUTOFLOWLABEL) {
1430 			autoflowlabel = 1;
1431 		}
1432 		ip_ttl = in6_selecthlim(inp, NULL);
1433 		if ((inp->in6p_outputopts == NULL) ||
1434 		    (inp->in6p_outputopts->ip6po_tclass == -1)) {
1435 			ip_tos = 0;
1436 		} else {
1437 			ip_tos = inp->in6p_outputopts->ip6po_tclass;
1438 		}
1439 	}
1440 #endif
1441 #if defined(INET6) && defined(INET)
1442 	else
1443 #endif
1444 #ifdef INET
1445 	{
1446 		ip_ttl = inp->inp_ip_ttl;
1447 		ip_tos = inp->inp_ip_tos;
1448 	}
1449 #endif
1450 	win = so->sol_sbrcv_hiwat;
1451 	ltflags = (tp->t_flags & (TF_NOOPT | TF_SIGNATURE));
1452 
1453 	if (V_tcp_fastopen_server_enable && (tp->t_flags & TF_FASTOPEN) &&
1454 	    (tp->t_tfo_pending != NULL) &&
1455 	    (to->to_flags & TOF_FASTOPEN)) {
1456 		/*
1457 		 * Limit the number of pending TFO connections to
1458 		 * approximately half of the queue limit.  This prevents TFO
1459 		 * SYN floods from starving the service by filling the
1460 		 * listen queue with bogus TFO connections.
1461 		 */
1462 		if (atomic_fetchadd_int(tp->t_tfo_pending, 1) <=
1463 		    (so->sol_qlimit / 2)) {
1464 			int result;
1465 
1466 			result = tcp_fastopen_check_cookie(inc,
1467 			    to->to_tfo_cookie, to->to_tfo_len,
1468 			    &tfo_response_cookie);
1469 			tfo_cookie_valid = (result > 0);
1470 			tfo_response_cookie_valid = (result >= 0);
1471 		}
1472 
1473 		/*
1474 		 * Remember the TFO pending counter as it will have to be
1475 		 * decremented below if we don't make it to syncache_tfo_expand().
1476 		 */
1477 		tfo_pending = tp->t_tfo_pending;
1478 	}
1479 
1480 #ifdef MAC
1481 	if (mac_syncache_init(&maclabel) != 0) {
1482 		INP_RUNLOCK(inp);
1483 		goto done;
1484 	} else
1485 		mac_syncache_create(maclabel, inp);
1486 #endif
1487 	if (!tfo_cookie_valid)
1488 		INP_RUNLOCK(inp);
1489 
1490 	/*
1491 	 * Remember the IP options, if any.
1492 	 */
1493 #ifdef INET6
1494 	if (!(inc->inc_flags & INC_ISIPV6))
1495 #endif
1496 #ifdef INET
1497 		ipopts = (m) ? ip_srcroute(m) : NULL;
1498 #else
1499 		ipopts = NULL;
1500 #endif
1501 
1502 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1503 	/*
1504 	 * When the socket is TCP-MD5 enabled check that,
1505 	 *  - a signed packet is valid
1506 	 *  - a non-signed packet does not have a security association
1507 	 *
1508 	 *  If a signed packet fails validation or a non-signed packet has a
1509 	 *  security association, the packet will be dropped.
1510 	 */
1511 	if (ltflags & TF_SIGNATURE) {
1512 		if (to->to_flags & TOF_SIGNATURE) {
1513 			if (!TCPMD5_ENABLED() ||
1514 			    TCPMD5_INPUT(m, th, to->to_signature) != 0)
1515 				goto done;
1516 		} else {
1517 			if (TCPMD5_ENABLED() &&
1518 			    TCPMD5_INPUT(m, NULL, NULL) != ENOENT)
1519 				goto done;
1520 		}
1521 	} else if (to->to_flags & TOF_SIGNATURE)
1522 		goto done;
1523 #endif	/* TCP_SIGNATURE */
1524 	/*
1525 	 * See if we already have an entry for this connection.
1526 	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
1527 	 *
1528 	 * XXX: should the syncache be re-initialized with the contents
1529 	 * of the new SYN here (which may have different options?)
1530 	 *
1531 	 * XXX: We do not check the sequence number to see if this is a
1532 	 * real retransmit or a new connection attempt.  The question is
1533 	 * how to handle such a case; either ignore it as spoofed, or
1534 	 * drop the current entry and create a new one?
1535 	 */
1536 	if (syncache_cookiesonly()) {
1537 		sc = NULL;
1538 		sch = syncache_hashbucket(inc);
1539 		locked = false;
1540 	} else {
1541 		sc = syncache_lookup(inc, &sch);	/* returns locked sch */
1542 		locked = true;
1543 		SCH_LOCK_ASSERT(sch);
1544 	}
1545 	if (sc != NULL) {
1546 		if (tfo_cookie_valid)
1547 			INP_RUNLOCK(inp);
1548 		TCPSTAT_INC(tcps_sc_dupsyn);
1549 		if (ipopts) {
1550 			/*
1551 			 * If we were remembering a previous source route,
1552 			 * forget it and use the new one we've been given.
1553 			 */
1554 			if (sc->sc_ipopts)
1555 				(void)m_free(sc->sc_ipopts);
1556 			sc->sc_ipopts = ipopts;
1557 		}
1558 		/*
1559 		 * Update timestamp if present.
1560 		 */
1561 		if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS))
1562 			sc->sc_tsreflect = to->to_tsval;
1563 		else
1564 			sc->sc_flags &= ~SCF_TIMESTAMP;
1565 		/*
1566 		 * Adjust ECN response if needed, e.g. different
1567 		 * IP ECN field, or a fallback by the remote host.
1568 		 */
1569 		if (sc->sc_flags & SCF_ECN_MASK) {
1570 			sc->sc_flags &= ~SCF_ECN_MASK;
1571 			sc->sc_flags |= tcp_ecn_syncache_add(tcp_get_flags(th), iptos);
1572 		}
1573 #ifdef MAC
1574 		/*
1575 		 * Since we have already unconditionally allocated label
1576 		 * storage, free it up.  The syncache entry will already
1577 		 * have an initialized label we can use.
1578 		 */
1579 		mac_syncache_destroy(&maclabel);
1580 #endif
1581 		TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1582 		/* Retransmit SYN|ACK and reset retransmit count. */
1583 		if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) {
1584 			log(LOG_DEBUG, "%s; %s: Received duplicate SYN, "
1585 			    "resetting timer and retransmitting SYN|ACK\n",
1586 			    s, __func__);
1587 			free(s, M_TCPLOG);
1588 		}
1589 		if (syncache_respond(sc, TH_SYN|TH_ACK) == 0) {
1590 			sc->sc_rxmits = 0;
1591 			syncache_timeout(sc, sch, 1);
1592 			TCPSTAT_INC(tcps_sndacks);
1593 			TCPSTAT_INC(tcps_sndtotal);
1594 		} else {
1595 			/*
1596 			 * Most likely we are memory constrained, so free
1597 			 * resources.
1598 			 */
1599 			syncache_drop(sc, sch);
1600 			TCPSTAT_INC(tcps_sc_dropped);
1601 		}
1602 		SCH_UNLOCK(sch);
1603 		goto donenoprobe;
1604 	}
1605 
1606 	KASSERT(sc == NULL, ("sc(%p) != NULL", sc));
1607 	/*
1608 	 * Skip allocating a syncache entry if we are just going to discard
1609 	 * it later.
1610 	 */
1611 	if (!locked || tfo_cookie_valid) {
1612 		bzero(&scs, sizeof(scs));
1613 		sc = &scs;
1614 	} else {
1615 		sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1616 		if (sc == NULL) {
1617 			/*
1618 			 * The zone allocator couldn't provide more entries.
1619 			 * Treat this as if the cache was full; drop the oldest
1620 			 * entry and insert the new one.
1621 			 */
1622 			TCPSTAT_INC(tcps_sc_zonefail);
1623 			sc = TAILQ_LAST(&sch->sch_bucket, sch_head);
1624 			if (sc != NULL) {
1625 				sch->sch_last_overflow = time_uptime;
1626 				syncache_drop(sc, sch);
1627 				syncache_pause(inc);
1628 			}
1629 			sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1630 			if (sc == NULL) {
1631 				if (V_tcp_syncookies) {
1632 					bzero(&scs, sizeof(scs));
1633 					sc = &scs;
1634 				} else {
1635 					KASSERT(locked,
1636 					    ("%s: bucket unexpectedly unlocked",
1637 					    __func__));
1638 					SCH_UNLOCK(sch);
1639 					goto done;
1640 				}
1641 			}
1642 		}
1643 	}
1644 
1645 	KASSERT(sc != NULL, ("sc == NULL"));
1646 	if (!tfo_cookie_valid && tfo_response_cookie_valid)
1647 		sc->sc_tfo_cookie = &tfo_response_cookie;
1648 
1649 	/*
1650 	 * Fill in the syncache values.
1651 	 */
1652 #ifdef MAC
1653 	sc->sc_label = maclabel;
1654 #endif
1655 	/*
1656 	 * sc_cred is only used in syncache_pcblist() to list TCP endpoints in
1657 	 * TCPS_SYN_RECEIVED state when V_tcp_syncache.see_other is false.
1658 	 * Therefore, store the credentials only when needed:
1659 	 * - sc is allocated from the zone and not using the on stack instance.
1660 	 * - the sysctl variable net.inet.tcp.syncache.see_other is false.
1661 	 * The reference count is decremented when a zone allocated sc is
1662 	 * freed in syncache_free().
1663 	 */
1664 	if (sc != &scs && !V_tcp_syncache.see_other) {
1665 		sc->sc_cred = cred;
1666 		cred = NULL;
1667 	} else
1668 		sc->sc_cred = NULL;
1669 	sc->sc_port = port;
1670 	sc->sc_ipopts = ipopts;
1671 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1672 	sc->sc_ip_tos = ip_tos;
1673 	sc->sc_ip_ttl = ip_ttl;
1674 #ifdef TCP_OFFLOAD
1675 	sc->sc_tod = tod;
1676 	sc->sc_todctx = todctx;
1677 #endif
1678 	sc->sc_irs = th->th_seq;
1679 	sc->sc_flags = 0;
1680 	sc->sc_flowlabel = 0;
1681 
1682 	/*
1683 	 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
1684 	 * win was derived from socket earlier in the function.
1685 	 */
1686 	win = imax(win, 0);
1687 	win = imin(win, TCP_MAXWIN);
1688 	sc->sc_wnd = win;
1689 
1690 	if (V_tcp_do_rfc1323 &&
1691 	    !(ltflags & TF_NOOPT)) {
1692 		/*
1693 		 * A timestamp received in a SYN makes
1694 		 * it ok to send timestamp requests and replies.
1695 		 */
1696 		if ((to->to_flags & TOF_TS) && (V_tcp_do_rfc1323 != 2)) {
1697 			sc->sc_tsreflect = to->to_tsval;
1698 			sc->sc_flags |= SCF_TIMESTAMP;
1699 			sc->sc_tsoff = tcp_new_ts_offset(inc);
1700 		}
1701 		if ((to->to_flags & TOF_SCALE) && (V_tcp_do_rfc1323 != 3)) {
1702 			u_int wscale = 0;
1703 
1704 			/*
1705 			 * Pick the smallest possible scaling factor that
1706 			 * will still allow us to scale up to sb_max, aka
1707 			 * kern.ipc.maxsockbuf.
1708 			 *
1709 			 * We do this because there are broken firewalls that
1710 			 * will corrupt the window scale option, leading to
1711 			 * the other endpoint believing that our advertised
1712 			 * window is unscaled.  At scale factors larger than
1713 			 * 5 the unscaled window will drop below 1500 bytes,
1714 			 * leading to serious problems when traversing these
1715 			 * broken firewalls.
1716 			 *
1717 			 * With the default maxsockbuf of 256K, a scale factor
1718 			 * of 3 will be chosen by this algorithm.  Those who
1719 			 * choose a larger maxsockbuf should watch out
1720 			 * for the compatibility problems mentioned above.
1721 			 *
1722 			 * RFC1323: The Window field in a SYN (i.e., a <SYN>
1723 			 * or <SYN,ACK>) segment itself is never scaled.
1724 			 */
1725 			while (wscale < TCP_MAX_WINSHIFT &&
1726 			    (TCP_MAXWIN << wscale) < sb_max)
1727 				wscale++;
1728 			sc->sc_requested_r_scale = wscale;
1729 			sc->sc_requested_s_scale = to->to_wscale;
1730 			sc->sc_flags |= SCF_WINSCALE;
1731 		}
1732 	}
1733 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1734 	/*
1735 	 * If incoming packet has an MD5 signature, flag this in the
1736 	 * syncache so that syncache_respond() will do the right thing
1737 	 * with the SYN+ACK.
1738 	 */
1739 	if (to->to_flags & TOF_SIGNATURE)
1740 		sc->sc_flags |= SCF_SIGNATURE;
1741 #endif	/* TCP_SIGNATURE */
1742 	if (to->to_flags & TOF_SACKPERM)
1743 		sc->sc_flags |= SCF_SACK;
1744 	if (to->to_flags & TOF_MSS)
1745 		sc->sc_peer_mss = to->to_mss;	/* peer mss may be zero */
1746 	if (ltflags & TF_NOOPT)
1747 		sc->sc_flags |= SCF_NOOPT;
1748 	/* ECN Handshake */
1749 	if (V_tcp_do_ecn && (tp->t_flags2 & TF2_CANNOT_DO_ECN) == 0)
1750 		sc->sc_flags |= tcp_ecn_syncache_add(tcp_get_flags(th), iptos);
1751 
1752 	if (V_tcp_syncookies || V_tcp_syncookiesonly)
1753 		sc->sc_iss = syncookie_generate(sch, sc);
1754 	else
1755 		sc->sc_iss = arc4random();
1756 #ifdef INET6
1757 	if (autoflowlabel) {
1758 		if (V_tcp_syncookies || V_tcp_syncookiesonly)
1759 			sc->sc_flowlabel = sc->sc_iss;
1760 		else
1761 			sc->sc_flowlabel = ip6_randomflowlabel();
1762 		sc->sc_flowlabel = htonl(sc->sc_flowlabel) & IPV6_FLOWLABEL_MASK;
1763 	}
1764 #endif
1765 	if (m != NULL && M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
1766 		sc->sc_flowid = m->m_pkthdr.flowid;
1767 		sc->sc_flowtype = M_HASHTYPE_GET(m);
1768 	}
1769 #ifdef NUMA
1770 	sc->sc_numa_domain = m ? m->m_pkthdr.numa_domain : M_NODOM;
1771 #endif
1772 	if (locked)
1773 		SCH_UNLOCK(sch);
1774 
1775 	if (tfo_cookie_valid) {
1776 		rv = syncache_tfo_expand(sc, so, m, tfo_response_cookie);
1777 		/* INP_RUNLOCK(inp) will be performed by the caller */
1778 		goto tfo_expanded;
1779 	}
1780 
1781 	TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1782 	/*
1783 	 * Do a standard 3-way handshake.
1784 	 */
1785 	if (syncache_respond(sc, TH_SYN|TH_ACK) == 0) {
1786 		if (sc != &scs)
1787 			syncache_insert(sc, sch);   /* locks and unlocks sch */
1788 		TCPSTAT_INC(tcps_sndacks);
1789 		TCPSTAT_INC(tcps_sndtotal);
1790 	} else {
1791 		/*
1792 		 * Most likely we are memory constrained, so free resources.
1793 		 */
1794 		if (sc != &scs)
1795 			syncache_free(sc);
1796 		TCPSTAT_INC(tcps_sc_dropped);
1797 	}
1798 	goto donenoprobe;
1799 
1800 done:
1801 	TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1802 donenoprobe:
1803 	if (m)
1804 		m_freem(m);
1805 	/*
1806 	 * If tfo_pending is not NULL here, then a TFO SYN that did not
1807 	 * result in a new socket was processed and the associated pending
1808 	 * counter has not yet been decremented.  All such TFO processing paths
1809 	 * transit this point.
1810 	 */
1811 	if (tfo_pending != NULL)
1812 		tcp_fastopen_decrement_counter(tfo_pending);
1813 
1814 tfo_expanded:
1815 	if (cred != NULL)
1816 		crfree(cred);
1817 	if (sc == NULL || sc == &scs) {
1818 #ifdef MAC
1819 		mac_syncache_destroy(&maclabel);
1820 #endif
1821 		if (ipopts)
1822 			(void)m_free(ipopts);
1823 	}
1824 	return (rv);
1825 }
1826 
1827 /*
1828  * Send SYN|ACK or ACK to the peer.  Either in response to a peer's segment
1829  * or upon 3WHS ACK timeout.
1830  */
1831 static int
1832 syncache_respond(struct syncache *sc, int flags)
1833 {
1834 	struct ip *ip = NULL;
1835 	struct mbuf *m;
1836 	struct tcphdr *th = NULL;
1837 	struct udphdr *udp = NULL;
1838 	int optlen, error = 0;	/* Make compiler happy */
1839 	u_int16_t hlen, tlen, mssopt, ulen;
1840 	struct tcpopt to;
1841 #ifdef INET6
1842 	struct ip6_hdr *ip6 = NULL;
1843 #endif
1844 
1845 	NET_EPOCH_ASSERT();
1846 
1847 	hlen =
1848 #ifdef INET6
1849 	       (sc->sc_inc.inc_flags & INC_ISIPV6) ? sizeof(struct ip6_hdr) :
1850 #endif
1851 		sizeof(struct ip);
1852 	tlen = hlen + sizeof(struct tcphdr);
1853 	if (sc->sc_port) {
1854 		tlen += sizeof(struct udphdr);
1855 	}
1856 	/* Determine MSS we advertize to other end of connection. */
1857 	mssopt = tcp_mssopt(&sc->sc_inc);
1858 	if (sc->sc_port)
1859 		mssopt -= V_tcp_udp_tunneling_overhead;
1860 	mssopt = max(mssopt, V_tcp_minmss);
1861 
1862 	/* XXX: Assume that the entire packet will fit in a header mbuf. */
1863 	KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN,
1864 	    ("syncache: mbuf too small: hlen %u, sc_port %u, max_linkhdr %d + "
1865 	    "tlen %d + TCP_MAXOLEN %ju <= MHLEN %d", hlen, sc->sc_port,
1866 	    max_linkhdr, tlen, (uintmax_t)TCP_MAXOLEN, MHLEN));
1867 
1868 	/* Create the IP+TCP header from scratch. */
1869 	m = m_gethdr(M_NOWAIT, MT_DATA);
1870 	if (m == NULL)
1871 		return (ENOBUFS);
1872 #ifdef MAC
1873 	mac_syncache_create_mbuf(sc->sc_label, m);
1874 #endif
1875 	m->m_data += max_linkhdr;
1876 	m->m_len = tlen;
1877 	m->m_pkthdr.len = tlen;
1878 	m->m_pkthdr.rcvif = NULL;
1879 
1880 #ifdef INET6
1881 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
1882 		ip6 = mtod(m, struct ip6_hdr *);
1883 		ip6->ip6_vfc = IPV6_VERSION;
1884 		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1885 		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1886 		ip6->ip6_plen = htons(tlen - hlen);
1887 		/* ip6_hlim is set after checksum */
1888 		/* Zero out traffic class and flow label. */
1889 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
1890 		ip6->ip6_flow |= sc->sc_flowlabel;
1891 		if (sc->sc_port != 0) {
1892 			ip6->ip6_nxt = IPPROTO_UDP;
1893 			udp = (struct udphdr *)(ip6 + 1);
1894 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
1895 			udp->uh_dport = sc->sc_port;
1896 			ulen = (tlen - sizeof(struct ip6_hdr));
1897 			th = (struct tcphdr *)(udp + 1);
1898 		} else {
1899 			ip6->ip6_nxt = IPPROTO_TCP;
1900 			th = (struct tcphdr *)(ip6 + 1);
1901 		}
1902 		ip6->ip6_flow |= htonl(sc->sc_ip_tos << IPV6_FLOWLABEL_LEN);
1903 	}
1904 #endif
1905 #if defined(INET6) && defined(INET)
1906 	else
1907 #endif
1908 #ifdef INET
1909 	{
1910 		ip = mtod(m, struct ip *);
1911 		ip->ip_v = IPVERSION;
1912 		ip->ip_hl = sizeof(struct ip) >> 2;
1913 		ip->ip_len = htons(tlen);
1914 		ip->ip_id = 0;
1915 		ip->ip_off = 0;
1916 		ip->ip_sum = 0;
1917 		ip->ip_src = sc->sc_inc.inc_laddr;
1918 		ip->ip_dst = sc->sc_inc.inc_faddr;
1919 		ip->ip_ttl = sc->sc_ip_ttl;
1920 		ip->ip_tos = sc->sc_ip_tos;
1921 
1922 		/*
1923 		 * See if we should do MTU discovery.  Route lookups are
1924 		 * expensive, so we will only unset the DF bit if:
1925 		 *
1926 		 *	1) path_mtu_discovery is disabled
1927 		 *	2) the SCF_UNREACH flag has been set
1928 		 */
1929 		if (V_path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1930 		       ip->ip_off |= htons(IP_DF);
1931 		if (sc->sc_port == 0) {
1932 			ip->ip_p = IPPROTO_TCP;
1933 			th = (struct tcphdr *)(ip + 1);
1934 		} else {
1935 			ip->ip_p = IPPROTO_UDP;
1936 			udp = (struct udphdr *)(ip + 1);
1937 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
1938 			udp->uh_dport = sc->sc_port;
1939 			ulen = (tlen - sizeof(struct ip));
1940 			th = (struct tcphdr *)(udp + 1);
1941 		}
1942 	}
1943 #endif /* INET */
1944 	th->th_sport = sc->sc_inc.inc_lport;
1945 	th->th_dport = sc->sc_inc.inc_fport;
1946 
1947 	if (flags & TH_SYN)
1948 		th->th_seq = htonl(sc->sc_iss);
1949 	else
1950 		th->th_seq = htonl(sc->sc_iss + 1);
1951 	th->th_ack = htonl(sc->sc_irs + 1);
1952 	th->th_off = sizeof(struct tcphdr) >> 2;
1953 	th->th_win = htons(sc->sc_wnd);
1954 	th->th_urp = 0;
1955 
1956 	flags = tcp_ecn_syncache_respond(flags, sc);
1957 	tcp_set_flags(th, flags);
1958 
1959 	/* Tack on the TCP options. */
1960 	if ((sc->sc_flags & SCF_NOOPT) == 0) {
1961 		to.to_flags = 0;
1962 
1963 		if (flags & TH_SYN) {
1964 			to.to_mss = mssopt;
1965 			to.to_flags = TOF_MSS;
1966 			if (sc->sc_flags & SCF_WINSCALE) {
1967 				to.to_wscale = sc->sc_requested_r_scale;
1968 				to.to_flags |= TOF_SCALE;
1969 			}
1970 			if (sc->sc_flags & SCF_SACK)
1971 				to.to_flags |= TOF_SACKPERM;
1972 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1973 			if (sc->sc_flags & SCF_SIGNATURE)
1974 				to.to_flags |= TOF_SIGNATURE;
1975 #endif
1976 			if (sc->sc_tfo_cookie) {
1977 				to.to_flags |= TOF_FASTOPEN;
1978 				to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
1979 				to.to_tfo_cookie = sc->sc_tfo_cookie;
1980 				/* don't send cookie again when retransmitting response */
1981 				sc->sc_tfo_cookie = NULL;
1982 			}
1983 		}
1984 		if (sc->sc_flags & SCF_TIMESTAMP) {
1985 			to.to_tsval = sc->sc_tsoff + tcp_ts_getticks();
1986 			to.to_tsecr = sc->sc_tsreflect;
1987 			to.to_flags |= TOF_TS;
1988 		}
1989 		optlen = tcp_addoptions(&to, (u_char *)(th + 1));
1990 
1991 		/* Adjust headers by option size. */
1992 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1993 		m->m_len += optlen;
1994 		m->m_pkthdr.len += optlen;
1995 #ifdef INET6
1996 		if (sc->sc_inc.inc_flags & INC_ISIPV6)
1997 			ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen);
1998 		else
1999 #endif
2000 			ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
2001 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2002 		if (sc->sc_flags & SCF_SIGNATURE) {
2003 			KASSERT(to.to_flags & TOF_SIGNATURE,
2004 			    ("tcp_addoptions() didn't set tcp_signature"));
2005 
2006 			/* NOTE: to.to_signature is inside of mbuf */
2007 			if (!TCPMD5_ENABLED() ||
2008 			    TCPMD5_OUTPUT(m, th, to.to_signature) != 0) {
2009 				m_freem(m);
2010 				return (EACCES);
2011 			}
2012 		}
2013 #endif
2014 	} else
2015 		optlen = 0;
2016 
2017 	if (udp) {
2018 		ulen += optlen;
2019 		udp->uh_ulen = htons(ulen);
2020 	}
2021 	M_SETFIB(m, sc->sc_inc.inc_fibnum);
2022 	m->m_pkthdr.flowid = sc->sc_flowid;
2023 	M_HASHTYPE_SET(m, sc->sc_flowtype);
2024 #ifdef NUMA
2025 	m->m_pkthdr.numa_domain = sc->sc_numa_domain;
2026 #endif
2027 #ifdef INET6
2028 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
2029 		if (sc->sc_port) {
2030 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
2031 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2032 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen,
2033 			      IPPROTO_UDP, 0);
2034 			th->th_sum = htons(0);
2035 		} else {
2036 			m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2037 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2038 			th->th_sum = in6_cksum_pseudo(ip6, tlen + optlen - hlen,
2039 			    IPPROTO_TCP, 0);
2040 		}
2041 		ip6->ip6_hlim = sc->sc_ip_ttl;
2042 #ifdef TCP_OFFLOAD
2043 		if (ADDED_BY_TOE(sc)) {
2044 			struct toedev *tod = sc->sc_tod;
2045 
2046 			error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
2047 
2048 			return (error);
2049 		}
2050 #endif
2051 		TCP_PROBE5(send, NULL, NULL, ip6, NULL, th);
2052 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2053 	}
2054 #endif
2055 #if defined(INET6) && defined(INET)
2056 	else
2057 #endif
2058 #ifdef INET
2059 	{
2060 		if (sc->sc_port) {
2061 			m->m_pkthdr.csum_flags = CSUM_UDP;
2062 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2063 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
2064 			      ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
2065 			th->th_sum = htons(0);
2066 		} else {
2067 			m->m_pkthdr.csum_flags = CSUM_TCP;
2068 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2069 			th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2070 			    htons(tlen + optlen - hlen + IPPROTO_TCP));
2071 		}
2072 #ifdef TCP_OFFLOAD
2073 		if (ADDED_BY_TOE(sc)) {
2074 			struct toedev *tod = sc->sc_tod;
2075 
2076 			error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
2077 
2078 			return (error);
2079 		}
2080 #endif
2081 		TCP_PROBE5(send, NULL, NULL, ip, NULL, th);
2082 		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
2083 	}
2084 #endif
2085 	return (error);
2086 }
2087 
2088 static void
2089 syncache_send_challenge_ack(struct syncache *sc)
2090 {
2091 	if (tcp_challenge_ack_check(&sc->sc_challenge_ack_end,
2092 	    &sc->sc_challenge_ack_cnt)) {
2093 		if (syncache_respond(sc, TH_ACK) == 0) {
2094 			TCPSTAT_INC(tcps_sndacks);
2095 			TCPSTAT_INC(tcps_sndtotal);
2096 		}
2097 	}
2098 }
2099 
2100 /*
2101  * The purpose of syncookies is to handle spoofed SYN flooding DoS attacks
2102  * that exceed the capacity of the syncache by avoiding the storage of any
2103  * of the SYNs we receive.  Syncookies defend against blind SYN flooding
2104  * attacks where the attacker does not have access to our responses.
2105  *
2106  * Syncookies encode and include all necessary information about the
2107  * connection setup within the SYN|ACK that we send back.  That way we
2108  * can avoid keeping any local state until the ACK to our SYN|ACK returns
2109  * (if ever).  Normally the syncache and syncookies are running in parallel
2110  * with the latter taking over when the former is exhausted.  When matching
2111  * syncache entry is found the syncookie is ignored.
2112  *
2113  * The only reliable information persisting the 3WHS is our initial sequence
2114  * number ISS of 32 bits.  Syncookies embed a cryptographically sufficient
2115  * strong hash (MAC) value and a few bits of TCP SYN options in the ISS
2116  * of our SYN|ACK.  The MAC can be recomputed when the ACK to our SYN|ACK
2117  * returns and signifies a legitimate connection if it matches the ACK.
2118  *
2119  * The available space of 32 bits to store the hash and to encode the SYN
2120  * option information is very tight and we should have at least 24 bits for
2121  * the MAC to keep the number of guesses by blind spoofing reasonably high.
2122  *
2123  * SYN option information we have to encode to fully restore a connection:
2124  * MSS: is imporant to chose an optimal segment size to avoid IP level
2125  *   fragmentation along the path.  The common MSS values can be encoded
2126  *   in a 3-bit table.  Uncommon values are captured by the next lower value
2127  *   in the table leading to a slight increase in packetization overhead.
2128  * WSCALE: is necessary to allow large windows to be used for high delay-
2129  *   bandwidth product links.  Not scaling the window when it was initially
2130  *   negotiated is bad for performance as lack of scaling further decreases
2131  *   the apparent available send window.  We only need to encode the WSCALE
2132  *   we received from the remote end.  Our end can be recalculated at any
2133  *   time.  The common WSCALE values can be encoded in a 3-bit table.
2134  *   Uncommon values are captured by the next lower value in the table
2135  *   making us under-estimate the available window size halving our
2136  *   theoretically possible maximum throughput for that connection.
2137  * SACK: Greatly assists in packet loss recovery and requires 1 bit.
2138  * TIMESTAMP and SIGNATURE is not encoded because they are permanent options
2139  *   that are included in all segments on a connection.  We enable them when
2140  *   the ACK has them.
2141  *
2142  * Security of syncookies and attack vectors:
2143  *
2144  * The MAC is computed over (faddr||laddr||fport||lport||irs||flags||secmod)
2145  * together with the gloabl secret to make it unique per connection attempt.
2146  * Thus any change of any of those parameters results in a different MAC output
2147  * in an unpredictable way unless a collision is encountered.  24 bits of the
2148  * MAC are embedded into the ISS.
2149  *
2150  * To prevent replay attacks two rotating global secrets are updated with a
2151  * new random value every 15 seconds.  The life-time of a syncookie is thus
2152  * 15-30 seconds.
2153  *
2154  * Vector 1: Attacking the secret.  This requires finding a weakness in the
2155  * MAC itself or the way it is used here.  The attacker can do a chosen plain
2156  * text attack by varying and testing the all parameters under his control.
2157  * The strength depends on the size and randomness of the secret, and the
2158  * cryptographic security of the MAC function.  Due to the constant updating
2159  * of the secret the attacker has at most 29.999 seconds to find the secret
2160  * and launch spoofed connections.  After that he has to start all over again.
2161  *
2162  * Vector 2: Collision attack on the MAC of a single ACK.  With a 24 bit MAC
2163  * size an average of 4,823 attempts are required for a 50% chance of success
2164  * to spoof a single syncookie (birthday collision paradox).  However the
2165  * attacker is blind and doesn't know if one of his attempts succeeded unless
2166  * he has a side channel to interfere success from.  A single connection setup
2167  * success average of 90% requires 8,790 packets, 99.99% requires 17,578 packets.
2168  * This many attempts are required for each one blind spoofed connection.  For
2169  * every additional spoofed connection he has to launch another N attempts.
2170  * Thus for a sustained rate 100 spoofed connections per second approximately
2171  * 1,800,000 packets per second would have to be sent.
2172  *
2173  * NB: The MAC function should be fast so that it doesn't become a CPU
2174  * exhaustion attack vector itself.
2175  *
2176  * References:
2177  *  RFC4987 TCP SYN Flooding Attacks and Common Mitigations
2178  *  SYN cookies were first proposed by cryptographer Dan J. Bernstein in 1996
2179  *   http://cr.yp.to/syncookies.html    (overview)
2180  *   http://cr.yp.to/syncookies/archive (details)
2181  *
2182  *
2183  * Schematic construction of a syncookie enabled Initial Sequence Number:
2184  *  0        1         2         3
2185  *  12345678901234567890123456789012
2186  * |xxxxxxxxxxxxxxxxxxxxxxxxWWWMMMSP|
2187  *
2188  *  x 24 MAC (truncated)
2189  *  W  3 Send Window Scale index
2190  *  M  3 MSS index
2191  *  S  1 SACK permitted
2192  *  P  1 Odd/even secret
2193  */
2194 
2195 /*
2196  * Distribution and probability of certain MSS values.  Those in between are
2197  * rounded down to the next lower one.
2198  * [An Analysis of TCP Maximum Segment Sizes, S. Alcock and R. Nelson, 2011]
2199  *                            .2%  .3%   5%    7%    7%    20%   15%   45%
2200  */
2201 static int tcp_sc_msstab[] = { 216, 536, 1200, 1360, 1400, 1440, 1452, 1460 };
2202 
2203 /*
2204  * Distribution and probability of certain WSCALE values.  We have to map the
2205  * (send) window scale (shift) option with a range of 0-14 from 4 bits into 3
2206  * bits based on prevalence of certain values.  Where we don't have an exact
2207  * match for are rounded down to the next lower one letting us under-estimate
2208  * the true available window.  At the moment this would happen only for the
2209  * very uncommon values 3, 5 and those above 8 (more than 16MB socket buffer
2210  * and window size).  The absence of the WSCALE option (no scaling in either
2211  * direction) is encoded with index zero.
2212  * [WSCALE values histograms, Allman, 2012]
2213  *                            X 10 10 35  5  6 14 10%   by host
2214  *                            X 11  4  5  5 18 49  3%   by connections
2215  */
2216 static int tcp_sc_wstab[] = { 0, 0, 1, 2, 4, 6, 7, 8 };
2217 
2218 /*
2219  * Compute the MAC for the SYN cookie.  SIPHASH-2-4 is chosen for its speed
2220  * and good cryptographic properties.
2221  */
2222 static uint32_t
2223 syncookie_mac(struct in_conninfo *inc, tcp_seq irs, uint8_t flags,
2224     uint8_t *secbits, uintptr_t secmod)
2225 {
2226 	SIPHASH_CTX ctx;
2227 	uint32_t siphash[2];
2228 
2229 	SipHash24_Init(&ctx);
2230 	SipHash_SetKey(&ctx, secbits);
2231 	switch (inc->inc_flags & INC_ISIPV6) {
2232 #ifdef INET
2233 	case 0:
2234 		SipHash_Update(&ctx, &inc->inc_faddr, sizeof(inc->inc_faddr));
2235 		SipHash_Update(&ctx, &inc->inc_laddr, sizeof(inc->inc_laddr));
2236 		break;
2237 #endif
2238 #ifdef INET6
2239 	case INC_ISIPV6:
2240 		SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(inc->inc6_faddr));
2241 		SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(inc->inc6_laddr));
2242 		break;
2243 #endif
2244 	}
2245 	SipHash_Update(&ctx, &inc->inc_fport, sizeof(inc->inc_fport));
2246 	SipHash_Update(&ctx, &inc->inc_lport, sizeof(inc->inc_lport));
2247 	SipHash_Update(&ctx, &irs, sizeof(irs));
2248 	SipHash_Update(&ctx, &flags, sizeof(flags));
2249 	SipHash_Update(&ctx, &secmod, sizeof(secmod));
2250 	SipHash_Final((u_int8_t *)&siphash, &ctx);
2251 
2252 	return (siphash[0] ^ siphash[1]);
2253 }
2254 
2255 static tcp_seq
2256 syncookie_generate(struct syncache_head *sch, struct syncache *sc)
2257 {
2258 	u_int i, secbit, wscale;
2259 	uint32_t iss, hash;
2260 	uint8_t *secbits;
2261 	union syncookie cookie;
2262 
2263 	cookie.cookie = 0;
2264 
2265 	/* Map our computed MSS into the 3-bit index. */
2266 	for (i = nitems(tcp_sc_msstab) - 1;
2267 	     tcp_sc_msstab[i] > sc->sc_peer_mss && i > 0;
2268 	     i--)
2269 		;
2270 	cookie.flags.mss_idx = i;
2271 
2272 	/*
2273 	 * Map the send window scale into the 3-bit index but only if
2274 	 * the wscale option was received.
2275 	 */
2276 	if (sc->sc_flags & SCF_WINSCALE) {
2277 		wscale = sc->sc_requested_s_scale;
2278 		for (i = nitems(tcp_sc_wstab) - 1;
2279 		    tcp_sc_wstab[i] > wscale && i > 0;
2280 		     i--)
2281 			;
2282 		cookie.flags.wscale_idx = i;
2283 	}
2284 
2285 	/* Can we do SACK? */
2286 	if (sc->sc_flags & SCF_SACK)
2287 		cookie.flags.sack_ok = 1;
2288 
2289 	/* Which of the two secrets to use. */
2290 	secbit = V_tcp_syncache.secret.oddeven & 0x1;
2291 	cookie.flags.odd_even = secbit;
2292 
2293 	secbits = V_tcp_syncache.secret.key[secbit];
2294 	hash = syncookie_mac(&sc->sc_inc, sc->sc_irs, cookie.cookie, secbits,
2295 	    (uintptr_t)sch);
2296 
2297 	/*
2298 	 * Put the flags into the hash and XOR them to get better ISS number
2299 	 * variance.  This doesn't enhance the cryptographic strength and is
2300 	 * done to prevent the 8 cookie bits from showing up directly on the
2301 	 * wire.
2302 	 */
2303 	iss = hash & ~0xff;
2304 	iss |= cookie.cookie ^ (hash >> 24);
2305 
2306 	TCPSTAT_INC(tcps_sc_sendcookie);
2307 	return (iss);
2308 }
2309 
2310 static bool
2311 syncookie_expand(struct in_conninfo *inc, const struct syncache_head *sch,
2312     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2313     struct socket *lso, uint16_t port)
2314 {
2315 	uint32_t hash;
2316 	uint8_t *secbits;
2317 	tcp_seq ack, seq;
2318 	int wnd;
2319 	union syncookie cookie;
2320 
2321 	/*
2322 	 * Pull information out of SYN-ACK/ACK and revert sequence number
2323 	 * advances.
2324 	 */
2325 	ack = th->th_ack - 1;
2326 	seq = th->th_seq - 1;
2327 
2328 	/*
2329 	 * Unpack the flags containing enough information to restore the
2330 	 * connection.
2331 	 */
2332 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
2333 
2334 	/* Which of the two secrets to use. */
2335 	secbits = V_tcp_syncache.secret.key[cookie.flags.odd_even];
2336 
2337 	hash = syncookie_mac(inc, seq, cookie.cookie, secbits, (uintptr_t)sch);
2338 
2339 	/* The recomputed hash matches the ACK if this was a genuine cookie. */
2340 	if ((ack & ~0xff) != (hash & ~0xff))
2341 		return (false);
2342 
2343 	/* Fill in the syncache values. */
2344 	sc->sc_flags = 0;
2345 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
2346 	sc->sc_ipopts = NULL;
2347 
2348 	sc->sc_irs = seq;
2349 	sc->sc_iss = ack;
2350 
2351 	switch (inc->inc_flags & INC_ISIPV6) {
2352 #ifdef INET
2353 	case 0:
2354 		sc->sc_ip_ttl = sotoinpcb(lso)->inp_ip_ttl;
2355 		sc->sc_ip_tos = sotoinpcb(lso)->inp_ip_tos;
2356 		break;
2357 #endif
2358 #ifdef INET6
2359 	case INC_ISIPV6:
2360 		if (sotoinpcb(lso)->inp_flags & IN6P_AUTOFLOWLABEL)
2361 			sc->sc_flowlabel =
2362 			    htonl(sc->sc_iss) & IPV6_FLOWLABEL_MASK;
2363 		break;
2364 #endif
2365 	}
2366 
2367 	sc->sc_peer_mss = tcp_sc_msstab[cookie.flags.mss_idx];
2368 
2369 	/* Only use wscale if it was enabled in the orignal SYN. */
2370 	if (cookie.flags.wscale_idx > 0) {
2371 		u_int wscale = 0;
2372 
2373 		/* Recompute the receive window scale that was sent earlier. */
2374 		while (wscale < TCP_MAX_WINSHIFT &&
2375 		    (TCP_MAXWIN << wscale) < sb_max)
2376 			wscale++;
2377 		sc->sc_requested_r_scale = wscale;
2378 		sc->sc_requested_s_scale = tcp_sc_wstab[cookie.flags.wscale_idx];
2379 		sc->sc_flags |= SCF_WINSCALE;
2380 	}
2381 
2382 	wnd = lso->sol_sbrcv_hiwat;
2383 	wnd = imax(wnd, 0);
2384 	wnd = imin(wnd, TCP_MAXWIN);
2385 	sc->sc_wnd = wnd;
2386 
2387 	if (cookie.flags.sack_ok)
2388 		sc->sc_flags |= SCF_SACK;
2389 
2390 	if (to->to_flags & TOF_TS) {
2391 		sc->sc_flags |= SCF_TIMESTAMP;
2392 		sc->sc_tsreflect = to->to_tsval;
2393 		sc->sc_tsoff = tcp_new_ts_offset(inc);
2394 	}
2395 
2396 	if (to->to_flags & TOF_SIGNATURE)
2397 		sc->sc_flags |= SCF_SIGNATURE;
2398 
2399 	sc->sc_rxmits = 0;
2400 
2401 	sc->sc_port = port;
2402 
2403 	return (true);
2404 }
2405 
2406 #ifdef INVARIANTS
2407 static void
2408 syncookie_cmp(struct in_conninfo *inc, const struct syncache_head *sch,
2409     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2410     struct socket *lso, uint16_t port)
2411 {
2412 	struct syncache scs;
2413 	char *s;
2414 
2415 	bzero(&scs, sizeof(scs));
2416 	if (syncookie_expand(inc, sch, &scs, th, to, lso, port) &&
2417 	    (sc->sc_peer_mss != scs.sc_peer_mss ||
2418 	     sc->sc_requested_r_scale != scs.sc_requested_r_scale ||
2419 	     sc->sc_requested_s_scale != scs.sc_requested_s_scale ||
2420 	     (sc->sc_flags & SCF_SACK) != (scs.sc_flags & SCF_SACK))) {
2421 
2422 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)) == NULL)
2423 			return;
2424 
2425 		if (sc->sc_peer_mss != scs.sc_peer_mss)
2426 			log(LOG_DEBUG, "%s; %s: mss different %i vs %i\n",
2427 			    s, __func__, sc->sc_peer_mss, scs.sc_peer_mss);
2428 
2429 		if (sc->sc_requested_r_scale != scs.sc_requested_r_scale)
2430 			log(LOG_DEBUG, "%s; %s: rwscale different %i vs %i\n",
2431 			    s, __func__, sc->sc_requested_r_scale,
2432 			    scs.sc_requested_r_scale);
2433 
2434 		if (sc->sc_requested_s_scale != scs.sc_requested_s_scale)
2435 			log(LOG_DEBUG, "%s; %s: swscale different %i vs %i\n",
2436 			    s, __func__, sc->sc_requested_s_scale,
2437 			    scs.sc_requested_s_scale);
2438 
2439 		if ((sc->sc_flags & SCF_SACK) != (scs.sc_flags & SCF_SACK))
2440 			log(LOG_DEBUG, "%s; %s: SACK different\n", s, __func__);
2441 
2442 		free(s, M_TCPLOG);
2443 	}
2444 }
2445 #endif /* INVARIANTS */
2446 
2447 static void
2448 syncookie_reseed(void *arg)
2449 {
2450 	struct tcp_syncache *sc = arg;
2451 	uint8_t *secbits;
2452 	int secbit;
2453 
2454 	/*
2455 	 * Reseeding the secret doesn't have to be protected by a lock.
2456 	 * It only must be ensured that the new random values are visible
2457 	 * to all CPUs in a SMP environment.  The atomic with release
2458 	 * semantics ensures that.
2459 	 */
2460 	secbit = (sc->secret.oddeven & 0x1) ? 0 : 1;
2461 	secbits = sc->secret.key[secbit];
2462 	arc4rand(secbits, SYNCOOKIE_SECRET_SIZE, 0);
2463 	atomic_add_rel_int(&sc->secret.oddeven, 1);
2464 
2465 	/* Reschedule ourself. */
2466 	callout_schedule(&sc->secret.reseed, SYNCOOKIE_LIFETIME * hz);
2467 }
2468 
2469 /*
2470  * We have overflowed a bucket. Let's pause dealing with the syncache.
2471  * This function will increment the bucketoverflow statistics appropriately
2472  * (once per pause when pausing is enabled; otherwise, once per overflow).
2473  */
2474 static void
2475 syncache_pause(struct in_conninfo *inc)
2476 {
2477 	time_t delta;
2478 	const char *s;
2479 
2480 	/* XXX:
2481 	 * 2. Add sysctl read here so we don't get the benefit of this
2482 	 * change without the new sysctl.
2483 	 */
2484 
2485 	/*
2486 	 * Try an unlocked read. If we already know that another thread
2487 	 * has activated the feature, there is no need to proceed.
2488 	 */
2489 	if (V_tcp_syncache.paused)
2490 		return;
2491 
2492 	/* Are cookied enabled? If not, we can't pause. */
2493 	if (!V_tcp_syncookies) {
2494 		TCPSTAT_INC(tcps_sc_bucketoverflow);
2495 		return;
2496 	}
2497 
2498 	/*
2499 	 * We may be the first thread to find an overflow. Get the lock
2500 	 * and evaluate if we need to take action.
2501 	 */
2502 	mtx_lock(&V_tcp_syncache.pause_mtx);
2503 	if (V_tcp_syncache.paused) {
2504 		mtx_unlock(&V_tcp_syncache.pause_mtx);
2505 		return;
2506 	}
2507 
2508 	/* Activate protection. */
2509 	V_tcp_syncache.paused = true;
2510 	TCPSTAT_INC(tcps_sc_bucketoverflow);
2511 
2512 	/*
2513 	 * Determine the last backoff time. If we are seeing a re-newed
2514 	 * attack within that same time after last reactivating the syncache,
2515 	 * consider it an extension of the same attack.
2516 	 */
2517 	delta = TCP_SYNCACHE_PAUSE_TIME << V_tcp_syncache.pause_backoff;
2518 	if (V_tcp_syncache.pause_until + delta - time_uptime > 0) {
2519 		if (V_tcp_syncache.pause_backoff < TCP_SYNCACHE_MAX_BACKOFF) {
2520 			delta <<= 1;
2521 			V_tcp_syncache.pause_backoff++;
2522 		}
2523 	} else {
2524 		delta = TCP_SYNCACHE_PAUSE_TIME;
2525 		V_tcp_syncache.pause_backoff = 0;
2526 	}
2527 
2528 	/* Log a warning, including IP addresses, if able. */
2529 	if (inc != NULL)
2530 		s = tcp_log_addrs(inc, NULL, NULL, NULL);
2531 	else
2532 		s = (const char *)NULL;
2533 	log(LOG_WARNING, "TCP syncache overflow detected; using syncookies for "
2534 	    "the next %lld seconds%s%s%s\n", (long long)delta,
2535 	    (s != NULL) ? " (last SYN: " : "", (s != NULL) ? s : "",
2536 	    (s != NULL) ? ")" : "");
2537 	free(__DECONST(void *, s), M_TCPLOG);
2538 
2539 	/* Use the calculated delta to set a new pause time. */
2540 	V_tcp_syncache.pause_until = time_uptime + delta;
2541 	callout_reset(&V_tcp_syncache.pause_co, delta * hz, syncache_unpause,
2542 	    &V_tcp_syncache);
2543 	mtx_unlock(&V_tcp_syncache.pause_mtx);
2544 }
2545 
2546 /* Evaluate whether we need to unpause. */
2547 static void
2548 syncache_unpause(void *arg)
2549 {
2550 	struct tcp_syncache *sc;
2551 	time_t delta;
2552 
2553 	sc = arg;
2554 	mtx_assert(&sc->pause_mtx, MA_OWNED | MA_NOTRECURSED);
2555 	callout_deactivate(&sc->pause_co);
2556 
2557 	/*
2558 	 * Check to make sure we are not running early. If the pause
2559 	 * time has expired, then deactivate the protection.
2560 	 */
2561 	if ((delta = sc->pause_until - time_uptime) > 0)
2562 		callout_schedule(&sc->pause_co, delta * hz);
2563 	else
2564 		sc->paused = false;
2565 }
2566 
2567 /*
2568  * Exports the syncache entries to userland so that netstat can display
2569  * them alongside the other sockets.  This function is intended to be
2570  * called only from tcp_pcblist.
2571  *
2572  * Due to concurrency on an active system, the number of pcbs exported
2573  * may have no relation to max_pcbs.  max_pcbs merely indicates the
2574  * amount of space the caller allocated for this function to use.
2575  */
2576 int
2577 syncache_pcblist(struct sysctl_req *req)
2578 {
2579 	struct xtcpcb xt;
2580 	struct syncache *sc;
2581 	struct syncache_head *sch;
2582 	int error, i;
2583 
2584 	bzero(&xt, sizeof(xt));
2585 	xt.xt_len = sizeof(xt);
2586 	xt.t_state = TCPS_SYN_RECEIVED;
2587 	xt.xt_inp.xi_socket.xso_protocol = IPPROTO_TCP;
2588 	xt.xt_inp.xi_socket.xso_len = sizeof (struct xsocket);
2589 	xt.xt_inp.xi_socket.so_type = SOCK_STREAM;
2590 	xt.xt_inp.xi_socket.so_state = SS_ISCONNECTING;
2591 
2592 	for (i = 0; i < V_tcp_syncache.hashsize; i++) {
2593 		sch = &V_tcp_syncache.hashbase[i];
2594 		SCH_LOCK(sch);
2595 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
2596 			if (sc->sc_cred != NULL &&
2597 			    cr_cansee(req->td->td_ucred, sc->sc_cred) != 0)
2598 				continue;
2599 			if (sc->sc_inc.inc_flags & INC_ISIPV6)
2600 				xt.xt_inp.inp_vflag = INP_IPV6;
2601 			else
2602 				xt.xt_inp.inp_vflag = INP_IPV4;
2603 			xt.xt_encaps_port = sc->sc_port;
2604 			bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc,
2605 			    sizeof (struct in_conninfo));
2606 			error = SYSCTL_OUT(req, &xt, sizeof xt);
2607 			if (error) {
2608 				SCH_UNLOCK(sch);
2609 				return (0);
2610 			}
2611 		}
2612 		SCH_UNLOCK(sch);
2613 	}
2614 
2615 	return (0);
2616 }
2617