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