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