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