xref: /freebsd/sys/netinet/tcp_syncache.c (revision 0faa9ca827a5e91273ba757bd87bd9e8179a0862)
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 int
syncache_expand(struct in_conninfo * inc,struct tcpopt * to,struct tcphdr * th,struct socket ** lsop,struct mbuf * m,uint16_t port)1051 syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1052     struct socket **lsop, struct mbuf *m, uint16_t port)
1053 {
1054 	struct syncache *sc;
1055 	struct syncache_head *sch;
1056 	struct syncache scs;
1057 	char *s;
1058 	bool locked;
1059 
1060 	NET_EPOCH_ASSERT();
1061 	KASSERT((tcp_get_flags(th) & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK,
1062 	    ("%s: can handle only ACK", __func__));
1063 
1064 	if (syncache_cookiesonly()) {
1065 		sc = NULL;
1066 		sch = syncache_hashbucket(inc);
1067 		locked = false;
1068 	} else {
1069 		sc = syncache_lookup(inc, &sch);	/* returns locked sch */
1070 		locked = true;
1071 		SCH_LOCK_ASSERT(sch);
1072 	}
1073 
1074 #ifdef INVARIANTS
1075 	/*
1076 	 * Test code for syncookies comparing the syncache stored
1077 	 * values with the reconstructed values from the cookie.
1078 	 */
1079 	if (sc != NULL)
1080 		syncookie_cmp(inc, sch, sc, th, to, *lsop, port);
1081 #endif
1082 
1083 	if (sc == NULL) {
1084 		if (locked) {
1085 			/*
1086 			 * The syncache is currently in use (neither disabled,
1087 			 * nor paused), but no entry was found.
1088 			 */
1089 			if (!V_tcp_syncookies) {
1090 				/*
1091 				 * Since no syncookies are used in case of
1092 				 * a bucket overflow, don't even check for
1093 				 * a valid syncookie.
1094 				 */
1095 				SCH_UNLOCK(sch);
1096 				TCPSTAT_INC(tcps_sc_spurcookie);
1097 				if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1098 					log(LOG_DEBUG, "%s; %s: Spurious ACK, "
1099 					    "segment rejected "
1100 					    "(syncookies disabled)\n",
1101 					    s, __func__);
1102 				goto failed;
1103 			}
1104 			if (sch->sch_last_overflow <
1105 			    time_uptime - SYNCOOKIE_LIFETIME) {
1106 				/*
1107 				 * Since the bucket did not overflow recently,
1108 				 * don't even check for a valid syncookie.
1109 				 */
1110 				SCH_UNLOCK(sch);
1111 				TCPSTAT_INC(tcps_sc_spurcookie);
1112 				if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1113 					log(LOG_DEBUG, "%s; %s: Spurious ACK, "
1114 					    "segment rejected "
1115 					    "(no syncache entry)\n",
1116 					    s, __func__);
1117 				goto failed;
1118 			}
1119 			SCH_UNLOCK(sch);
1120 		}
1121 		bzero(&scs, sizeof(scs));
1122 		/*
1123 		 * Now check, if the syncookie is valid. If it is, create an on
1124 		 * stack syncache entry.
1125 		 */
1126 		if (syncookie_expand(inc, sch, &scs, th, to, *lsop, port)) {
1127 			sc = &scs;
1128 			TCPSTAT_INC(tcps_sc_recvcookie);
1129 		} else {
1130 			TCPSTAT_INC(tcps_sc_failcookie);
1131 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1132 				log(LOG_DEBUG, "%s; %s: Segment failed "
1133 				    "SYNCOOKIE authentication, segment rejected "
1134 				    "(probably spoofed)\n", s, __func__);
1135 			goto failed;
1136 		}
1137 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1138 		/* If received ACK has MD5 signature, check it. */
1139 		if ((to->to_flags & TOF_SIGNATURE) != 0 &&
1140 		    (!TCPMD5_ENABLED() ||
1141 		    TCPMD5_INPUT(m, th, to->to_signature) != 0)) {
1142 			/* Drop the ACK. */
1143 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1144 				log(LOG_DEBUG, "%s; %s: Segment rejected, "
1145 				    "MD5 signature doesn't match.\n",
1146 				    s, __func__);
1147 				free(s, M_TCPLOG);
1148 			}
1149 			TCPSTAT_INC(tcps_sig_err_sigopt);
1150 			return (-1); /* Do not send RST */
1151 		}
1152 #endif /* TCP_SIGNATURE */
1153 		TCPSTATES_INC(TCPS_SYN_RECEIVED);
1154 	} else {
1155 		if (sc->sc_port != port) {
1156 			SCH_UNLOCK(sch);
1157 			return (0);
1158 		}
1159 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1160 		/*
1161 		 * If listening socket requested TCP digests, check that
1162 		 * received ACK has signature and it is correct.
1163 		 * If not, drop the ACK and leave sc entry in th cache,
1164 		 * because SYN was received with correct signature.
1165 		 */
1166 		if (sc->sc_flags & SCF_SIGNATURE) {
1167 			if ((to->to_flags & TOF_SIGNATURE) == 0) {
1168 				/* No signature */
1169 				TCPSTAT_INC(tcps_sig_err_nosigopt);
1170 				SCH_UNLOCK(sch);
1171 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1172 					log(LOG_DEBUG, "%s; %s: Segment "
1173 					    "rejected, MD5 signature wasn't "
1174 					    "provided.\n", s, __func__);
1175 					free(s, M_TCPLOG);
1176 				}
1177 				return (-1); /* Do not send RST */
1178 			}
1179 			if (!TCPMD5_ENABLED() ||
1180 			    TCPMD5_INPUT(m, th, to->to_signature) != 0) {
1181 				/* Doesn't match or no SA */
1182 				SCH_UNLOCK(sch);
1183 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1184 					log(LOG_DEBUG, "%s; %s: Segment "
1185 					    "rejected, MD5 signature doesn't "
1186 					    "match.\n", s, __func__);
1187 					free(s, M_TCPLOG);
1188 				}
1189 				return (-1); /* Do not send RST */
1190 			}
1191 		}
1192 #endif /* TCP_SIGNATURE */
1193 
1194 		/*
1195 		 * RFC 7323 PAWS: If we have a timestamp on this segment and
1196 		 * it's less than ts_recent, drop it.
1197 		 * XXXMT: RFC 7323 also requires to send an ACK.
1198 		 *        In tcp_input.c this is only done for TCP segments
1199 		 *        with user data, so be consistent here and just drop
1200 		 *        the segment.
1201 		 */
1202 		if (sc->sc_flags & SCF_TIMESTAMP && to->to_flags & TOF_TS &&
1203 		    TSTMP_LT(to->to_tsval, sc->sc_tsreflect)) {
1204 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1205 				log(LOG_DEBUG,
1206 				    "%s; %s: SEG.TSval %u < TS.Recent %u, "
1207 				    "segment dropped\n", s, __func__,
1208 				    to->to_tsval, sc->sc_tsreflect);
1209 				free(s, M_TCPLOG);
1210 			}
1211 			SCH_UNLOCK(sch);
1212 			return (-1);  /* Do not send RST */
1213 		}
1214 
1215 		/*
1216 		 * If timestamps were not negotiated during SYN/ACK and a
1217 		 * segment with a timestamp is received, ignore the
1218 		 * timestamp and process the packet normally.
1219 		 * See section 3.2 of RFC 7323.
1220 		 */
1221 		if (!(sc->sc_flags & SCF_TIMESTAMP) &&
1222 		    (to->to_flags & TOF_TS)) {
1223 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1224 				log(LOG_DEBUG, "%s; %s: Timestamp not "
1225 				    "expected, segment processed normally\n",
1226 				    s, __func__);
1227 				free(s, M_TCPLOG);
1228 				s = NULL;
1229 			}
1230 		}
1231 
1232 		/*
1233 		 * If timestamps were negotiated during SYN/ACK and a
1234 		 * segment without a timestamp is received, silently drop
1235 		 * the segment, unless the missing timestamps are tolerated.
1236 		 * See section 3.2 of RFC 7323.
1237 		 */
1238 		if ((sc->sc_flags & SCF_TIMESTAMP) &&
1239 		    !(to->to_flags & TOF_TS)) {
1240 			if (V_tcp_tolerate_missing_ts) {
1241 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1242 					log(LOG_DEBUG,
1243 					    "%s; %s: Timestamp missing, "
1244 					    "segment processed normally\n",
1245 					    s, __func__);
1246 					free(s, M_TCPLOG);
1247 				}
1248 			} else {
1249 				SCH_UNLOCK(sch);
1250 				if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1251 					log(LOG_DEBUG,
1252 					    "%s; %s: Timestamp missing, "
1253 					    "segment silently dropped\n",
1254 					    s, __func__);
1255 					free(s, M_TCPLOG);
1256 				}
1257 				return (-1);  /* Do not send RST */
1258 			}
1259 		}
1260 
1261 		/*
1262 		 * SEG.SEQ validation:
1263 		 * The SEG.SEQ must be in the window starting at our
1264 		 * initial receive sequence number + 1.
1265 		 */
1266 		if (SEQ_LEQ(th->th_seq, sc->sc_irs) ||
1267 		    SEQ_GT(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
1268 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1269 				log(LOG_DEBUG, "%s; %s: SEQ %u != IRS+1 %u, "
1270 				    "sending challenge ACK\n",
1271 				    s, __func__, th->th_seq, sc->sc_irs + 1);
1272 			syncache_send_challenge_ack(sc, m);
1273 			SCH_UNLOCK(sch);
1274 			free(s, M_TCPLOG);
1275 			return (-1);  /* Do not send RST */
1276 		}
1277 
1278 		/*
1279 		 * SEG.ACK validation:
1280 		 * SEG.ACK must match our initial send sequence number + 1.
1281 		 */
1282 		if (th->th_ack != sc->sc_iss + 1) {
1283 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1284 				log(LOG_DEBUG, "%s; %s: ACK %u != ISS+1 %u, "
1285 				    "segment rejected\n",
1286 				    s, __func__, th->th_ack, sc->sc_iss + 1);
1287 			SCH_UNLOCK(sch);
1288 			free(s, M_TCPLOG);
1289 			return (0);  /* Do send RST, do not free sc. */
1290 		}
1291 
1292 		TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
1293 		sch->sch_length--;
1294 #ifdef TCP_OFFLOAD
1295 		if (ADDED_BY_TOE(sc)) {
1296 			struct toedev *tod = sc->sc_tod;
1297 
1298 			tod->tod_syncache_removed(tod, sc->sc_todctx);
1299 		}
1300 #endif
1301 		SCH_UNLOCK(sch);
1302 	}
1303 
1304 	*lsop = syncache_socket(sc, *lsop, m);
1305 
1306 	if (__predict_false(*lsop == NULL)) {
1307 		TCPSTAT_INC(tcps_sc_aborted);
1308 		TCPSTATES_DEC(TCPS_SYN_RECEIVED);
1309 	} else if (sc != &scs)
1310 		TCPSTAT_INC(tcps_sc_completed);
1311 
1312 	if (sc != &scs)
1313 		syncache_free(sc);
1314 	return (1);
1315 failed:
1316 	if (sc != NULL) {
1317 		TCPSTATES_DEC(TCPS_SYN_RECEIVED);
1318 		if (sc != &scs)
1319 			syncache_free(sc);
1320 	}
1321 	if (s != NULL)
1322 		free(s, M_TCPLOG);
1323 	*lsop = NULL;
1324 	return (0);
1325 }
1326 
1327 static struct socket *
syncache_tfo_expand(struct syncache * sc,struct socket * lso,struct mbuf * m,uint64_t response_cookie)1328 syncache_tfo_expand(struct syncache *sc, struct socket *lso, struct mbuf *m,
1329     uint64_t response_cookie)
1330 {
1331 	struct inpcb *inp;
1332 	struct tcpcb *tp;
1333 	unsigned int *pending_counter;
1334 	struct socket *so;
1335 
1336 	NET_EPOCH_ASSERT();
1337 
1338 	pending_counter = intotcpcb(sotoinpcb(lso))->t_tfo_pending;
1339 	so = syncache_socket(sc, lso, m);
1340 	if (so == NULL) {
1341 		TCPSTAT_INC(tcps_sc_aborted);
1342 		atomic_subtract_int(pending_counter, 1);
1343 	} else {
1344 		soisconnected(so);
1345 		inp = sotoinpcb(so);
1346 		tp = intotcpcb(inp);
1347 		tp->t_flags |= TF_FASTOPEN;
1348 		tp->t_tfo_cookie.server = response_cookie;
1349 		tp->snd_max = tp->iss;
1350 		tp->snd_nxt = tp->iss;
1351 		tp->t_tfo_pending = pending_counter;
1352 		TCPSTATES_INC(TCPS_SYN_RECEIVED);
1353 		TCPSTAT_INC(tcps_sc_completed);
1354 	}
1355 
1356 	return (so);
1357 }
1358 
1359 /*
1360  * Given a LISTEN socket and an inbound SYN request, add
1361  * this to the syn cache, and send back a segment:
1362  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1363  * to the source.
1364  *
1365  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
1366  * Doing so would require that we hold onto the data and deliver it
1367  * to the application.  However, if we are the target of a SYN-flood
1368  * DoS attack, an attacker could send data which would eventually
1369  * consume all available buffer space if it were ACKed.  By not ACKing
1370  * the data, we avoid this DoS scenario.
1371  *
1372  * The exception to the above is when a SYN with a valid TCP Fast Open (TFO)
1373  * cookie is processed and a new socket is created.  In this case, any data
1374  * accompanying the SYN will be queued to the socket by tcp_input() and will
1375  * be ACKed either when the application sends response data or the delayed
1376  * ACK timer expires, whichever comes first.
1377  */
1378 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)1379 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1380     struct inpcb *inp, struct socket *so, struct mbuf *m, void *tod,
1381     void *todctx, uint8_t iptos, uint16_t port)
1382 {
1383 	struct tcpcb *tp;
1384 	struct socket *rv = NULL;
1385 	struct syncache *sc = NULL;
1386 	struct syncache_head *sch;
1387 	struct mbuf *ipopts = NULL;
1388 	u_int ltflags;
1389 	int win, ip_ttl, ip_tos;
1390 	char *s;
1391 #ifdef INET6
1392 	int autoflowlabel = 0;
1393 #endif
1394 #ifdef MAC
1395 	struct label *maclabel = NULL;
1396 #endif
1397 	struct syncache scs;
1398 	uint64_t tfo_response_cookie;
1399 	unsigned int *tfo_pending = NULL;
1400 	int tfo_cookie_valid = 0;
1401 	int tfo_response_cookie_valid = 0;
1402 	bool locked;
1403 
1404 	INP_RLOCK_ASSERT(inp);			/* listen socket */
1405 	KASSERT((tcp_get_flags(th) & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN,
1406 	    ("%s: unexpected tcp flags", __func__));
1407 
1408 	/*
1409 	 * Combine all so/tp operations very early to drop the INP lock as
1410 	 * soon as possible.
1411 	 */
1412 	KASSERT(SOLISTENING(so), ("%s: %p not listening", __func__, so));
1413 	tp = sototcpcb(so);
1414 
1415 #ifdef INET6
1416 	if (inc->inc_flags & INC_ISIPV6) {
1417 		if (inp->inp_flags & IN6P_AUTOFLOWLABEL) {
1418 			autoflowlabel = 1;
1419 		}
1420 		ip_ttl = in6_selecthlim(inp, NULL);
1421 		if ((inp->in6p_outputopts == NULL) ||
1422 		    (inp->in6p_outputopts->ip6po_tclass == -1)) {
1423 			ip_tos = 0;
1424 		} else {
1425 			ip_tos = inp->in6p_outputopts->ip6po_tclass;
1426 		}
1427 	}
1428 #endif
1429 #if defined(INET6) && defined(INET)
1430 	else
1431 #endif
1432 #ifdef INET
1433 	{
1434 		ip_ttl = inp->inp_ip_ttl;
1435 		ip_tos = inp->inp_ip_tos;
1436 	}
1437 #endif
1438 	win = so->sol_sbrcv_hiwat;
1439 	ltflags = (tp->t_flags & (TF_NOOPT | TF_SIGNATURE));
1440 
1441 	if (V_tcp_fastopen_server_enable && (tp->t_flags & TF_FASTOPEN) &&
1442 	    (tp->t_tfo_pending != NULL) &&
1443 	    (to->to_flags & TOF_FASTOPEN)) {
1444 		/*
1445 		 * Limit the number of pending TFO connections to
1446 		 * approximately half of the queue limit.  This prevents TFO
1447 		 * SYN floods from starving the service by filling the
1448 		 * listen queue with bogus TFO connections.
1449 		 */
1450 		if (atomic_fetchadd_int(tp->t_tfo_pending, 1) <=
1451 		    (so->sol_qlimit / 2)) {
1452 			int result;
1453 
1454 			result = tcp_fastopen_check_cookie(inc,
1455 			    to->to_tfo_cookie, to->to_tfo_len,
1456 			    &tfo_response_cookie);
1457 			tfo_cookie_valid = (result > 0);
1458 			tfo_response_cookie_valid = (result >= 0);
1459 		}
1460 
1461 		/*
1462 		 * Remember the TFO pending counter as it will have to be
1463 		 * decremented below if we don't make it to syncache_tfo_expand().
1464 		 */
1465 		tfo_pending = tp->t_tfo_pending;
1466 	}
1467 
1468 #ifdef MAC
1469 	if (mac_syncache_init(&maclabel) != 0) {
1470 		INP_RUNLOCK(inp);
1471 		goto done;
1472 	} else
1473 		mac_syncache_create(maclabel, inp);
1474 #endif
1475 	if (!tfo_cookie_valid)
1476 		INP_RUNLOCK(inp);
1477 
1478 	/*
1479 	 * Remember the IP options, if any.
1480 	 */
1481 #ifdef INET6
1482 	if (!(inc->inc_flags & INC_ISIPV6))
1483 #endif
1484 #ifdef INET
1485 		ipopts = (m) ? ip_srcroute(m) : NULL;
1486 #else
1487 		ipopts = NULL;
1488 #endif
1489 
1490 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1491 	/*
1492 	 * When the socket is TCP-MD5 enabled check that,
1493 	 *  - a signed packet is valid
1494 	 *  - a non-signed packet does not have a security association
1495 	 *
1496 	 *  If a signed packet fails validation or a non-signed packet has a
1497 	 *  security association, the packet will be dropped.
1498 	 */
1499 	if (ltflags & TF_SIGNATURE) {
1500 		if (to->to_flags & TOF_SIGNATURE) {
1501 			if (!TCPMD5_ENABLED() ||
1502 			    TCPMD5_INPUT(m, th, to->to_signature) != 0)
1503 				goto done;
1504 		} else {
1505 			if (TCPMD5_ENABLED() &&
1506 			    TCPMD5_INPUT(m, NULL, NULL) != ENOENT)
1507 				goto done;
1508 		}
1509 	} else if (to->to_flags & TOF_SIGNATURE)
1510 		goto done;
1511 #endif	/* TCP_SIGNATURE */
1512 	/*
1513 	 * See if we already have an entry for this connection.
1514 	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
1515 	 *
1516 	 * XXX: should the syncache be re-initialized with the contents
1517 	 * of the new SYN here (which may have different options?)
1518 	 *
1519 	 * XXX: We do not check the sequence number to see if this is a
1520 	 * real retransmit or a new connection attempt.  The question is
1521 	 * how to handle such a case; either ignore it as spoofed, or
1522 	 * drop the current entry and create a new one?
1523 	 */
1524 	if (syncache_cookiesonly()) {
1525 		sc = NULL;
1526 		sch = syncache_hashbucket(inc);
1527 		locked = false;
1528 	} else {
1529 		sc = syncache_lookup(inc, &sch);	/* returns locked sch */
1530 		locked = true;
1531 		SCH_LOCK_ASSERT(sch);
1532 	}
1533 	if (sc != NULL) {
1534 		if (tfo_cookie_valid)
1535 			INP_RUNLOCK(inp);
1536 		TCPSTAT_INC(tcps_sc_dupsyn);
1537 		if (ipopts) {
1538 			/*
1539 			 * If we were remembering a previous source route,
1540 			 * forget it and use the new one we've been given.
1541 			 */
1542 			if (sc->sc_ipopts)
1543 				(void)m_free(sc->sc_ipopts);
1544 			sc->sc_ipopts = ipopts;
1545 		}
1546 		/*
1547 		 * Update timestamp if present.
1548 		 */
1549 		if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS))
1550 			sc->sc_tsreflect = to->to_tsval;
1551 		else
1552 			sc->sc_flags &= ~SCF_TIMESTAMP;
1553 		/*
1554 		 * Adjust ECN response if needed, e.g. different
1555 		 * IP ECN field, or a fallback by the remote host.
1556 		 */
1557 		if (sc->sc_flags & SCF_ECN_MASK) {
1558 			sc->sc_flags &= ~SCF_ECN_MASK;
1559 			sc->sc_flags |= tcp_ecn_syncache_add(tcp_get_flags(th), iptos);
1560 		}
1561 #ifdef MAC
1562 		/*
1563 		 * Since we have already unconditionally allocated label
1564 		 * storage, free it up.  The syncache entry will already
1565 		 * have an initialized label we can use.
1566 		 */
1567 		mac_syncache_destroy(&maclabel);
1568 #endif
1569 		TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1570 		/* Retransmit SYN|ACK and reset retransmit count. */
1571 		if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) {
1572 			log(LOG_DEBUG, "%s; %s: Received duplicate SYN, "
1573 			    "resetting timer and retransmitting SYN|ACK\n",
1574 			    s, __func__);
1575 			free(s, M_TCPLOG);
1576 		}
1577 		if (syncache_respond(sc, m, TH_SYN|TH_ACK) == 0) {
1578 			sc->sc_rxmits = 0;
1579 			syncache_timeout(sc, sch, 1);
1580 			TCPSTAT_INC(tcps_sndacks);
1581 			TCPSTAT_INC(tcps_sndtotal);
1582 		} else {
1583 			syncache_drop(sc, sch);
1584 			TCPSTAT_INC(tcps_sc_dropped);
1585 		}
1586 		SCH_UNLOCK(sch);
1587 		goto donenoprobe;
1588 	}
1589 
1590 	KASSERT(sc == NULL, ("sc(%p) != NULL", sc));
1591 	/*
1592 	 * Skip allocating a syncache entry if we are just going to discard
1593 	 * it later.
1594 	 */
1595 	if (!locked || tfo_cookie_valid) {
1596 		bzero(&scs, sizeof(scs));
1597 		sc = &scs;
1598 	} else {
1599 		sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1600 		if (sc == NULL) {
1601 			/*
1602 			 * The zone allocator couldn't provide more entries.
1603 			 * Treat this as if the cache was full; drop the oldest
1604 			 * entry and insert the new one.
1605 			 */
1606 			TCPSTAT_INC(tcps_sc_zonefail);
1607 			sc = TAILQ_LAST(&sch->sch_bucket, sch_head);
1608 			if (sc != NULL) {
1609 				sch->sch_last_overflow = time_uptime;
1610 				syncache_drop(sc, sch);
1611 				syncache_pause(inc);
1612 			}
1613 			sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1614 			if (sc == NULL) {
1615 				if (V_tcp_syncookies) {
1616 					bzero(&scs, sizeof(scs));
1617 					sc = &scs;
1618 				} else {
1619 					KASSERT(locked,
1620 					    ("%s: bucket unexpectedly unlocked",
1621 					    __func__));
1622 					SCH_UNLOCK(sch);
1623 					goto done;
1624 				}
1625 			}
1626 		}
1627 	}
1628 
1629 	KASSERT(sc != NULL, ("sc == NULL"));
1630 	if (!tfo_cookie_valid && tfo_response_cookie_valid)
1631 		sc->sc_tfo_cookie = &tfo_response_cookie;
1632 
1633 	/*
1634 	 * Fill in the syncache values.
1635 	 */
1636 #ifdef MAC
1637 	sc->sc_label = maclabel;
1638 #endif
1639 	/*
1640 	 * sc_cred is only used in syncache_pcblist() to list TCP endpoints in
1641 	 * TCPS_SYN_RECEIVED state when V_tcp_syncache.see_other is false.
1642 	 * Therefore, store the credentials and take a reference count only
1643 	 * when needed:
1644 	 * - sc is allocated from the zone and not using the on stack instance.
1645 	 * - the sysctl variable net.inet.tcp.syncache.see_other is false.
1646 	 * The reference count is decremented when a zone allocated sc is
1647 	 * freed in syncache_free().
1648 	 */
1649 	if (sc != &scs && !V_tcp_syncache.see_other)
1650 		sc->sc_cred = crhold(so->so_cred);
1651 	else
1652 		sc->sc_cred = NULL;
1653 	sc->sc_port = port;
1654 	sc->sc_ipopts = ipopts;
1655 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1656 	sc->sc_ip_tos = ip_tos;
1657 	sc->sc_ip_ttl = ip_ttl;
1658 #ifdef TCP_OFFLOAD
1659 	sc->sc_tod = tod;
1660 	sc->sc_todctx = todctx;
1661 #endif
1662 	sc->sc_irs = th->th_seq;
1663 	sc->sc_flags = 0;
1664 	sc->sc_flowlabel = 0;
1665 
1666 	/*
1667 	 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
1668 	 * win was derived from socket earlier in the function.
1669 	 */
1670 	win = imax(win, 0);
1671 	win = imin(win, TCP_MAXWIN);
1672 	sc->sc_wnd = win;
1673 
1674 	if (V_tcp_do_rfc1323 &&
1675 	    !(ltflags & TF_NOOPT)) {
1676 		/*
1677 		 * A timestamp received in a SYN makes
1678 		 * it ok to send timestamp requests and replies.
1679 		 */
1680 		if ((to->to_flags & TOF_TS) && (V_tcp_do_rfc1323 != 2)) {
1681 			sc->sc_tsreflect = to->to_tsval;
1682 			sc->sc_flags |= SCF_TIMESTAMP;
1683 			sc->sc_tsoff = tcp_new_ts_offset(inc);
1684 		}
1685 		if ((to->to_flags & TOF_SCALE) && (V_tcp_do_rfc1323 != 3)) {
1686 			u_int wscale = 0;
1687 
1688 			/*
1689 			 * Pick the smallest possible scaling factor that
1690 			 * will still allow us to scale up to sb_max, aka
1691 			 * kern.ipc.maxsockbuf.
1692 			 *
1693 			 * We do this because there are broken firewalls that
1694 			 * will corrupt the window scale option, leading to
1695 			 * the other endpoint believing that our advertised
1696 			 * window is unscaled.  At scale factors larger than
1697 			 * 5 the unscaled window will drop below 1500 bytes,
1698 			 * leading to serious problems when traversing these
1699 			 * broken firewalls.
1700 			 *
1701 			 * With the default maxsockbuf of 256K, a scale factor
1702 			 * of 3 will be chosen by this algorithm.  Those who
1703 			 * choose a larger maxsockbuf should watch out
1704 			 * for the compatibility problems mentioned above.
1705 			 *
1706 			 * RFC1323: The Window field in a SYN (i.e., a <SYN>
1707 			 * or <SYN,ACK>) segment itself is never scaled.
1708 			 */
1709 			while (wscale < TCP_MAX_WINSHIFT &&
1710 			    (TCP_MAXWIN << wscale) < sb_max)
1711 				wscale++;
1712 			sc->sc_requested_r_scale = wscale;
1713 			sc->sc_requested_s_scale = to->to_wscale;
1714 			sc->sc_flags |= SCF_WINSCALE;
1715 		}
1716 	}
1717 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1718 	/*
1719 	 * If incoming packet has an MD5 signature, flag this in the
1720 	 * syncache so that syncache_respond() will do the right thing
1721 	 * with the SYN+ACK.
1722 	 */
1723 	if (to->to_flags & TOF_SIGNATURE)
1724 		sc->sc_flags |= SCF_SIGNATURE;
1725 #endif	/* TCP_SIGNATURE */
1726 	if (to->to_flags & TOF_SACKPERM)
1727 		sc->sc_flags |= SCF_SACK;
1728 	if (to->to_flags & TOF_MSS)
1729 		sc->sc_peer_mss = to->to_mss;	/* peer mss may be zero */
1730 	if (ltflags & TF_NOOPT)
1731 		sc->sc_flags |= SCF_NOOPT;
1732 	/* ECN Handshake */
1733 	if (V_tcp_do_ecn && (tp->t_flags2 & TF2_CANNOT_DO_ECN) == 0)
1734 		sc->sc_flags |= tcp_ecn_syncache_add(tcp_get_flags(th), iptos);
1735 
1736 	if (V_tcp_syncookies || V_tcp_syncookiesonly)
1737 		sc->sc_iss = syncookie_generate(sch, sc);
1738 	else
1739 		sc->sc_iss = arc4random();
1740 #ifdef INET6
1741 	if (autoflowlabel) {
1742 		if (V_tcp_syncookies || V_tcp_syncookiesonly)
1743 			sc->sc_flowlabel = sc->sc_iss;
1744 		else
1745 			sc->sc_flowlabel = ip6_randomflowlabel();
1746 		sc->sc_flowlabel = htonl(sc->sc_flowlabel) & IPV6_FLOWLABEL_MASK;
1747 	}
1748 #endif
1749 	if (locked)
1750 		SCH_UNLOCK(sch);
1751 
1752 	if (tfo_cookie_valid) {
1753 		rv = syncache_tfo_expand(sc, so, m, tfo_response_cookie);
1754 		/* INP_RUNLOCK(inp) will be performed by the caller */
1755 		goto tfo_expanded;
1756 	}
1757 
1758 	TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1759 	/*
1760 	 * Do a standard 3-way handshake.
1761 	 */
1762 	if (syncache_respond(sc, m, TH_SYN|TH_ACK) == 0) {
1763 		if (sc != &scs)
1764 			syncache_insert(sc, sch);   /* locks and unlocks sch */
1765 		TCPSTAT_INC(tcps_sndacks);
1766 		TCPSTAT_INC(tcps_sndtotal);
1767 	} else {
1768 		if (sc != &scs)
1769 			syncache_free(sc);
1770 		TCPSTAT_INC(tcps_sc_dropped);
1771 	}
1772 	goto donenoprobe;
1773 
1774 done:
1775 	TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1776 donenoprobe:
1777 	if (m)
1778 		m_freem(m);
1779 	/*
1780 	 * If tfo_pending is not NULL here, then a TFO SYN that did not
1781 	 * result in a new socket was processed and the associated pending
1782 	 * counter has not yet been decremented.  All such TFO processing paths
1783 	 * transit this point.
1784 	 */
1785 	if (tfo_pending != NULL)
1786 		tcp_fastopen_decrement_counter(tfo_pending);
1787 
1788 tfo_expanded:
1789 	if (sc == NULL || sc == &scs) {
1790 #ifdef MAC
1791 		mac_syncache_destroy(&maclabel);
1792 #endif
1793 		if (ipopts)
1794 			(void)m_free(ipopts);
1795 	}
1796 	return (rv);
1797 }
1798 
1799 /*
1800  * Send SYN|ACK or ACK to the peer.  Either in response to a peer's segment,
1801  * i.e. m0 != NULL, or upon 3WHS ACK timeout, i.e. m0 == NULL.
1802  */
1803 static int
syncache_respond(struct syncache * sc,const struct mbuf * m0,int flags)1804 syncache_respond(struct syncache *sc, const struct mbuf *m0, int flags)
1805 {
1806 	struct ip *ip = NULL;
1807 	struct mbuf *m;
1808 	struct tcphdr *th = NULL;
1809 	struct udphdr *udp = NULL;
1810 	int optlen, error = 0;	/* Make compiler happy */
1811 	u_int16_t hlen, tlen, mssopt, ulen;
1812 	struct tcpopt to;
1813 #ifdef INET6
1814 	struct ip6_hdr *ip6 = NULL;
1815 #endif
1816 
1817 	NET_EPOCH_ASSERT();
1818 
1819 	hlen =
1820 #ifdef INET6
1821 	       (sc->sc_inc.inc_flags & INC_ISIPV6) ? sizeof(struct ip6_hdr) :
1822 #endif
1823 		sizeof(struct ip);
1824 	tlen = hlen + sizeof(struct tcphdr);
1825 	if (sc->sc_port) {
1826 		tlen += sizeof(struct udphdr);
1827 	}
1828 	/* Determine MSS we advertize to other end of connection. */
1829 	mssopt = tcp_mssopt(&sc->sc_inc);
1830 	if (sc->sc_port)
1831 		mssopt -= V_tcp_udp_tunneling_overhead;
1832 	mssopt = max(mssopt, V_tcp_minmss);
1833 
1834 	/* XXX: Assume that the entire packet will fit in a header mbuf. */
1835 	KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN,
1836 	    ("syncache: mbuf too small: hlen %u, sc_port %u, max_linkhdr %d + "
1837 	    "tlen %d + TCP_MAXOLEN %ju <= MHLEN %d", hlen, sc->sc_port,
1838 	    max_linkhdr, tlen, (uintmax_t)TCP_MAXOLEN, MHLEN));
1839 
1840 	/* Create the IP+TCP header from scratch. */
1841 	m = m_gethdr(M_NOWAIT, MT_DATA);
1842 	if (m == NULL)
1843 		return (ENOBUFS);
1844 #ifdef MAC
1845 	mac_syncache_create_mbuf(sc->sc_label, m);
1846 #endif
1847 	m->m_data += max_linkhdr;
1848 	m->m_len = tlen;
1849 	m->m_pkthdr.len = tlen;
1850 	m->m_pkthdr.rcvif = NULL;
1851 
1852 #ifdef INET6
1853 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
1854 		ip6 = mtod(m, struct ip6_hdr *);
1855 		ip6->ip6_vfc = IPV6_VERSION;
1856 		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1857 		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1858 		ip6->ip6_plen = htons(tlen - hlen);
1859 		/* ip6_hlim is set after checksum */
1860 		/* Zero out traffic class and flow label. */
1861 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
1862 		ip6->ip6_flow |= sc->sc_flowlabel;
1863 		if (sc->sc_port != 0) {
1864 			ip6->ip6_nxt = IPPROTO_UDP;
1865 			udp = (struct udphdr *)(ip6 + 1);
1866 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
1867 			udp->uh_dport = sc->sc_port;
1868 			ulen = (tlen - sizeof(struct ip6_hdr));
1869 			th = (struct tcphdr *)(udp + 1);
1870 		} else {
1871 			ip6->ip6_nxt = IPPROTO_TCP;
1872 			th = (struct tcphdr *)(ip6 + 1);
1873 		}
1874 		ip6->ip6_flow |= htonl(sc->sc_ip_tos << IPV6_FLOWLABEL_LEN);
1875 	}
1876 #endif
1877 #if defined(INET6) && defined(INET)
1878 	else
1879 #endif
1880 #ifdef INET
1881 	{
1882 		ip = mtod(m, struct ip *);
1883 		ip->ip_v = IPVERSION;
1884 		ip->ip_hl = sizeof(struct ip) >> 2;
1885 		ip->ip_len = htons(tlen);
1886 		ip->ip_id = 0;
1887 		ip->ip_off = 0;
1888 		ip->ip_sum = 0;
1889 		ip->ip_src = sc->sc_inc.inc_laddr;
1890 		ip->ip_dst = sc->sc_inc.inc_faddr;
1891 		ip->ip_ttl = sc->sc_ip_ttl;
1892 		ip->ip_tos = sc->sc_ip_tos;
1893 
1894 		/*
1895 		 * See if we should do MTU discovery.  Route lookups are
1896 		 * expensive, so we will only unset the DF bit if:
1897 		 *
1898 		 *	1) path_mtu_discovery is disabled
1899 		 *	2) the SCF_UNREACH flag has been set
1900 		 */
1901 		if (V_path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1902 		       ip->ip_off |= htons(IP_DF);
1903 		if (sc->sc_port == 0) {
1904 			ip->ip_p = IPPROTO_TCP;
1905 			th = (struct tcphdr *)(ip + 1);
1906 		} else {
1907 			ip->ip_p = IPPROTO_UDP;
1908 			udp = (struct udphdr *)(ip + 1);
1909 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
1910 			udp->uh_dport = sc->sc_port;
1911 			ulen = (tlen - sizeof(struct ip));
1912 			th = (struct tcphdr *)(udp + 1);
1913 		}
1914 	}
1915 #endif /* INET */
1916 	th->th_sport = sc->sc_inc.inc_lport;
1917 	th->th_dport = sc->sc_inc.inc_fport;
1918 
1919 	if (flags & TH_SYN)
1920 		th->th_seq = htonl(sc->sc_iss);
1921 	else
1922 		th->th_seq = htonl(sc->sc_iss + 1);
1923 	th->th_ack = htonl(sc->sc_irs + 1);
1924 	th->th_off = sizeof(struct tcphdr) >> 2;
1925 	th->th_win = htons(sc->sc_wnd);
1926 	th->th_urp = 0;
1927 
1928 	flags = tcp_ecn_syncache_respond(flags, sc);
1929 	tcp_set_flags(th, flags);
1930 
1931 	/* Tack on the TCP options. */
1932 	if ((sc->sc_flags & SCF_NOOPT) == 0) {
1933 		to.to_flags = 0;
1934 
1935 		if (flags & TH_SYN) {
1936 			to.to_mss = mssopt;
1937 			to.to_flags = TOF_MSS;
1938 			if (sc->sc_flags & SCF_WINSCALE) {
1939 				to.to_wscale = sc->sc_requested_r_scale;
1940 				to.to_flags |= TOF_SCALE;
1941 			}
1942 			if (sc->sc_flags & SCF_SACK)
1943 				to.to_flags |= TOF_SACKPERM;
1944 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1945 			if (sc->sc_flags & SCF_SIGNATURE)
1946 				to.to_flags |= TOF_SIGNATURE;
1947 #endif
1948 			if (sc->sc_tfo_cookie) {
1949 				to.to_flags |= TOF_FASTOPEN;
1950 				to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
1951 				to.to_tfo_cookie = sc->sc_tfo_cookie;
1952 				/* don't send cookie again when retransmitting response */
1953 				sc->sc_tfo_cookie = NULL;
1954 			}
1955 		}
1956 		if (sc->sc_flags & SCF_TIMESTAMP) {
1957 			to.to_tsval = sc->sc_tsoff + tcp_ts_getticks();
1958 			to.to_tsecr = sc->sc_tsreflect;
1959 			to.to_flags |= TOF_TS;
1960 		}
1961 		optlen = tcp_addoptions(&to, (u_char *)(th + 1));
1962 
1963 		/* Adjust headers by option size. */
1964 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1965 		m->m_len += optlen;
1966 		m->m_pkthdr.len += optlen;
1967 #ifdef INET6
1968 		if (sc->sc_inc.inc_flags & INC_ISIPV6)
1969 			ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen);
1970 		else
1971 #endif
1972 			ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
1973 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1974 		if (sc->sc_flags & SCF_SIGNATURE) {
1975 			KASSERT(to.to_flags & TOF_SIGNATURE,
1976 			    ("tcp_addoptions() didn't set tcp_signature"));
1977 
1978 			/* NOTE: to.to_signature is inside of mbuf */
1979 			if (!TCPMD5_ENABLED() ||
1980 			    TCPMD5_OUTPUT(m, th, to.to_signature) != 0) {
1981 				m_freem(m);
1982 				return (EACCES);
1983 			}
1984 		}
1985 #endif
1986 	} else
1987 		optlen = 0;
1988 
1989 	if (udp) {
1990 		ulen += optlen;
1991 		udp->uh_ulen = htons(ulen);
1992 	}
1993 	M_SETFIB(m, sc->sc_inc.inc_fibnum);
1994 	/*
1995 	 * If we have peer's SYN and it has a flowid, then let's assign it to
1996 	 * our SYN|ACK.  ip6_output() and ip_output() will not assign flowid
1997 	 * to SYN|ACK due to lack of inp here.
1998 	 */
1999 	if (m0 != NULL && M_HASHTYPE_GET(m0) != M_HASHTYPE_NONE) {
2000 		m->m_pkthdr.flowid = m0->m_pkthdr.flowid;
2001 		M_HASHTYPE_SET(m, M_HASHTYPE_GET(m0));
2002 	}
2003 #ifdef INET6
2004 	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
2005 		if (sc->sc_port) {
2006 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
2007 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2008 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen,
2009 			      IPPROTO_UDP, 0);
2010 			th->th_sum = htons(0);
2011 		} else {
2012 			m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2013 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2014 			th->th_sum = in6_cksum_pseudo(ip6, tlen + optlen - hlen,
2015 			    IPPROTO_TCP, 0);
2016 		}
2017 		ip6->ip6_hlim = sc->sc_ip_ttl;
2018 #ifdef TCP_OFFLOAD
2019 		if (ADDED_BY_TOE(sc)) {
2020 			struct toedev *tod = sc->sc_tod;
2021 
2022 			error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
2023 
2024 			return (error);
2025 		}
2026 #endif
2027 		TCP_PROBE5(send, NULL, NULL, ip6, NULL, th);
2028 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2029 	}
2030 #endif
2031 #if defined(INET6) && defined(INET)
2032 	else
2033 #endif
2034 #ifdef INET
2035 	{
2036 		if (sc->sc_port) {
2037 			m->m_pkthdr.csum_flags = CSUM_UDP;
2038 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2039 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
2040 			      ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
2041 			th->th_sum = htons(0);
2042 		} else {
2043 			m->m_pkthdr.csum_flags = CSUM_TCP;
2044 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2045 			th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2046 			    htons(tlen + optlen - hlen + IPPROTO_TCP));
2047 		}
2048 #ifdef TCP_OFFLOAD
2049 		if (ADDED_BY_TOE(sc)) {
2050 			struct toedev *tod = sc->sc_tod;
2051 
2052 			error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
2053 
2054 			return (error);
2055 		}
2056 #endif
2057 		TCP_PROBE5(send, NULL, NULL, ip, NULL, th);
2058 		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
2059 	}
2060 #endif
2061 	return (error);
2062 }
2063 
2064 static void
syncache_send_challenge_ack(struct syncache * sc,struct mbuf * m)2065 syncache_send_challenge_ack(struct syncache *sc, struct mbuf *m)
2066 {
2067 	if (tcp_challenge_ack_check(&sc->sc_challenge_ack_end,
2068 	    &sc->sc_challenge_ack_cnt)) {
2069 		if (syncache_respond(sc, m, TH_ACK) == 0) {
2070 			TCPSTAT_INC(tcps_sndacks);
2071 			TCPSTAT_INC(tcps_sndtotal);
2072 		}
2073 	}
2074 }
2075 
2076 /*
2077  * The purpose of syncookies is to handle spoofed SYN flooding DoS attacks
2078  * that exceed the capacity of the syncache by avoiding the storage of any
2079  * of the SYNs we receive.  Syncookies defend against blind SYN flooding
2080  * attacks where the attacker does not have access to our responses.
2081  *
2082  * Syncookies encode and include all necessary information about the
2083  * connection setup within the SYN|ACK that we send back.  That way we
2084  * can avoid keeping any local state until the ACK to our SYN|ACK returns
2085  * (if ever).  Normally the syncache and syncookies are running in parallel
2086  * with the latter taking over when the former is exhausted.  When matching
2087  * syncache entry is found the syncookie is ignored.
2088  *
2089  * The only reliable information persisting the 3WHS is our initial sequence
2090  * number ISS of 32 bits.  Syncookies embed a cryptographically sufficient
2091  * strong hash (MAC) value and a few bits of TCP SYN options in the ISS
2092  * of our SYN|ACK.  The MAC can be recomputed when the ACK to our SYN|ACK
2093  * returns and signifies a legitimate connection if it matches the ACK.
2094  *
2095  * The available space of 32 bits to store the hash and to encode the SYN
2096  * option information is very tight and we should have at least 24 bits for
2097  * the MAC to keep the number of guesses by blind spoofing reasonably high.
2098  *
2099  * SYN option information we have to encode to fully restore a connection:
2100  * MSS: is imporant to chose an optimal segment size to avoid IP level
2101  *   fragmentation along the path.  The common MSS values can be encoded
2102  *   in a 3-bit table.  Uncommon values are captured by the next lower value
2103  *   in the table leading to a slight increase in packetization overhead.
2104  * WSCALE: is necessary to allow large windows to be used for high delay-
2105  *   bandwidth product links.  Not scaling the window when it was initially
2106  *   negotiated is bad for performance as lack of scaling further decreases
2107  *   the apparent available send window.  We only need to encode the WSCALE
2108  *   we received from the remote end.  Our end can be recalculated at any
2109  *   time.  The common WSCALE values can be encoded in a 3-bit table.
2110  *   Uncommon values are captured by the next lower value in the table
2111  *   making us under-estimate the available window size halving our
2112  *   theoretically possible maximum throughput for that connection.
2113  * SACK: Greatly assists in packet loss recovery and requires 1 bit.
2114  * TIMESTAMP and SIGNATURE is not encoded because they are permanent options
2115  *   that are included in all segments on a connection.  We enable them when
2116  *   the ACK has them.
2117  *
2118  * Security of syncookies and attack vectors:
2119  *
2120  * The MAC is computed over (faddr||laddr||fport||lport||irs||flags||secmod)
2121  * together with the gloabl secret to make it unique per connection attempt.
2122  * Thus any change of any of those parameters results in a different MAC output
2123  * in an unpredictable way unless a collision is encountered.  24 bits of the
2124  * MAC are embedded into the ISS.
2125  *
2126  * To prevent replay attacks two rotating global secrets are updated with a
2127  * new random value every 15 seconds.  The life-time of a syncookie is thus
2128  * 15-30 seconds.
2129  *
2130  * Vector 1: Attacking the secret.  This requires finding a weakness in the
2131  * MAC itself or the way it is used here.  The attacker can do a chosen plain
2132  * text attack by varying and testing the all parameters under his control.
2133  * The strength depends on the size and randomness of the secret, and the
2134  * cryptographic security of the MAC function.  Due to the constant updating
2135  * of the secret the attacker has at most 29.999 seconds to find the secret
2136  * and launch spoofed connections.  After that he has to start all over again.
2137  *
2138  * Vector 2: Collision attack on the MAC of a single ACK.  With a 24 bit MAC
2139  * size an average of 4,823 attempts are required for a 50% chance of success
2140  * to spoof a single syncookie (birthday collision paradox).  However the
2141  * attacker is blind and doesn't know if one of his attempts succeeded unless
2142  * he has a side channel to interfere success from.  A single connection setup
2143  * success average of 90% requires 8,790 packets, 99.99% requires 17,578 packets.
2144  * This many attempts are required for each one blind spoofed connection.  For
2145  * every additional spoofed connection he has to launch another N attempts.
2146  * Thus for a sustained rate 100 spoofed connections per second approximately
2147  * 1,800,000 packets per second would have to be sent.
2148  *
2149  * NB: The MAC function should be fast so that it doesn't become a CPU
2150  * exhaustion attack vector itself.
2151  *
2152  * References:
2153  *  RFC4987 TCP SYN Flooding Attacks and Common Mitigations
2154  *  SYN cookies were first proposed by cryptographer Dan J. Bernstein in 1996
2155  *   http://cr.yp.to/syncookies.html    (overview)
2156  *   http://cr.yp.to/syncookies/archive (details)
2157  *
2158  *
2159  * Schematic construction of a syncookie enabled Initial Sequence Number:
2160  *  0        1         2         3
2161  *  12345678901234567890123456789012
2162  * |xxxxxxxxxxxxxxxxxxxxxxxxWWWMMMSP|
2163  *
2164  *  x 24 MAC (truncated)
2165  *  W  3 Send Window Scale index
2166  *  M  3 MSS index
2167  *  S  1 SACK permitted
2168  *  P  1 Odd/even secret
2169  */
2170 
2171 /*
2172  * Distribution and probability of certain MSS values.  Those in between are
2173  * rounded down to the next lower one.
2174  * [An Analysis of TCP Maximum Segment Sizes, S. Alcock and R. Nelson, 2011]
2175  *                            .2%  .3%   5%    7%    7%    20%   15%   45%
2176  */
2177 static int tcp_sc_msstab[] = { 216, 536, 1200, 1360, 1400, 1440, 1452, 1460 };
2178 
2179 /*
2180  * Distribution and probability of certain WSCALE values.  We have to map the
2181  * (send) window scale (shift) option with a range of 0-14 from 4 bits into 3
2182  * bits based on prevalence of certain values.  Where we don't have an exact
2183  * match for are rounded down to the next lower one letting us under-estimate
2184  * the true available window.  At the moment this would happen only for the
2185  * very uncommon values 3, 5 and those above 8 (more than 16MB socket buffer
2186  * and window size).  The absence of the WSCALE option (no scaling in either
2187  * direction) is encoded with index zero.
2188  * [WSCALE values histograms, Allman, 2012]
2189  *                            X 10 10 35  5  6 14 10%   by host
2190  *                            X 11  4  5  5 18 49  3%   by connections
2191  */
2192 static int tcp_sc_wstab[] = { 0, 0, 1, 2, 4, 6, 7, 8 };
2193 
2194 /*
2195  * Compute the MAC for the SYN cookie.  SIPHASH-2-4 is chosen for its speed
2196  * and good cryptographic properties.
2197  */
2198 static uint32_t
syncookie_mac(struct in_conninfo * inc,tcp_seq irs,uint8_t flags,uint8_t * secbits,uintptr_t secmod)2199 syncookie_mac(struct in_conninfo *inc, tcp_seq irs, uint8_t flags,
2200     uint8_t *secbits, uintptr_t secmod)
2201 {
2202 	SIPHASH_CTX ctx;
2203 	uint32_t siphash[2];
2204 
2205 	SipHash24_Init(&ctx);
2206 	SipHash_SetKey(&ctx, secbits);
2207 	switch (inc->inc_flags & INC_ISIPV6) {
2208 #ifdef INET
2209 	case 0:
2210 		SipHash_Update(&ctx, &inc->inc_faddr, sizeof(inc->inc_faddr));
2211 		SipHash_Update(&ctx, &inc->inc_laddr, sizeof(inc->inc_laddr));
2212 		break;
2213 #endif
2214 #ifdef INET6
2215 	case INC_ISIPV6:
2216 		SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(inc->inc6_faddr));
2217 		SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(inc->inc6_laddr));
2218 		break;
2219 #endif
2220 	}
2221 	SipHash_Update(&ctx, &inc->inc_fport, sizeof(inc->inc_fport));
2222 	SipHash_Update(&ctx, &inc->inc_lport, sizeof(inc->inc_lport));
2223 	SipHash_Update(&ctx, &irs, sizeof(irs));
2224 	SipHash_Update(&ctx, &flags, sizeof(flags));
2225 	SipHash_Update(&ctx, &secmod, sizeof(secmod));
2226 	SipHash_Final((u_int8_t *)&siphash, &ctx);
2227 
2228 	return (siphash[0] ^ siphash[1]);
2229 }
2230 
2231 static tcp_seq
syncookie_generate(struct syncache_head * sch,struct syncache * sc)2232 syncookie_generate(struct syncache_head *sch, struct syncache *sc)
2233 {
2234 	u_int i, secbit, wscale;
2235 	uint32_t iss, hash;
2236 	uint8_t *secbits;
2237 	union syncookie cookie;
2238 
2239 	cookie.cookie = 0;
2240 
2241 	/* Map our computed MSS into the 3-bit index. */
2242 	for (i = nitems(tcp_sc_msstab) - 1;
2243 	     tcp_sc_msstab[i] > sc->sc_peer_mss && i > 0;
2244 	     i--)
2245 		;
2246 	cookie.flags.mss_idx = i;
2247 
2248 	/*
2249 	 * Map the send window scale into the 3-bit index but only if
2250 	 * the wscale option was received.
2251 	 */
2252 	if (sc->sc_flags & SCF_WINSCALE) {
2253 		wscale = sc->sc_requested_s_scale;
2254 		for (i = nitems(tcp_sc_wstab) - 1;
2255 		    tcp_sc_wstab[i] > wscale && i > 0;
2256 		     i--)
2257 			;
2258 		cookie.flags.wscale_idx = i;
2259 	}
2260 
2261 	/* Can we do SACK? */
2262 	if (sc->sc_flags & SCF_SACK)
2263 		cookie.flags.sack_ok = 1;
2264 
2265 	/* Which of the two secrets to use. */
2266 	secbit = V_tcp_syncache.secret.oddeven & 0x1;
2267 	cookie.flags.odd_even = secbit;
2268 
2269 	secbits = V_tcp_syncache.secret.key[secbit];
2270 	hash = syncookie_mac(&sc->sc_inc, sc->sc_irs, cookie.cookie, secbits,
2271 	    (uintptr_t)sch);
2272 
2273 	/*
2274 	 * Put the flags into the hash and XOR them to get better ISS number
2275 	 * variance.  This doesn't enhance the cryptographic strength and is
2276 	 * done to prevent the 8 cookie bits from showing up directly on the
2277 	 * wire.
2278 	 */
2279 	iss = hash & ~0xff;
2280 	iss |= cookie.cookie ^ (hash >> 24);
2281 
2282 	TCPSTAT_INC(tcps_sc_sendcookie);
2283 	return (iss);
2284 }
2285 
2286 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)2287 syncookie_expand(struct in_conninfo *inc, const struct syncache_head *sch,
2288     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2289     struct socket *lso, uint16_t port)
2290 {
2291 	uint32_t hash;
2292 	uint8_t *secbits;
2293 	tcp_seq ack, seq;
2294 	int wnd;
2295 	union syncookie cookie;
2296 
2297 	/*
2298 	 * Pull information out of SYN-ACK/ACK and revert sequence number
2299 	 * advances.
2300 	 */
2301 	ack = th->th_ack - 1;
2302 	seq = th->th_seq - 1;
2303 
2304 	/*
2305 	 * Unpack the flags containing enough information to restore the
2306 	 * connection.
2307 	 */
2308 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
2309 
2310 	/* Which of the two secrets to use. */
2311 	secbits = V_tcp_syncache.secret.key[cookie.flags.odd_even];
2312 
2313 	hash = syncookie_mac(inc, seq, cookie.cookie, secbits, (uintptr_t)sch);
2314 
2315 	/* The recomputed hash matches the ACK if this was a genuine cookie. */
2316 	if ((ack & ~0xff) != (hash & ~0xff))
2317 		return (false);
2318 
2319 	/* Fill in the syncache values. */
2320 	sc->sc_flags = 0;
2321 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
2322 	sc->sc_ipopts = NULL;
2323 
2324 	sc->sc_irs = seq;
2325 	sc->sc_iss = ack;
2326 
2327 	switch (inc->inc_flags & INC_ISIPV6) {
2328 #ifdef INET
2329 	case 0:
2330 		sc->sc_ip_ttl = sotoinpcb(lso)->inp_ip_ttl;
2331 		sc->sc_ip_tos = sotoinpcb(lso)->inp_ip_tos;
2332 		break;
2333 #endif
2334 #ifdef INET6
2335 	case INC_ISIPV6:
2336 		if (sotoinpcb(lso)->inp_flags & IN6P_AUTOFLOWLABEL)
2337 			sc->sc_flowlabel =
2338 			    htonl(sc->sc_iss) & IPV6_FLOWLABEL_MASK;
2339 		break;
2340 #endif
2341 	}
2342 
2343 	sc->sc_peer_mss = tcp_sc_msstab[cookie.flags.mss_idx];
2344 
2345 	/* Only use wscale if it was enabled in the orignal SYN. */
2346 	if (cookie.flags.wscale_idx > 0) {
2347 		u_int wscale = 0;
2348 
2349 		/* Recompute the receive window scale that was sent earlier. */
2350 		while (wscale < TCP_MAX_WINSHIFT &&
2351 		    (TCP_MAXWIN << wscale) < sb_max)
2352 			wscale++;
2353 		sc->sc_requested_r_scale = wscale;
2354 		sc->sc_requested_s_scale = tcp_sc_wstab[cookie.flags.wscale_idx];
2355 		sc->sc_flags |= SCF_WINSCALE;
2356 	}
2357 
2358 	wnd = lso->sol_sbrcv_hiwat;
2359 	wnd = imax(wnd, 0);
2360 	wnd = imin(wnd, TCP_MAXWIN);
2361 	sc->sc_wnd = wnd;
2362 
2363 	if (cookie.flags.sack_ok)
2364 		sc->sc_flags |= SCF_SACK;
2365 
2366 	if (to->to_flags & TOF_TS) {
2367 		sc->sc_flags |= SCF_TIMESTAMP;
2368 		sc->sc_tsreflect = to->to_tsval;
2369 		sc->sc_tsoff = tcp_new_ts_offset(inc);
2370 	}
2371 
2372 	if (to->to_flags & TOF_SIGNATURE)
2373 		sc->sc_flags |= SCF_SIGNATURE;
2374 
2375 	sc->sc_rxmits = 0;
2376 
2377 	sc->sc_port = port;
2378 
2379 	return (true);
2380 }
2381 
2382 #ifdef INVARIANTS
2383 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)2384 syncookie_cmp(struct in_conninfo *inc, const struct syncache_head *sch,
2385     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2386     struct socket *lso, uint16_t port)
2387 {
2388 	struct syncache scs;
2389 	char *s;
2390 
2391 	bzero(&scs, sizeof(scs));
2392 	if (syncookie_expand(inc, sch, &scs, th, to, lso, port) &&
2393 	    (sc->sc_peer_mss != scs.sc_peer_mss ||
2394 	     sc->sc_requested_r_scale != scs.sc_requested_r_scale ||
2395 	     sc->sc_requested_s_scale != scs.sc_requested_s_scale ||
2396 	     (sc->sc_flags & SCF_SACK) != (scs.sc_flags & SCF_SACK))) {
2397 
2398 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)) == NULL)
2399 			return;
2400 
2401 		if (sc->sc_peer_mss != scs.sc_peer_mss)
2402 			log(LOG_DEBUG, "%s; %s: mss different %i vs %i\n",
2403 			    s, __func__, sc->sc_peer_mss, scs.sc_peer_mss);
2404 
2405 		if (sc->sc_requested_r_scale != scs.sc_requested_r_scale)
2406 			log(LOG_DEBUG, "%s; %s: rwscale different %i vs %i\n",
2407 			    s, __func__, sc->sc_requested_r_scale,
2408 			    scs.sc_requested_r_scale);
2409 
2410 		if (sc->sc_requested_s_scale != scs.sc_requested_s_scale)
2411 			log(LOG_DEBUG, "%s; %s: swscale different %i vs %i\n",
2412 			    s, __func__, sc->sc_requested_s_scale,
2413 			    scs.sc_requested_s_scale);
2414 
2415 		if ((sc->sc_flags & SCF_SACK) != (scs.sc_flags & SCF_SACK))
2416 			log(LOG_DEBUG, "%s; %s: SACK different\n", s, __func__);
2417 
2418 		free(s, M_TCPLOG);
2419 	}
2420 }
2421 #endif /* INVARIANTS */
2422 
2423 static void
syncookie_reseed(void * arg)2424 syncookie_reseed(void *arg)
2425 {
2426 	struct tcp_syncache *sc = arg;
2427 	uint8_t *secbits;
2428 	int secbit;
2429 
2430 	/*
2431 	 * Reseeding the secret doesn't have to be protected by a lock.
2432 	 * It only must be ensured that the new random values are visible
2433 	 * to all CPUs in a SMP environment.  The atomic with release
2434 	 * semantics ensures that.
2435 	 */
2436 	secbit = (sc->secret.oddeven & 0x1) ? 0 : 1;
2437 	secbits = sc->secret.key[secbit];
2438 	arc4rand(secbits, SYNCOOKIE_SECRET_SIZE, 0);
2439 	atomic_add_rel_int(&sc->secret.oddeven, 1);
2440 
2441 	/* Reschedule ourself. */
2442 	callout_schedule(&sc->secret.reseed, SYNCOOKIE_LIFETIME * hz);
2443 }
2444 
2445 /*
2446  * We have overflowed a bucket. Let's pause dealing with the syncache.
2447  * This function will increment the bucketoverflow statistics appropriately
2448  * (once per pause when pausing is enabled; otherwise, once per overflow).
2449  */
2450 static void
syncache_pause(struct in_conninfo * inc)2451 syncache_pause(struct in_conninfo *inc)
2452 {
2453 	time_t delta;
2454 	const char *s;
2455 
2456 	/* XXX:
2457 	 * 2. Add sysctl read here so we don't get the benefit of this
2458 	 * change without the new sysctl.
2459 	 */
2460 
2461 	/*
2462 	 * Try an unlocked read. If we already know that another thread
2463 	 * has activated the feature, there is no need to proceed.
2464 	 */
2465 	if (V_tcp_syncache.paused)
2466 		return;
2467 
2468 	/* Are cookied enabled? If not, we can't pause. */
2469 	if (!V_tcp_syncookies) {
2470 		TCPSTAT_INC(tcps_sc_bucketoverflow);
2471 		return;
2472 	}
2473 
2474 	/*
2475 	 * We may be the first thread to find an overflow. Get the lock
2476 	 * and evaluate if we need to take action.
2477 	 */
2478 	mtx_lock(&V_tcp_syncache.pause_mtx);
2479 	if (V_tcp_syncache.paused) {
2480 		mtx_unlock(&V_tcp_syncache.pause_mtx);
2481 		return;
2482 	}
2483 
2484 	/* Activate protection. */
2485 	V_tcp_syncache.paused = true;
2486 	TCPSTAT_INC(tcps_sc_bucketoverflow);
2487 
2488 	/*
2489 	 * Determine the last backoff time. If we are seeing a re-newed
2490 	 * attack within that same time after last reactivating the syncache,
2491 	 * consider it an extension of the same attack.
2492 	 */
2493 	delta = TCP_SYNCACHE_PAUSE_TIME << V_tcp_syncache.pause_backoff;
2494 	if (V_tcp_syncache.pause_until + delta - time_uptime > 0) {
2495 		if (V_tcp_syncache.pause_backoff < TCP_SYNCACHE_MAX_BACKOFF) {
2496 			delta <<= 1;
2497 			V_tcp_syncache.pause_backoff++;
2498 		}
2499 	} else {
2500 		delta = TCP_SYNCACHE_PAUSE_TIME;
2501 		V_tcp_syncache.pause_backoff = 0;
2502 	}
2503 
2504 	/* Log a warning, including IP addresses, if able. */
2505 	if (inc != NULL)
2506 		s = tcp_log_addrs(inc, NULL, NULL, NULL);
2507 	else
2508 		s = (const char *)NULL;
2509 	log(LOG_WARNING, "TCP syncache overflow detected; using syncookies for "
2510 	    "the next %lld seconds%s%s%s\n", (long long)delta,
2511 	    (s != NULL) ? " (last SYN: " : "", (s != NULL) ? s : "",
2512 	    (s != NULL) ? ")" : "");
2513 	free(__DECONST(void *, s), M_TCPLOG);
2514 
2515 	/* Use the calculated delta to set a new pause time. */
2516 	V_tcp_syncache.pause_until = time_uptime + delta;
2517 	callout_reset(&V_tcp_syncache.pause_co, delta * hz, syncache_unpause,
2518 	    &V_tcp_syncache);
2519 	mtx_unlock(&V_tcp_syncache.pause_mtx);
2520 }
2521 
2522 /* Evaluate whether we need to unpause. */
2523 static void
syncache_unpause(void * arg)2524 syncache_unpause(void *arg)
2525 {
2526 	struct tcp_syncache *sc;
2527 	time_t delta;
2528 
2529 	sc = arg;
2530 	mtx_assert(&sc->pause_mtx, MA_OWNED | MA_NOTRECURSED);
2531 	callout_deactivate(&sc->pause_co);
2532 
2533 	/*
2534 	 * Check to make sure we are not running early. If the pause
2535 	 * time has expired, then deactivate the protection.
2536 	 */
2537 	if ((delta = sc->pause_until - time_uptime) > 0)
2538 		callout_schedule(&sc->pause_co, delta * hz);
2539 	else
2540 		sc->paused = false;
2541 }
2542 
2543 /*
2544  * Exports the syncache entries to userland so that netstat can display
2545  * them alongside the other sockets.  This function is intended to be
2546  * called only from tcp_pcblist.
2547  *
2548  * Due to concurrency on an active system, the number of pcbs exported
2549  * may have no relation to max_pcbs.  max_pcbs merely indicates the
2550  * amount of space the caller allocated for this function to use.
2551  */
2552 int
syncache_pcblist(struct sysctl_req * req)2553 syncache_pcblist(struct sysctl_req *req)
2554 {
2555 	struct xtcpcb xt;
2556 	struct syncache *sc;
2557 	struct syncache_head *sch;
2558 	int error, i;
2559 
2560 	bzero(&xt, sizeof(xt));
2561 	xt.xt_len = sizeof(xt);
2562 	xt.t_state = TCPS_SYN_RECEIVED;
2563 	xt.xt_inp.xi_socket.xso_protocol = IPPROTO_TCP;
2564 	xt.xt_inp.xi_socket.xso_len = sizeof (struct xsocket);
2565 	xt.xt_inp.xi_socket.so_type = SOCK_STREAM;
2566 	xt.xt_inp.xi_socket.so_state = SS_ISCONNECTING;
2567 
2568 	for (i = 0; i < V_tcp_syncache.hashsize; i++) {
2569 		sch = &V_tcp_syncache.hashbase[i];
2570 		SCH_LOCK(sch);
2571 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
2572 			if (sc->sc_cred != NULL &&
2573 			    cr_cansee(req->td->td_ucred, sc->sc_cred) != 0)
2574 				continue;
2575 			if (sc->sc_inc.inc_flags & INC_ISIPV6)
2576 				xt.xt_inp.inp_vflag = INP_IPV6;
2577 			else
2578 				xt.xt_inp.inp_vflag = INP_IPV4;
2579 			xt.xt_encaps_port = sc->sc_port;
2580 			bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc,
2581 			    sizeof (struct in_conninfo));
2582 			error = SYSCTL_OUT(req, &xt, sizeof xt);
2583 			if (error) {
2584 				SCH_UNLOCK(sch);
2585 				return (0);
2586 			}
2587 		}
2588 		SCH_UNLOCK(sch);
2589 	}
2590 
2591 	return (0);
2592 }
2593