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