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