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