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