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