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