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