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