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