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