xref: /freebsd/sys/netinet/tcp_syncache.c (revision ea906c4152774dff300bb26fbfc1e4188351c89a)
1 /*-
2  * Copyright (c) 2001 McAfee, Inc.
3  * Copyright (c) 2006 Andre Oppermann, Internet Business Solutions AG
4  * All rights reserved.
5  *
6  * This software was developed for the FreeBSD Project by Jonathan Lemon
7  * and McAfee Research, the Security Research Division of McAfee, Inc. under
8  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
9  * DARPA CHATS research program.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_mac.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/sysctl.h>
45 #include <sys/limits.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/md5.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/vimage.h>
57 
58 #include <vm/uma.h>
59 
60 #include <net/if.h>
61 #include <net/route.h>
62 
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
66 #include <netinet/in_var.h>
67 #include <netinet/in_pcb.h>
68 #include <netinet/ip_var.h>
69 #include <netinet/ip_options.h>
70 #ifdef INET6
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <netinet6/nd6.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/in6_pcb.h>
76 #endif
77 #include <netinet/tcp.h>
78 #include <netinet/tcp_fsm.h>
79 #include <netinet/tcp_seq.h>
80 #include <netinet/tcp_timer.h>
81 #include <netinet/tcp_var.h>
82 #include <netinet/tcp_syncache.h>
83 #include <netinet/tcp_offload.h>
84 #ifdef INET6
85 #include <netinet6/tcp6_var.h>
86 #endif
87 
88 #ifdef IPSEC
89 #include <netipsec/ipsec.h>
90 #ifdef INET6
91 #include <netipsec/ipsec6.h>
92 #endif
93 #include <netipsec/key.h>
94 #endif /*IPSEC*/
95 
96 #include <machine/in_cksum.h>
97 
98 #include <security/mac/mac_framework.h>
99 
100 static int tcp_syncookies = 1;
101 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
102     &tcp_syncookies, 0,
103     "Use TCP SYN cookies if the syncache overflows");
104 
105 static int tcp_syncookiesonly = 0;
106 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies_only, CTLFLAG_RW,
107     &tcp_syncookiesonly, 0,
108     "Use only TCP SYN cookies");
109 
110 #define	SYNCOOKIE_SECRET_SIZE	8	/* dwords */
111 #define	SYNCOOKIE_LIFETIME	16	/* seconds */
112 
113 struct syncache {
114 	TAILQ_ENTRY(syncache)	sc_hash;
115 	struct		in_conninfo sc_inc;	/* addresses */
116 	int		sc_rxttime;		/* retransmit time */
117 	u_int16_t	sc_rxmits;		/* retransmit counter */
118 
119 	u_int32_t	sc_tsreflect;		/* timestamp to reflect */
120 	u_int32_t	sc_ts;			/* our timestamp to send */
121 	u_int32_t	sc_tsoff;		/* ts offset w/ syncookies */
122 	u_int32_t	sc_flowlabel;		/* IPv6 flowlabel */
123 	tcp_seq		sc_irs;			/* seq from peer */
124 	tcp_seq		sc_iss;			/* our ISS */
125 	struct		mbuf *sc_ipopts;	/* source route */
126 
127 	u_int16_t	sc_peer_mss;		/* peer's MSS */
128 	u_int16_t	sc_wnd;			/* advertised window */
129 	u_int8_t	sc_ip_ttl;		/* IPv4 TTL */
130 	u_int8_t	sc_ip_tos;		/* IPv4 TOS */
131 	u_int8_t	sc_requested_s_scale:4,
132 			sc_requested_r_scale:4;
133 	u_int16_t	sc_flags;
134 #define SCF_NOOPT	0x01			/* no TCP options */
135 #define SCF_WINSCALE	0x02			/* negotiated window scaling */
136 #define SCF_TIMESTAMP	0x04			/* negotiated timestamps */
137 						/* MSS is implicit */
138 #define SCF_UNREACH	0x10			/* icmp unreachable received */
139 #define SCF_SIGNATURE	0x20			/* send MD5 digests */
140 #define SCF_SACK	0x80			/* send SACK option */
141 #define SCF_ECN		0x100			/* send ECN setup packet */
142 #ifndef TCP_OFFLOAD_DISABLE
143 	struct toe_usrreqs *sc_tu;		/* TOE operations */
144 	void 		*sc_toepcb;		/* TOE protocol block */
145 #endif
146 #ifdef MAC
147 	struct label	*sc_label;		/* MAC label reference */
148 #endif
149 };
150 
151 #ifdef TCP_OFFLOAD_DISABLE
152 #define TOEPCB_ISSET(sc) (0)
153 #else
154 #define TOEPCB_ISSET(sc) ((sc)->sc_toepcb != NULL)
155 #endif
156 
157 
158 struct syncache_head {
159 	struct mtx	sch_mtx;
160 	TAILQ_HEAD(sch_head, syncache)	sch_bucket;
161 	struct callout	sch_timer;
162 	int		sch_nextc;
163 	u_int		sch_length;
164 	u_int		sch_oddeven;
165 	u_int32_t	sch_secbits_odd[SYNCOOKIE_SECRET_SIZE];
166 	u_int32_t	sch_secbits_even[SYNCOOKIE_SECRET_SIZE];
167 	u_int		sch_reseed;		/* time_uptime, seconds */
168 };
169 
170 static void	 syncache_drop(struct syncache *, struct syncache_head *);
171 static void	 syncache_free(struct syncache *);
172 static void	 syncache_insert(struct syncache *, struct syncache_head *);
173 struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
174 static int	 syncache_respond(struct syncache *);
175 static struct	 socket *syncache_socket(struct syncache *, struct socket *,
176 		    struct mbuf *m);
177 static void	 syncache_timeout(struct syncache *sc, struct syncache_head *sch,
178 		    int docallout);
179 static void	 syncache_timer(void *);
180 static void	 syncookie_generate(struct syncache_head *, struct syncache *,
181 		    u_int32_t *);
182 static struct syncache
183 		*syncookie_lookup(struct in_conninfo *, struct syncache_head *,
184 		    struct syncache *, struct tcpopt *, struct tcphdr *,
185 		    struct socket *);
186 
187 /*
188  * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
189  * 3 retransmits corresponds to a timeout of 3 * (1 + 2 + 4 + 8) == 45 seconds,
190  * the odds are that the user has given up attempting to connect by then.
191  */
192 #define SYNCACHE_MAXREXMTS		3
193 
194 /* Arbitrary values */
195 #define TCP_SYNCACHE_HASHSIZE		512
196 #define TCP_SYNCACHE_BUCKETLIMIT	30
197 
198 struct tcp_syncache {
199 	struct	syncache_head *hashbase;
200 	uma_zone_t zone;
201 	u_int	hashsize;
202 	u_int	hashmask;
203 	u_int	bucket_limit;
204 	u_int	cache_count;		/* XXX: unprotected */
205 	u_int	cache_limit;
206 	u_int	rexmt_limit;
207 	u_int	hash_secret;
208 };
209 static struct tcp_syncache tcp_syncache;
210 
211 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
212 
213 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RDTUN,
214      &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
215 
216 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RDTUN,
217      &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
218 
219 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
220      &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
221 
222 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RDTUN,
223      &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
224 
225 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
226      &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
227 
228 int	tcp_sc_rst_sock_fail = 1;
229 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rst_on_sock_fail, CTLFLAG_RW,
230      &tcp_sc_rst_sock_fail, 0, "Send reset on socket allocation failure");
231 
232 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
233 
234 #define SYNCACHE_HASH(inc, mask)					\
235 	((V_tcp_syncache.hash_secret ^					\
236 	  (inc)->inc_faddr.s_addr ^					\
237 	  ((inc)->inc_faddr.s_addr >> 16) ^				\
238 	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
239 
240 #define SYNCACHE_HASH6(inc, mask)					\
241 	((V_tcp_syncache.hash_secret ^					\
242 	  (inc)->inc6_faddr.s6_addr32[0] ^				\
243 	  (inc)->inc6_faddr.s6_addr32[3] ^				\
244 	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
245 
246 #define ENDPTS_EQ(a, b) (						\
247 	(a)->ie_fport == (b)->ie_fport &&				\
248 	(a)->ie_lport == (b)->ie_lport &&				\
249 	(a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&			\
250 	(a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr			\
251 )
252 
253 #define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
254 
255 #define	SCH_LOCK(sch)		mtx_lock(&(sch)->sch_mtx)
256 #define	SCH_UNLOCK(sch)		mtx_unlock(&(sch)->sch_mtx)
257 #define	SCH_LOCK_ASSERT(sch)	mtx_assert(&(sch)->sch_mtx, MA_OWNED)
258 
259 /*
260  * Requires the syncache entry to be already removed from the bucket list.
261  */
262 static void
263 syncache_free(struct syncache *sc)
264 {
265 	if (sc->sc_ipopts)
266 		(void) m_free(sc->sc_ipopts);
267 #ifdef MAC
268 	mac_syncache_destroy(&sc->sc_label);
269 #endif
270 
271 	uma_zfree(V_tcp_syncache.zone, sc);
272 }
273 
274 void
275 syncache_init(void)
276 {
277 	int i;
278 
279 	V_tcp_syncache.cache_count = 0;
280 	V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
281 	V_tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
282 	V_tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
283 	V_tcp_syncache.hash_secret = arc4random();
284 
285 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
286 	    &V_tcp_syncache.hashsize);
287 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
288 	    &V_tcp_syncache.bucket_limit);
289 	if (!powerof2(V_tcp_syncache.hashsize) ||
290 	    V_tcp_syncache.hashsize == 0) {
291 		printf("WARNING: syncache hash size is not a power of 2.\n");
292 		V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
293 	}
294 	V_tcp_syncache.hashmask = V_tcp_syncache.hashsize - 1;
295 
296 	/* Set limits. */
297 	V_tcp_syncache.cache_limit =
298 	    V_tcp_syncache.hashsize * V_tcp_syncache.bucket_limit;
299 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
300 	    &V_tcp_syncache.cache_limit);
301 
302 	/* Allocate the hash table. */
303 	MALLOC(V_tcp_syncache.hashbase, struct syncache_head *,
304 	    V_tcp_syncache.hashsize * sizeof(struct syncache_head),
305 	    M_SYNCACHE, M_WAITOK | M_ZERO);
306 
307 	/* Initialize the hash buckets. */
308 	for (i = 0; i < V_tcp_syncache.hashsize; i++) {
309 		TAILQ_INIT(&V_tcp_syncache.hashbase[i].sch_bucket);
310 		mtx_init(&V_tcp_syncache.hashbase[i].sch_mtx, "tcp_sc_head",
311 			 NULL, MTX_DEF);
312 		callout_init_mtx(&V_tcp_syncache.hashbase[i].sch_timer,
313 			 &V_tcp_syncache.hashbase[i].sch_mtx, 0);
314 		V_tcp_syncache.hashbase[i].sch_length = 0;
315 	}
316 
317 	/* Create the syncache entry zone. */
318 	V_tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
319 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
320 	uma_zone_set_max(V_tcp_syncache.zone, V_tcp_syncache.cache_limit);
321 }
322 
323 /*
324  * Inserts a syncache entry into the specified bucket row.
325  * Locks and unlocks the syncache_head autonomously.
326  */
327 static void
328 syncache_insert(struct syncache *sc, struct syncache_head *sch)
329 {
330 	struct syncache *sc2;
331 
332 	SCH_LOCK(sch);
333 
334 	/*
335 	 * Make sure that we don't overflow the per-bucket limit.
336 	 * If the bucket is full, toss the oldest element.
337 	 */
338 	if (sch->sch_length >= V_tcp_syncache.bucket_limit) {
339 		KASSERT(!TAILQ_EMPTY(&sch->sch_bucket),
340 			("sch->sch_length incorrect"));
341 		sc2 = TAILQ_LAST(&sch->sch_bucket, sch_head);
342 		syncache_drop(sc2, sch);
343 		V_tcpstat.tcps_sc_bucketoverflow++;
344 	}
345 
346 	/* Put it into the bucket. */
347 	TAILQ_INSERT_HEAD(&sch->sch_bucket, sc, sc_hash);
348 	sch->sch_length++;
349 
350 	/* Reinitialize the bucket row's timer. */
351 	if (sch->sch_length == 1)
352 		sch->sch_nextc = ticks + INT_MAX;
353 	syncache_timeout(sc, sch, 1);
354 
355 	SCH_UNLOCK(sch);
356 
357 	V_tcp_syncache.cache_count++;
358 	V_tcpstat.tcps_sc_added++;
359 }
360 
361 /*
362  * Remove and free entry from syncache bucket row.
363  * Expects locked syncache head.
364  */
365 static void
366 syncache_drop(struct syncache *sc, struct syncache_head *sch)
367 {
368 
369 	SCH_LOCK_ASSERT(sch);
370 
371 	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
372 	sch->sch_length--;
373 
374 #ifndef TCP_OFFLOAD_DISABLE
375 	if (sc->sc_tu)
376 		sc->sc_tu->tu_syncache_event(TOE_SC_DROP, sc->sc_toepcb);
377 #endif
378 	syncache_free(sc);
379 	V_tcp_syncache.cache_count--;
380 }
381 
382 /*
383  * Engage/reengage time on bucket row.
384  */
385 static void
386 syncache_timeout(struct syncache *sc, struct syncache_head *sch, int docallout)
387 {
388 	sc->sc_rxttime = ticks +
389 		TCPTV_RTOBASE * (tcp_backoff[sc->sc_rxmits]);
390 	sc->sc_rxmits++;
391 	if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc)) {
392 		sch->sch_nextc = sc->sc_rxttime;
393 		if (docallout)
394 			callout_reset(&sch->sch_timer, sch->sch_nextc - ticks,
395 			    syncache_timer, (void *)sch);
396 	}
397 }
398 
399 /*
400  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
401  * If we have retransmitted an entry the maximum number of times, expire it.
402  * One separate timer for each bucket row.
403  */
404 static void
405 syncache_timer(void *xsch)
406 {
407 	struct syncache_head *sch = (struct syncache_head *)xsch;
408 	struct syncache *sc, *nsc;
409 	int tick = ticks;
410 	char *s;
411 
412 	/* NB: syncache_head has already been locked by the callout. */
413 	SCH_LOCK_ASSERT(sch);
414 
415 	/*
416 	 * In the following cycle we may remove some entries and/or
417 	 * advance some timeouts, so re-initialize the bucket timer.
418 	 */
419 	sch->sch_nextc = tick + INT_MAX;
420 
421 	TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) {
422 		/*
423 		 * We do not check if the listen socket still exists
424 		 * and accept the case where the listen socket may be
425 		 * gone by the time we resend the SYN/ACK.  We do
426 		 * not expect this to happens often. If it does,
427 		 * then the RST will be sent by the time the remote
428 		 * host does the SYN/ACK->ACK.
429 		 */
430 		if (TSTMP_GT(sc->sc_rxttime, tick)) {
431 			if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc))
432 				sch->sch_nextc = sc->sc_rxttime;
433 			continue;
434 		}
435 		if (sc->sc_rxmits > V_tcp_syncache.rexmt_limit) {
436 			if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
437 				log(LOG_DEBUG, "%s; %s: Retransmits exhausted, "
438 				    "giving up and removing syncache entry\n",
439 				    s, __func__);
440 				free(s, M_TCPLOG);
441 			}
442 			syncache_drop(sc, sch);
443 			V_tcpstat.tcps_sc_stale++;
444 			continue;
445 		}
446 		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
447 			log(LOG_DEBUG, "%s; %s: Response timeout, "
448 			    "retransmitting (%u) SYN|ACK\n",
449 			    s, __func__, sc->sc_rxmits);
450 			free(s, M_TCPLOG);
451 		}
452 
453 		(void) syncache_respond(sc);
454 		V_tcpstat.tcps_sc_retransmitted++;
455 		syncache_timeout(sc, sch, 0);
456 	}
457 	if (!TAILQ_EMPTY(&(sch)->sch_bucket))
458 		callout_reset(&(sch)->sch_timer, (sch)->sch_nextc - tick,
459 			syncache_timer, (void *)(sch));
460 }
461 
462 /*
463  * Find an entry in the syncache.
464  * Returns always with locked syncache_head plus a matching entry or NULL.
465  */
466 struct syncache *
467 syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
468 {
469 	struct syncache *sc;
470 	struct syncache_head *sch;
471 
472 #ifdef INET6
473 	if (inc->inc_isipv6) {
474 		sch = &V_tcp_syncache.hashbase[
475 		    SYNCACHE_HASH6(inc, V_tcp_syncache.hashmask)];
476 		*schp = sch;
477 
478 		SCH_LOCK(sch);
479 
480 		/* Circle through bucket row to find matching entry. */
481 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
482 			if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
483 				return (sc);
484 		}
485 	} else
486 #endif
487 	{
488 		sch = &V_tcp_syncache.hashbase[
489 		    SYNCACHE_HASH(inc, V_tcp_syncache.hashmask)];
490 		*schp = sch;
491 
492 		SCH_LOCK(sch);
493 
494 		/* Circle through bucket row to find matching entry. */
495 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
496 #ifdef INET6
497 			if (sc->sc_inc.inc_isipv6)
498 				continue;
499 #endif
500 			if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
501 				return (sc);
502 		}
503 	}
504 	SCH_LOCK_ASSERT(*schp);
505 	return (NULL);			/* always returns with locked sch */
506 }
507 
508 /*
509  * This function is called when we get a RST for a
510  * non-existent connection, so that we can see if the
511  * connection is in the syn cache.  If it is, zap it.
512  */
513 void
514 syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th)
515 {
516 	struct syncache *sc;
517 	struct syncache_head *sch;
518 	char *s = NULL;
519 
520 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
521 	SCH_LOCK_ASSERT(sch);
522 
523 	/*
524 	 * Any RST to our SYN|ACK must not carry ACK, SYN or FIN flags.
525 	 * See RFC 793 page 65, section SEGMENT ARRIVES.
526 	 */
527 	if (th->th_flags & (TH_ACK|TH_SYN|TH_FIN)) {
528 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
529 			log(LOG_DEBUG, "%s; %s: Spurious RST with ACK, SYN or "
530 			    "FIN flag set, segment ignored\n", s, __func__);
531 		V_tcpstat.tcps_badrst++;
532 		goto done;
533 	}
534 
535 	/*
536 	 * No corresponding connection was found in syncache.
537 	 * If syncookies are enabled and possibly exclusively
538 	 * used, or we are under memory pressure, a valid RST
539 	 * may not find a syncache entry.  In that case we're
540 	 * done and no SYN|ACK retransmissions will happen.
541 	 * Otherwise the the RST was misdirected or spoofed.
542 	 */
543 	if (sc == NULL) {
544 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
545 			log(LOG_DEBUG, "%s; %s: Spurious RST without matching "
546 			    "syncache entry (possibly syncookie only), "
547 			    "segment ignored\n", s, __func__);
548 		V_tcpstat.tcps_badrst++;
549 		goto done;
550 	}
551 
552 	/*
553 	 * If the RST bit is set, check the sequence number to see
554 	 * if this is a valid reset segment.
555 	 * RFC 793 page 37:
556 	 *   In all states except SYN-SENT, all reset (RST) segments
557 	 *   are validated by checking their SEQ-fields.  A reset is
558 	 *   valid if its sequence number is in the window.
559 	 *
560 	 *   The sequence number in the reset segment is normally an
561 	 *   echo of our outgoing acknowlegement numbers, but some hosts
562 	 *   send a reset with the sequence number at the rightmost edge
563 	 *   of our receive window, and we have to handle this case.
564 	 */
565 	if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
566 	    SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
567 		syncache_drop(sc, sch);
568 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
569 			log(LOG_DEBUG, "%s; %s: Our SYN|ACK was rejected, "
570 			    "connection attempt aborted by remote endpoint\n",
571 			    s, __func__);
572 		V_tcpstat.tcps_sc_reset++;
573 	} else {
574 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
575 			log(LOG_DEBUG, "%s; %s: RST with invalid SEQ %u != "
576 			    "IRS %u (+WND %u), segment ignored\n",
577 			    s, __func__, th->th_seq, sc->sc_irs, sc->sc_wnd);
578 		V_tcpstat.tcps_badrst++;
579 	}
580 
581 done:
582 	if (s != NULL)
583 		free(s, M_TCPLOG);
584 	SCH_UNLOCK(sch);
585 }
586 
587 void
588 syncache_badack(struct in_conninfo *inc)
589 {
590 	struct syncache *sc;
591 	struct syncache_head *sch;
592 
593 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
594 	SCH_LOCK_ASSERT(sch);
595 	if (sc != NULL) {
596 		syncache_drop(sc, sch);
597 		V_tcpstat.tcps_sc_badack++;
598 	}
599 	SCH_UNLOCK(sch);
600 }
601 
602 void
603 syncache_unreach(struct in_conninfo *inc, struct tcphdr *th)
604 {
605 	struct syncache *sc;
606 	struct syncache_head *sch;
607 
608 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
609 	SCH_LOCK_ASSERT(sch);
610 	if (sc == NULL)
611 		goto done;
612 
613 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
614 	if (ntohl(th->th_seq) != sc->sc_iss)
615 		goto done;
616 
617 	/*
618 	 * If we've rertransmitted 3 times and this is our second error,
619 	 * we remove the entry.  Otherwise, we allow it to continue on.
620 	 * This prevents us from incorrectly nuking an entry during a
621 	 * spurious network outage.
622 	 *
623 	 * See tcp_notify().
624 	 */
625 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxmits < 3 + 1) {
626 		sc->sc_flags |= SCF_UNREACH;
627 		goto done;
628 	}
629 	syncache_drop(sc, sch);
630 	V_tcpstat.tcps_sc_unreach++;
631 done:
632 	SCH_UNLOCK(sch);
633 }
634 
635 /*
636  * Build a new TCP socket structure from a syncache entry.
637  */
638 static struct socket *
639 syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m)
640 {
641 	struct inpcb *inp = NULL;
642 	struct socket *so;
643 	struct tcpcb *tp;
644 	char *s;
645 
646 	INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
647 
648 	/*
649 	 * Ok, create the full blown connection, and set things up
650 	 * as they would have been set up if we had created the
651 	 * connection when the SYN arrived.  If we can't create
652 	 * the connection, abort it.
653 	 */
654 	so = sonewconn(lso, SS_ISCONNECTED);
655 	if (so == NULL) {
656 		/*
657 		 * Drop the connection; we will either send a RST or
658 		 * have the peer retransmit its SYN again after its
659 		 * RTO and try again.
660 		 */
661 		V_tcpstat.tcps_listendrop++;
662 		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
663 			log(LOG_DEBUG, "%s; %s: Socket create failed "
664 			    "due to limits or memory shortage\n",
665 			    s, __func__);
666 			free(s, M_TCPLOG);
667 		}
668 		goto abort2;
669 	}
670 #ifdef MAC
671 	SOCK_LOCK(so);
672 	mac_socketpeer_set_from_mbuf(m, so);
673 	SOCK_UNLOCK(so);
674 #endif
675 
676 	inp = sotoinpcb(so);
677 	inp->inp_inc.inc_fibnum = sc->sc_inc.inc_fibnum;
678 	so->so_fibnum = sc->sc_inc.inc_fibnum;
679 	INP_WLOCK(inp);
680 
681 	/* Insert new socket into PCB hash list. */
682 	inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
683 #ifdef INET6
684 	if (sc->sc_inc.inc_isipv6) {
685 		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
686 	} else {
687 		inp->inp_vflag &= ~INP_IPV6;
688 		inp->inp_vflag |= INP_IPV4;
689 #endif
690 		inp->inp_laddr = sc->sc_inc.inc_laddr;
691 #ifdef INET6
692 	}
693 #endif
694 	inp->inp_lport = sc->sc_inc.inc_lport;
695 	if (in_pcbinshash(inp) != 0) {
696 		/*
697 		 * Undo the assignments above if we failed to
698 		 * put the PCB on the hash lists.
699 		 */
700 #ifdef INET6
701 		if (sc->sc_inc.inc_isipv6)
702 			inp->in6p_laddr = in6addr_any;
703 		else
704 #endif
705 			inp->inp_laddr.s_addr = INADDR_ANY;
706 		inp->inp_lport = 0;
707 		goto abort;
708 	}
709 #ifdef IPSEC
710 	/* Copy old policy into new socket's. */
711 	if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
712 		printf("syncache_socket: could not copy policy\n");
713 #endif
714 #ifdef INET6
715 	if (sc->sc_inc.inc_isipv6) {
716 		struct inpcb *oinp = sotoinpcb(lso);
717 		struct in6_addr laddr6;
718 		struct sockaddr_in6 sin6;
719 		/*
720 		 * Inherit socket options from the listening socket.
721 		 * Note that in6p_inputopts are not (and should not be)
722 		 * copied, since it stores previously received options and is
723 		 * used to detect if each new option is different than the
724 		 * previous one and hence should be passed to a user.
725 		 * If we copied in6p_inputopts, a user would not be able to
726 		 * receive options just after calling the accept system call.
727 		 */
728 		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
729 		if (oinp->in6p_outputopts)
730 			inp->in6p_outputopts =
731 			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
732 
733 		sin6.sin6_family = AF_INET6;
734 		sin6.sin6_len = sizeof(sin6);
735 		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
736 		sin6.sin6_port = sc->sc_inc.inc_fport;
737 		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
738 		laddr6 = inp->in6p_laddr;
739 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
740 			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
741 		if (in6_pcbconnect(inp, (struct sockaddr *)&sin6,
742 		    thread0.td_ucred)) {
743 			inp->in6p_laddr = laddr6;
744 			goto abort;
745 		}
746 		/* Override flowlabel from in6_pcbconnect. */
747 		inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
748 		inp->in6p_flowinfo |= sc->sc_flowlabel;
749 	} else
750 #endif
751 	{
752 		struct in_addr laddr;
753 		struct sockaddr_in sin;
754 
755 		inp->inp_options = (m) ? ip_srcroute(m) : NULL;
756 
757 		if (inp->inp_options == NULL) {
758 			inp->inp_options = sc->sc_ipopts;
759 			sc->sc_ipopts = NULL;
760 		}
761 
762 		sin.sin_family = AF_INET;
763 		sin.sin_len = sizeof(sin);
764 		sin.sin_addr = sc->sc_inc.inc_faddr;
765 		sin.sin_port = sc->sc_inc.inc_fport;
766 		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
767 		laddr = inp->inp_laddr;
768 		if (inp->inp_laddr.s_addr == INADDR_ANY)
769 			inp->inp_laddr = sc->sc_inc.inc_laddr;
770 		if (in_pcbconnect(inp, (struct sockaddr *)&sin,
771 		    thread0.td_ucred)) {
772 			inp->inp_laddr = laddr;
773 			goto abort;
774 		}
775 	}
776 	tp = intotcpcb(inp);
777 	tp->t_state = TCPS_SYN_RECEIVED;
778 	tp->iss = sc->sc_iss;
779 	tp->irs = sc->sc_irs;
780 	tcp_rcvseqinit(tp);
781 	tcp_sendseqinit(tp);
782 	tp->snd_wl1 = sc->sc_irs;
783 	tp->snd_max = tp->iss + 1;
784 	tp->snd_nxt = tp->iss + 1;
785 	tp->rcv_up = sc->sc_irs + 1;
786 	tp->rcv_wnd = sc->sc_wnd;
787 	tp->rcv_adv += tp->rcv_wnd;
788 	tp->last_ack_sent = tp->rcv_nxt;
789 
790 	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
791 	if (sc->sc_flags & SCF_NOOPT)
792 		tp->t_flags |= TF_NOOPT;
793 	else {
794 		if (sc->sc_flags & SCF_WINSCALE) {
795 			tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
796 			tp->snd_scale = sc->sc_requested_s_scale;
797 			tp->request_r_scale = sc->sc_requested_r_scale;
798 		}
799 		if (sc->sc_flags & SCF_TIMESTAMP) {
800 			tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
801 			tp->ts_recent = sc->sc_tsreflect;
802 			tp->ts_recent_age = ticks;
803 			tp->ts_offset = sc->sc_tsoff;
804 		}
805 #ifdef TCP_SIGNATURE
806 		if (sc->sc_flags & SCF_SIGNATURE)
807 			tp->t_flags |= TF_SIGNATURE;
808 #endif
809 		if (sc->sc_flags & SCF_SACK)
810 			tp->t_flags |= TF_SACK_PERMIT;
811 	}
812 
813 	if (sc->sc_flags & SCF_ECN)
814 		tp->t_flags |= TF_ECN_PERMIT;
815 
816 	/*
817 	 * Set up MSS and get cached values from tcp_hostcache.
818 	 * This might overwrite some of the defaults we just set.
819 	 */
820 	tcp_mss(tp, sc->sc_peer_mss);
821 
822 	/*
823 	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
824 	 */
825 	if (sc->sc_rxmits)
826 		tp->snd_cwnd = tp->t_maxseg;
827 	tcp_timer_activate(tp, TT_KEEP, tcp_keepinit);
828 
829 	INP_WUNLOCK(inp);
830 
831 	V_tcpstat.tcps_accepts++;
832 	return (so);
833 
834 abort:
835 	INP_WUNLOCK(inp);
836 abort2:
837 	if (so != NULL)
838 		soabort(so);
839 	return (NULL);
840 }
841 
842 /*
843  * This function gets called when we receive an ACK for a
844  * socket in the LISTEN state.  We look up the connection
845  * in the syncache, and if its there, we pull it out of
846  * the cache and turn it into a full-blown connection in
847  * the SYN-RECEIVED state.
848  */
849 int
850 syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
851     struct socket **lsop, struct mbuf *m)
852 {
853 	struct syncache *sc;
854 	struct syncache_head *sch;
855 	struct syncache scs;
856 	char *s;
857 
858 	/*
859 	 * Global TCP locks are held because we manipulate the PCB lists
860 	 * and create a new socket.
861 	 */
862 	INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
863 	KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK,
864 	    ("%s: can handle only ACK", __func__));
865 
866 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
867 	SCH_LOCK_ASSERT(sch);
868 	if (sc == NULL) {
869 		/*
870 		 * There is no syncache entry, so see if this ACK is
871 		 * a returning syncookie.  To do this, first:
872 		 *  A. See if this socket has had a syncache entry dropped in
873 		 *     the past.  We don't want to accept a bogus syncookie
874 		 *     if we've never received a SYN.
875 		 *  B. check that the syncookie is valid.  If it is, then
876 		 *     cobble up a fake syncache entry, and return.
877 		 */
878 		if (!tcp_syncookies) {
879 			SCH_UNLOCK(sch);
880 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
881 				log(LOG_DEBUG, "%s; %s: Spurious ACK, "
882 				    "segment rejected (syncookies disabled)\n",
883 				    s, __func__);
884 			goto failed;
885 		}
886 		bzero(&scs, sizeof(scs));
887 		sc = syncookie_lookup(inc, sch, &scs, to, th, *lsop);
888 		SCH_UNLOCK(sch);
889 		if (sc == NULL) {
890 			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
891 				log(LOG_DEBUG, "%s; %s: Segment failed "
892 				    "SYNCOOKIE authentication, segment rejected "
893 				    "(probably spoofed)\n", s, __func__);
894 			goto failed;
895 		}
896 	} else {
897 		/* Pull out the entry to unlock the bucket row. */
898 		TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
899 		sch->sch_length--;
900 		V_tcp_syncache.cache_count--;
901 		SCH_UNLOCK(sch);
902 	}
903 
904 	/*
905 	 * Segment validation:
906 	 * ACK must match our initial sequence number + 1 (the SYN|ACK).
907 	 */
908 	if (th->th_ack != sc->sc_iss + 1 && !TOEPCB_ISSET(sc)) {
909 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
910 			log(LOG_DEBUG, "%s; %s: ACK %u != ISS+1 %u, segment "
911 			    "rejected\n", s, __func__, th->th_ack, sc->sc_iss);
912 		goto failed;
913 	}
914 
915 	/*
916 	 * The SEQ must fall in the window starting at the received
917 	 * initial receive sequence number + 1 (the SYN).
918 	 */
919 	if ((SEQ_LEQ(th->th_seq, sc->sc_irs) ||
920 	    SEQ_GT(th->th_seq, sc->sc_irs + sc->sc_wnd)) &&
921 	    !TOEPCB_ISSET(sc)) {
922 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
923 			log(LOG_DEBUG, "%s; %s: SEQ %u != IRS+1 %u, segment "
924 			    "rejected\n", s, __func__, th->th_seq, sc->sc_irs);
925 		goto failed;
926 	}
927 
928 	if (!(sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS)) {
929 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
930 			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
931 			    "segment rejected\n", s, __func__);
932 		goto failed;
933 	}
934 	/*
935 	 * If timestamps were negotiated the reflected timestamp
936 	 * must be equal to what we actually sent in the SYN|ACK.
937 	 */
938 	if ((to->to_flags & TOF_TS) && to->to_tsecr != sc->sc_ts &&
939 	    !TOEPCB_ISSET(sc)) {
940 		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
941 			log(LOG_DEBUG, "%s; %s: TSECR %u != TS %u, "
942 			    "segment rejected\n",
943 			    s, __func__, to->to_tsecr, sc->sc_ts);
944 		goto failed;
945 	}
946 
947 	*lsop = syncache_socket(sc, *lsop, m);
948 
949 	if (*lsop == NULL)
950 		V_tcpstat.tcps_sc_aborted++;
951 	else
952 		V_tcpstat.tcps_sc_completed++;
953 
954 /* how do we find the inp for the new socket? */
955 	if (sc != &scs)
956 		syncache_free(sc);
957 	return (1);
958 failed:
959 	if (sc != NULL && sc != &scs)
960 		syncache_free(sc);
961 	if (s != NULL)
962 		free(s, M_TCPLOG);
963 	*lsop = NULL;
964 	return (0);
965 }
966 
967 int
968 tcp_offload_syncache_expand(struct in_conninfo *inc, struct tcpopt *to,
969     struct tcphdr *th, struct socket **lsop, struct mbuf *m)
970 {
971 	int rc;
972 
973 	INP_INFO_WLOCK(&V_tcbinfo);
974 	rc = syncache_expand(inc, to, th, lsop, m);
975 	INP_INFO_WUNLOCK(&V_tcbinfo);
976 
977 	return (rc);
978 }
979 
980 /*
981  * Given a LISTEN socket and an inbound SYN request, add
982  * this to the syn cache, and send back a segment:
983  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
984  * to the source.
985  *
986  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
987  * Doing so would require that we hold onto the data and deliver it
988  * to the application.  However, if we are the target of a SYN-flood
989  * DoS attack, an attacker could send data which would eventually
990  * consume all available buffer space if it were ACKed.  By not ACKing
991  * the data, we avoid this DoS scenario.
992  */
993 static void
994 _syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
995     struct inpcb *inp, struct socket **lsop, struct mbuf *m,
996     struct toe_usrreqs *tu, void *toepcb)
997 {
998 	struct tcpcb *tp;
999 	struct socket *so;
1000 	struct syncache *sc = NULL;
1001 	struct syncache_head *sch;
1002 	struct mbuf *ipopts = NULL;
1003 	u_int32_t flowtmp;
1004 	int win, sb_hiwat, ip_ttl, ip_tos, noopt;
1005 	char *s;
1006 #ifdef INET6
1007 	int autoflowlabel = 0;
1008 #endif
1009 #ifdef MAC
1010 	struct label *maclabel;
1011 #endif
1012 	struct syncache scs;
1013 
1014 	INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1015 	INP_WLOCK_ASSERT(inp);			/* listen socket */
1016 	KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN,
1017 	    ("%s: unexpected tcp flags", __func__));
1018 
1019 	/*
1020 	 * Combine all so/tp operations very early to drop the INP lock as
1021 	 * soon as possible.
1022 	 */
1023 	so = *lsop;
1024 	tp = sototcpcb(so);
1025 
1026 #ifdef INET6
1027 	if (inc->inc_isipv6 &&
1028 	    (inp->in6p_flags & IN6P_AUTOFLOWLABEL))
1029 		autoflowlabel = 1;
1030 #endif
1031 	ip_ttl = inp->inp_ip_ttl;
1032 	ip_tos = inp->inp_ip_tos;
1033 	win = sbspace(&so->so_rcv);
1034 	sb_hiwat = so->so_rcv.sb_hiwat;
1035 	noopt = (tp->t_flags & TF_NOOPT);
1036 
1037 	so = NULL;
1038 	tp = NULL;
1039 
1040 #ifdef MAC
1041 	if (mac_syncache_init(&maclabel) != 0) {
1042 		INP_WUNLOCK(inp);
1043 		INP_INFO_WUNLOCK(&V_tcbinfo);
1044 		goto done;
1045 	} else
1046 		mac_syncache_create(maclabel, inp);
1047 #endif
1048 	INP_WUNLOCK(inp);
1049 	INP_INFO_WUNLOCK(&V_tcbinfo);
1050 
1051 	/*
1052 	 * Remember the IP options, if any.
1053 	 */
1054 #ifdef INET6
1055 	if (!inc->inc_isipv6)
1056 #endif
1057 		ipopts = (m) ? ip_srcroute(m) : NULL;
1058 
1059 	/*
1060 	 * See if we already have an entry for this connection.
1061 	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
1062 	 *
1063 	 * XXX: should the syncache be re-initialized with the contents
1064 	 * of the new SYN here (which may have different options?)
1065 	 *
1066 	 * XXX: We do not check the sequence number to see if this is a
1067 	 * real retransmit or a new connection attempt.  The question is
1068 	 * how to handle such a case; either ignore it as spoofed, or
1069 	 * drop the current entry and create a new one?
1070 	 */
1071 	sc = syncache_lookup(inc, &sch);	/* returns locked entry */
1072 	SCH_LOCK_ASSERT(sch);
1073 	if (sc != NULL) {
1074 #ifndef TCP_OFFLOAD_DISABLE
1075 		if (sc->sc_tu)
1076 			sc->sc_tu->tu_syncache_event(TOE_SC_ENTRY_PRESENT,
1077 			    sc->sc_toepcb);
1078 #endif
1079 		V_tcpstat.tcps_sc_dupsyn++;
1080 		if (ipopts) {
1081 			/*
1082 			 * If we were remembering a previous source route,
1083 			 * forget it and use the new one we've been given.
1084 			 */
1085 			if (sc->sc_ipopts)
1086 				(void) m_free(sc->sc_ipopts);
1087 			sc->sc_ipopts = ipopts;
1088 		}
1089 		/*
1090 		 * Update timestamp if present.
1091 		 */
1092 		if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS))
1093 			sc->sc_tsreflect = to->to_tsval;
1094 		else
1095 			sc->sc_flags &= ~SCF_TIMESTAMP;
1096 #ifdef MAC
1097 		/*
1098 		 * Since we have already unconditionally allocated label
1099 		 * storage, free it up.  The syncache entry will already
1100 		 * have an initialized label we can use.
1101 		 */
1102 		mac_syncache_destroy(&maclabel);
1103 		KASSERT(sc->sc_label != NULL,
1104 		    ("%s: label not initialized", __func__));
1105 #endif
1106 		/* Retransmit SYN|ACK and reset retransmit count. */
1107 		if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) {
1108 			log(LOG_DEBUG, "%s; %s: Received duplicate SYN, "
1109 			    "resetting timer and retransmitting SYN|ACK\n",
1110 			    s, __func__);
1111 			free(s, M_TCPLOG);
1112 		}
1113 		if (!TOEPCB_ISSET(sc) && syncache_respond(sc) == 0) {
1114 			sc->sc_rxmits = 0;
1115 			syncache_timeout(sc, sch, 1);
1116 			V_tcpstat.tcps_sndacks++;
1117 			V_tcpstat.tcps_sndtotal++;
1118 		}
1119 		SCH_UNLOCK(sch);
1120 		goto done;
1121 	}
1122 
1123 	sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1124 	if (sc == NULL) {
1125 		/*
1126 		 * The zone allocator couldn't provide more entries.
1127 		 * Treat this as if the cache was full; drop the oldest
1128 		 * entry and insert the new one.
1129 		 */
1130 		V_tcpstat.tcps_sc_zonefail++;
1131 		if ((sc = TAILQ_LAST(&sch->sch_bucket, sch_head)) != NULL)
1132 			syncache_drop(sc, sch);
1133 		sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1134 		if (sc == NULL) {
1135 			if (tcp_syncookies) {
1136 				bzero(&scs, sizeof(scs));
1137 				sc = &scs;
1138 			} else {
1139 				SCH_UNLOCK(sch);
1140 				if (ipopts)
1141 					(void) m_free(ipopts);
1142 				goto done;
1143 			}
1144 		}
1145 	}
1146 
1147 	/*
1148 	 * Fill in the syncache values.
1149 	 */
1150 #ifdef MAC
1151 	sc->sc_label = maclabel;
1152 #endif
1153 	sc->sc_ipopts = ipopts;
1154 	sc->sc_inc.inc_fibnum = inp->inp_inc.inc_fibnum;
1155 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1156 #ifdef INET6
1157 	if (!inc->inc_isipv6)
1158 #endif
1159 	{
1160 		sc->sc_ip_tos = ip_tos;
1161 		sc->sc_ip_ttl = ip_ttl;
1162 	}
1163 #ifndef TCP_OFFLOAD_DISABLE
1164 	sc->sc_tu = tu;
1165 	sc->sc_toepcb = toepcb;
1166 #endif
1167 	sc->sc_irs = th->th_seq;
1168 	sc->sc_iss = arc4random();
1169 	sc->sc_flags = 0;
1170 	sc->sc_flowlabel = 0;
1171 
1172 	/*
1173 	 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
1174 	 * win was derived from socket earlier in the function.
1175 	 */
1176 	win = imax(win, 0);
1177 	win = imin(win, TCP_MAXWIN);
1178 	sc->sc_wnd = win;
1179 
1180 	if (V_tcp_do_rfc1323) {
1181 		/*
1182 		 * A timestamp received in a SYN makes
1183 		 * it ok to send timestamp requests and replies.
1184 		 */
1185 		if (to->to_flags & TOF_TS) {
1186 			sc->sc_tsreflect = to->to_tsval;
1187 			sc->sc_ts = ticks;
1188 			sc->sc_flags |= SCF_TIMESTAMP;
1189 		}
1190 		if (to->to_flags & TOF_SCALE) {
1191 			int wscale = 0;
1192 
1193 			/*
1194 			 * Pick the smallest possible scaling factor that
1195 			 * will still allow us to scale up to sb_max, aka
1196 			 * kern.ipc.maxsockbuf.
1197 			 *
1198 			 * We do this because there are broken firewalls that
1199 			 * will corrupt the window scale option, leading to
1200 			 * the other endpoint believing that our advertised
1201 			 * window is unscaled.  At scale factors larger than
1202 			 * 5 the unscaled window will drop below 1500 bytes,
1203 			 * leading to serious problems when traversing these
1204 			 * broken firewalls.
1205 			 *
1206 			 * With the default maxsockbuf of 256K, a scale factor
1207 			 * of 3 will be chosen by this algorithm.  Those who
1208 			 * choose a larger maxsockbuf should watch out
1209 			 * for the compatiblity problems mentioned above.
1210 			 *
1211 			 * RFC1323: The Window field in a SYN (i.e., a <SYN>
1212 			 * or <SYN,ACK>) segment itself is never scaled.
1213 			 */
1214 			while (wscale < TCP_MAX_WINSHIFT &&
1215 			    (TCP_MAXWIN << wscale) < sb_max)
1216 				wscale++;
1217 			sc->sc_requested_r_scale = wscale;
1218 			sc->sc_requested_s_scale = to->to_wscale;
1219 			sc->sc_flags |= SCF_WINSCALE;
1220 		}
1221 	}
1222 #ifdef TCP_SIGNATURE
1223 	/*
1224 	 * If listening socket requested TCP digests, and received SYN
1225 	 * contains the option, flag this in the syncache so that
1226 	 * syncache_respond() will do the right thing with the SYN+ACK.
1227 	 * XXX: Currently we always record the option by default and will
1228 	 * attempt to use it in syncache_respond().
1229 	 */
1230 	if (to->to_flags & TOF_SIGNATURE)
1231 		sc->sc_flags |= SCF_SIGNATURE;
1232 #endif
1233 	if (to->to_flags & TOF_SACKPERM)
1234 		sc->sc_flags |= SCF_SACK;
1235 	if (to->to_flags & TOF_MSS)
1236 		sc->sc_peer_mss = to->to_mss;	/* peer mss may be zero */
1237 	if (noopt)
1238 		sc->sc_flags |= SCF_NOOPT;
1239 	if ((th->th_flags & (TH_ECE|TH_CWR)) && V_tcp_do_ecn)
1240 		sc->sc_flags |= SCF_ECN;
1241 
1242 	if (tcp_syncookies) {
1243 		syncookie_generate(sch, sc, &flowtmp);
1244 #ifdef INET6
1245 		if (autoflowlabel)
1246 			sc->sc_flowlabel = flowtmp;
1247 #endif
1248 	} else {
1249 #ifdef INET6
1250 		if (autoflowlabel)
1251 			sc->sc_flowlabel =
1252 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1253 #endif
1254 	}
1255 	SCH_UNLOCK(sch);
1256 
1257 	/*
1258 	 * Do a standard 3-way handshake.
1259 	 */
1260 	if (TOEPCB_ISSET(sc) || syncache_respond(sc) == 0) {
1261 		if (tcp_syncookies && tcp_syncookiesonly && sc != &scs)
1262 			syncache_free(sc);
1263 		else if (sc != &scs)
1264 			syncache_insert(sc, sch);   /* locks and unlocks sch */
1265 		V_tcpstat.tcps_sndacks++;
1266 		V_tcpstat.tcps_sndtotal++;
1267 	} else {
1268 		if (sc != &scs)
1269 			syncache_free(sc);
1270 		V_tcpstat.tcps_sc_dropped++;
1271 	}
1272 
1273 done:
1274 #ifdef MAC
1275 	if (sc == &scs)
1276 		mac_syncache_destroy(&maclabel);
1277 #endif
1278 	if (m) {
1279 
1280 		*lsop = NULL;
1281 		m_freem(m);
1282 	}
1283 	return;
1284 }
1285 
1286 static int
1287 syncache_respond(struct syncache *sc)
1288 {
1289 	struct ip *ip = NULL;
1290 	struct mbuf *m;
1291 	struct tcphdr *th;
1292 	int optlen, error;
1293 	u_int16_t hlen, tlen, mssopt;
1294 	struct tcpopt to;
1295 #ifdef INET6
1296 	struct ip6_hdr *ip6 = NULL;
1297 #endif
1298 
1299 	hlen =
1300 #ifdef INET6
1301 	       (sc->sc_inc.inc_isipv6) ? sizeof(struct ip6_hdr) :
1302 #endif
1303 		sizeof(struct ip);
1304 	tlen = hlen + sizeof(struct tcphdr);
1305 
1306 	/* Determine MSS we advertize to other end of connection. */
1307 	mssopt = tcp_mssopt(&sc->sc_inc);
1308 	if (sc->sc_peer_mss)
1309 		mssopt = max( min(sc->sc_peer_mss, mssopt), V_tcp_minmss);
1310 
1311 	/* XXX: Assume that the entire packet will fit in a header mbuf. */
1312 	KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN,
1313 	    ("syncache: mbuf too small"));
1314 
1315 	/* Create the IP+TCP header from scratch. */
1316 	m = m_gethdr(M_DONTWAIT, MT_DATA);
1317 	if (m == NULL)
1318 		return (ENOBUFS);
1319 #ifdef MAC
1320 	mac_syncache_create_mbuf(sc->sc_label, m);
1321 #endif
1322 	m->m_data += max_linkhdr;
1323 	m->m_len = tlen;
1324 	m->m_pkthdr.len = tlen;
1325 	m->m_pkthdr.rcvif = NULL;
1326 
1327 #ifdef INET6
1328 	if (sc->sc_inc.inc_isipv6) {
1329 		ip6 = mtod(m, struct ip6_hdr *);
1330 		ip6->ip6_vfc = IPV6_VERSION;
1331 		ip6->ip6_nxt = IPPROTO_TCP;
1332 		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1333 		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1334 		ip6->ip6_plen = htons(tlen - hlen);
1335 		/* ip6_hlim is set after checksum */
1336 		ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
1337 		ip6->ip6_flow |= sc->sc_flowlabel;
1338 
1339 		th = (struct tcphdr *)(ip6 + 1);
1340 	} else
1341 #endif
1342 	{
1343 		ip = mtod(m, struct ip *);
1344 		ip->ip_v = IPVERSION;
1345 		ip->ip_hl = sizeof(struct ip) >> 2;
1346 		ip->ip_len = tlen;
1347 		ip->ip_id = 0;
1348 		ip->ip_off = 0;
1349 		ip->ip_sum = 0;
1350 		ip->ip_p = IPPROTO_TCP;
1351 		ip->ip_src = sc->sc_inc.inc_laddr;
1352 		ip->ip_dst = sc->sc_inc.inc_faddr;
1353 		ip->ip_ttl = sc->sc_ip_ttl;
1354 		ip->ip_tos = sc->sc_ip_tos;
1355 
1356 		/*
1357 		 * See if we should do MTU discovery.  Route lookups are
1358 		 * expensive, so we will only unset the DF bit if:
1359 		 *
1360 		 *	1) path_mtu_discovery is disabled
1361 		 *	2) the SCF_UNREACH flag has been set
1362 		 */
1363 		if (V_path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1364 		       ip->ip_off |= IP_DF;
1365 
1366 		th = (struct tcphdr *)(ip + 1);
1367 	}
1368 	th->th_sport = sc->sc_inc.inc_lport;
1369 	th->th_dport = sc->sc_inc.inc_fport;
1370 
1371 	th->th_seq = htonl(sc->sc_iss);
1372 	th->th_ack = htonl(sc->sc_irs + 1);
1373 	th->th_off = sizeof(struct tcphdr) >> 2;
1374 	th->th_x2 = 0;
1375 	th->th_flags = TH_SYN|TH_ACK;
1376 	th->th_win = htons(sc->sc_wnd);
1377 	th->th_urp = 0;
1378 
1379 	if (sc->sc_flags & SCF_ECN) {
1380 		th->th_flags |= TH_ECE;
1381 		V_tcpstat.tcps_ecn_shs++;
1382 	}
1383 
1384 	/* Tack on the TCP options. */
1385 	if ((sc->sc_flags & SCF_NOOPT) == 0) {
1386 		to.to_flags = 0;
1387 
1388 		to.to_mss = mssopt;
1389 		to.to_flags = TOF_MSS;
1390 		if (sc->sc_flags & SCF_WINSCALE) {
1391 			to.to_wscale = sc->sc_requested_r_scale;
1392 			to.to_flags |= TOF_SCALE;
1393 		}
1394 		if (sc->sc_flags & SCF_TIMESTAMP) {
1395 			/* Virgin timestamp or TCP cookie enhanced one. */
1396 			to.to_tsval = sc->sc_ts;
1397 			to.to_tsecr = sc->sc_tsreflect;
1398 			to.to_flags |= TOF_TS;
1399 		}
1400 		if (sc->sc_flags & SCF_SACK)
1401 			to.to_flags |= TOF_SACKPERM;
1402 #ifdef TCP_SIGNATURE
1403 		if (sc->sc_flags & SCF_SIGNATURE)
1404 			to.to_flags |= TOF_SIGNATURE;
1405 #endif
1406 		optlen = tcp_addoptions(&to, (u_char *)(th + 1));
1407 
1408 		/* Adjust headers by option size. */
1409 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1410 		m->m_len += optlen;
1411 		m->m_pkthdr.len += optlen;
1412 
1413 #ifdef TCP_SIGNATURE
1414 		if (sc->sc_flags & SCF_SIGNATURE)
1415 			tcp_signature_compute(m, sizeof(struct ip), 0, optlen,
1416 			    to.to_signature, IPSEC_DIR_OUTBOUND);
1417 #endif
1418 #ifdef INET6
1419 		if (sc->sc_inc.inc_isipv6)
1420 			ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen);
1421 		else
1422 #endif
1423 			ip->ip_len += optlen;
1424 	} else
1425 		optlen = 0;
1426 
1427 #ifdef INET6
1428 	if (sc->sc_inc.inc_isipv6) {
1429 		th->th_sum = 0;
1430 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen,
1431 				       tlen + optlen - hlen);
1432 		ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
1433 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1434 	} else
1435 #endif
1436 	{
1437 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1438 		    htons(tlen + optlen - hlen + IPPROTO_TCP));
1439 		m->m_pkthdr.csum_flags = CSUM_TCP;
1440 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1441 		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
1442 	}
1443 	return (error);
1444 }
1445 
1446 void
1447 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1448     struct inpcb *inp, struct socket **lsop, struct mbuf *m)
1449 {
1450 	_syncache_add(inc, to, th, inp, lsop, m, NULL, NULL);
1451 }
1452 
1453 void
1454 tcp_offload_syncache_add(struct in_conninfo *inc, struct tcpopt *to,
1455     struct tcphdr *th, struct inpcb *inp, struct socket **lsop,
1456     struct toe_usrreqs *tu, void *toepcb)
1457 {
1458 
1459 	INP_INFO_WLOCK(&V_tcbinfo);
1460 	INP_WLOCK(inp);
1461 	_syncache_add(inc, to, th, inp, lsop, NULL, tu, toepcb);
1462 }
1463 
1464 /*
1465  * The purpose of SYN cookies is to avoid keeping track of all SYN's we
1466  * receive and to be able to handle SYN floods from bogus source addresses
1467  * (where we will never receive any reply).  SYN floods try to exhaust all
1468  * our memory and available slots in the SYN cache table to cause a denial
1469  * of service to legitimate users of the local host.
1470  *
1471  * The idea of SYN cookies is to encode and include all necessary information
1472  * about the connection setup state within the SYN-ACK we send back and thus
1473  * to get along without keeping any local state until the ACK to the SYN-ACK
1474  * arrives (if ever).  Everything we need to know should be available from
1475  * the information we encoded in the SYN-ACK.
1476  *
1477  * More information about the theory behind SYN cookies and its first
1478  * discussion and specification can be found at:
1479  *  http://cr.yp.to/syncookies.html    (overview)
1480  *  http://cr.yp.to/syncookies/archive (gory details)
1481  *
1482  * This implementation extends the orginal idea and first implementation
1483  * of FreeBSD by using not only the initial sequence number field to store
1484  * information but also the timestamp field if present.  This way we can
1485  * keep track of the entire state we need to know to recreate the session in
1486  * its original form.  Almost all TCP speakers implement RFC1323 timestamps
1487  * these days.  For those that do not we still have to live with the known
1488  * shortcomings of the ISN only SYN cookies.
1489  *
1490  * Cookie layers:
1491  *
1492  * Initial sequence number we send:
1493  * 31|................................|0
1494  *    DDDDDDDDDDDDDDDDDDDDDDDDDMMMRRRP
1495  *    D = MD5 Digest (first dword)
1496  *    M = MSS index
1497  *    R = Rotation of secret
1498  *    P = Odd or Even secret
1499  *
1500  * The MD5 Digest is computed with over following parameters:
1501  *  a) randomly rotated secret
1502  *  b) struct in_conninfo containing the remote/local ip/port (IPv4&IPv6)
1503  *  c) the received initial sequence number from remote host
1504  *  d) the rotation offset and odd/even bit
1505  *
1506  * Timestamp we send:
1507  * 31|................................|0
1508  *    DDDDDDDDDDDDDDDDDDDDDDSSSSRRRRA5
1509  *    D = MD5 Digest (third dword) (only as filler)
1510  *    S = Requested send window scale
1511  *    R = Requested receive window scale
1512  *    A = SACK allowed
1513  *    5 = TCP-MD5 enabled (not implemented yet)
1514  *    XORed with MD5 Digest (forth dword)
1515  *
1516  * The timestamp isn't cryptographically secure and doesn't need to be.
1517  * The double use of the MD5 digest dwords ties it to a specific remote/
1518  * local host/port, remote initial sequence number and our local time
1519  * limited secret.  A received timestamp is reverted (XORed) and then
1520  * the contained MD5 dword is compared to the computed one to ensure the
1521  * timestamp belongs to the SYN-ACK we sent.  The other parameters may
1522  * have been tampered with but this isn't different from supplying bogus
1523  * values in the SYN in the first place.
1524  *
1525  * Some problems with SYN cookies remain however:
1526  * Consider the problem of a recreated (and retransmitted) cookie.  If the
1527  * original SYN was accepted, the connection is established.  The second
1528  * SYN is inflight, and if it arrives with an ISN that falls within the
1529  * receive window, the connection is killed.
1530  *
1531  * Notes:
1532  * A heuristic to determine when to accept syn cookies is not necessary.
1533  * An ACK flood would cause the syncookie verification to be attempted,
1534  * but a SYN flood causes syncookies to be generated.  Both are of equal
1535  * cost, so there's no point in trying to optimize the ACK flood case.
1536  * Also, if you don't process certain ACKs for some reason, then all someone
1537  * would have to do is launch a SYN and ACK flood at the same time, which
1538  * would stop cookie verification and defeat the entire purpose of syncookies.
1539  */
1540 static int tcp_sc_msstab[] = { 0, 256, 468, 536, 996, 1452, 1460, 8960 };
1541 
1542 static void
1543 syncookie_generate(struct syncache_head *sch, struct syncache *sc,
1544     u_int32_t *flowlabel)
1545 {
1546 	MD5_CTX ctx;
1547 	u_int32_t md5_buffer[MD5_DIGEST_LENGTH / sizeof(u_int32_t)];
1548 	u_int32_t data;
1549 	u_int32_t *secbits;
1550 	u_int off, pmss, mss;
1551 	int i;
1552 
1553 	SCH_LOCK_ASSERT(sch);
1554 
1555 	/* Which of the two secrets to use. */
1556 	secbits = sch->sch_oddeven ?
1557 			sch->sch_secbits_odd : sch->sch_secbits_even;
1558 
1559 	/* Reseed secret if too old. */
1560 	if (sch->sch_reseed < time_uptime) {
1561 		sch->sch_oddeven = sch->sch_oddeven ? 0 : 1;	/* toggle */
1562 		secbits = sch->sch_oddeven ?
1563 				sch->sch_secbits_odd : sch->sch_secbits_even;
1564 		for (i = 0; i < SYNCOOKIE_SECRET_SIZE; i++)
1565 			secbits[i] = arc4random();
1566 		sch->sch_reseed = time_uptime + SYNCOOKIE_LIFETIME;
1567 	}
1568 
1569 	/* Secret rotation offset. */
1570 	off = sc->sc_iss & 0x7;			/* iss was randomized before */
1571 
1572 	/* Maximum segment size calculation. */
1573 	pmss =
1574 	    max( min(sc->sc_peer_mss, tcp_mssopt(&sc->sc_inc)),	V_tcp_minmss);
1575 	for (mss = sizeof(tcp_sc_msstab) / sizeof(int) - 1; mss > 0; mss--)
1576 		if (tcp_sc_msstab[mss] <= pmss)
1577 			break;
1578 
1579 	/* Fold parameters and MD5 digest into the ISN we will send. */
1580 	data = sch->sch_oddeven;/* odd or even secret, 1 bit */
1581 	data |= off << 1;	/* secret offset, derived from iss, 3 bits */
1582 	data |= mss << 4;	/* mss, 3 bits */
1583 
1584 	MD5Init(&ctx);
1585 	MD5Update(&ctx, ((u_int8_t *)secbits) + off,
1586 	    SYNCOOKIE_SECRET_SIZE * sizeof(*secbits) - off);
1587 	MD5Update(&ctx, secbits, off);
1588 	MD5Update(&ctx, &sc->sc_inc, sizeof(sc->sc_inc));
1589 	MD5Update(&ctx, &sc->sc_irs, sizeof(sc->sc_irs));
1590 	MD5Update(&ctx, &data, sizeof(data));
1591 	MD5Final((u_int8_t *)&md5_buffer, &ctx);
1592 
1593 	data |= (md5_buffer[0] << 7);
1594 	sc->sc_iss = data;
1595 
1596 #ifdef INET6
1597 	*flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1598 #endif
1599 
1600 	/* Additional parameters are stored in the timestamp if present. */
1601 	if (sc->sc_flags & SCF_TIMESTAMP) {
1602 		data =  ((sc->sc_flags & SCF_SIGNATURE) ? 1 : 0); /* TCP-MD5, 1 bit */
1603 		data |= ((sc->sc_flags & SCF_SACK) ? 1 : 0) << 1; /* SACK, 1 bit */
1604 		data |= sc->sc_requested_s_scale << 2;  /* SWIN scale, 4 bits */
1605 		data |= sc->sc_requested_r_scale << 6;  /* RWIN scale, 4 bits */
1606 		data |= md5_buffer[2] << 10;		/* more digest bits */
1607 		data ^= md5_buffer[3];
1608 		sc->sc_ts = data;
1609 		sc->sc_tsoff = data - ticks;		/* after XOR */
1610 	}
1611 
1612 	V_tcpstat.tcps_sc_sendcookie++;
1613 	return;
1614 }
1615 
1616 static struct syncache *
1617 syncookie_lookup(struct in_conninfo *inc, struct syncache_head *sch,
1618     struct syncache *sc, struct tcpopt *to, struct tcphdr *th,
1619     struct socket *so)
1620 {
1621 	MD5_CTX ctx;
1622 	u_int32_t md5_buffer[MD5_DIGEST_LENGTH / sizeof(u_int32_t)];
1623 	u_int32_t data = 0;
1624 	u_int32_t *secbits;
1625 	tcp_seq ack, seq;
1626 	int off, mss, wnd, flags;
1627 
1628 	SCH_LOCK_ASSERT(sch);
1629 
1630 	/*
1631 	 * Pull information out of SYN-ACK/ACK and
1632 	 * revert sequence number advances.
1633 	 */
1634 	ack = th->th_ack - 1;
1635 	seq = th->th_seq - 1;
1636 	off = (ack >> 1) & 0x7;
1637 	mss = (ack >> 4) & 0x7;
1638 	flags = ack & 0x7f;
1639 
1640 	/* Which of the two secrets to use. */
1641 	secbits = (flags & 0x1) ? sch->sch_secbits_odd : sch->sch_secbits_even;
1642 
1643 	/*
1644 	 * The secret wasn't updated for the lifetime of a syncookie,
1645 	 * so this SYN-ACK/ACK is either too old (replay) or totally bogus.
1646 	 */
1647 	if (sch->sch_reseed + SYNCOOKIE_LIFETIME < time_uptime) {
1648 		return (NULL);
1649 	}
1650 
1651 	/* Recompute the digest so we can compare it. */
1652 	MD5Init(&ctx);
1653 	MD5Update(&ctx, ((u_int8_t *)secbits) + off,
1654 	    SYNCOOKIE_SECRET_SIZE * sizeof(*secbits) - off);
1655 	MD5Update(&ctx, secbits, off);
1656 	MD5Update(&ctx, inc, sizeof(*inc));
1657 	MD5Update(&ctx, &seq, sizeof(seq));
1658 	MD5Update(&ctx, &flags, sizeof(flags));
1659 	MD5Final((u_int8_t *)&md5_buffer, &ctx);
1660 
1661 	/* Does the digest part of or ACK'ed ISS match? */
1662 	if ((ack & (~0x7f)) != (md5_buffer[0] << 7))
1663 		return (NULL);
1664 
1665 	/* Does the digest part of our reflected timestamp match? */
1666 	if (to->to_flags & TOF_TS) {
1667 		data = md5_buffer[3] ^ to->to_tsecr;
1668 		if ((data & (~0x3ff)) != (md5_buffer[2] << 10))
1669 			return (NULL);
1670 	}
1671 
1672 	/* Fill in the syncache values. */
1673 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1674 	sc->sc_ipopts = NULL;
1675 
1676 	sc->sc_irs = seq;
1677 	sc->sc_iss = ack;
1678 
1679 #ifdef INET6
1680 	if (inc->inc_isipv6) {
1681 		if (sotoinpcb(so)->in6p_flags & IN6P_AUTOFLOWLABEL)
1682 			sc->sc_flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1683 	} else
1684 #endif
1685 	{
1686 		sc->sc_ip_ttl = sotoinpcb(so)->inp_ip_ttl;
1687 		sc->sc_ip_tos = sotoinpcb(so)->inp_ip_tos;
1688 	}
1689 
1690 	/* Additional parameters that were encoded in the timestamp. */
1691 	if (data) {
1692 		sc->sc_flags |= SCF_TIMESTAMP;
1693 		sc->sc_tsreflect = to->to_tsval;
1694 		sc->sc_ts = to->to_tsecr;
1695 		sc->sc_tsoff = to->to_tsecr - ticks;
1696 		sc->sc_flags |= (data & 0x1) ? SCF_SIGNATURE : 0;
1697 		sc->sc_flags |= ((data >> 1) & 0x1) ? SCF_SACK : 0;
1698 		sc->sc_requested_s_scale = min((data >> 2) & 0xf,
1699 		    TCP_MAX_WINSHIFT);
1700 		sc->sc_requested_r_scale = min((data >> 6) & 0xf,
1701 		    TCP_MAX_WINSHIFT);
1702 		if (sc->sc_requested_s_scale || sc->sc_requested_r_scale)
1703 			sc->sc_flags |= SCF_WINSCALE;
1704 	} else
1705 		sc->sc_flags |= SCF_NOOPT;
1706 
1707 	wnd = sbspace(&so->so_rcv);
1708 	wnd = imax(wnd, 0);
1709 	wnd = imin(wnd, TCP_MAXWIN);
1710 	sc->sc_wnd = wnd;
1711 
1712 	sc->sc_rxmits = 0;
1713 	sc->sc_peer_mss = tcp_sc_msstab[mss];
1714 
1715 	V_tcpstat.tcps_sc_recvcookie++;
1716 	return (sc);
1717 }
1718 
1719 /*
1720  * Returns the current number of syncache entries.  This number
1721  * will probably change before you get around to calling
1722  * syncache_pcblist.
1723  */
1724 
1725 int
1726 syncache_pcbcount(void)
1727 {
1728 	struct syncache_head *sch;
1729 	int count, i;
1730 
1731 	for (count = 0, i = 0; i < V_tcp_syncache.hashsize; i++) {
1732 		/* No need to lock for a read. */
1733 		sch = &V_tcp_syncache.hashbase[i];
1734 		count += sch->sch_length;
1735 	}
1736 	return count;
1737 }
1738 
1739 /*
1740  * Exports the syncache entries to userland so that netstat can display
1741  * them alongside the other sockets.  This function is intended to be
1742  * called only from tcp_pcblist.
1743  *
1744  * Due to concurrency on an active system, the number of pcbs exported
1745  * may have no relation to max_pcbs.  max_pcbs merely indicates the
1746  * amount of space the caller allocated for this function to use.
1747  */
1748 int
1749 syncache_pcblist(struct sysctl_req *req, int max_pcbs, int *pcbs_exported)
1750 {
1751 	struct xtcpcb xt;
1752 	struct syncache *sc;
1753 	struct syncache_head *sch;
1754 	int count, error, i;
1755 
1756 	for (count = 0, error = 0, i = 0; i < V_tcp_syncache.hashsize; i++) {
1757 		sch = &V_tcp_syncache.hashbase[i];
1758 		SCH_LOCK(sch);
1759 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
1760 			if (count >= max_pcbs) {
1761 				SCH_UNLOCK(sch);
1762 				goto exit;
1763 			}
1764 			bzero(&xt, sizeof(xt));
1765 			xt.xt_len = sizeof(xt);
1766 			if (sc->sc_inc.inc_isipv6)
1767 				xt.xt_inp.inp_vflag = INP_IPV6;
1768 			else
1769 				xt.xt_inp.inp_vflag = INP_IPV4;
1770 			bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc, sizeof (struct in_conninfo));
1771 			xt.xt_tp.t_inpcb = &xt.xt_inp;
1772 			xt.xt_tp.t_state = TCPS_SYN_RECEIVED;
1773 			xt.xt_socket.xso_protocol = IPPROTO_TCP;
1774 			xt.xt_socket.xso_len = sizeof (struct xsocket);
1775 			xt.xt_socket.so_type = SOCK_STREAM;
1776 			xt.xt_socket.so_state = SS_ISCONNECTING;
1777 			error = SYSCTL_OUT(req, &xt, sizeof xt);
1778 			if (error) {
1779 				SCH_UNLOCK(sch);
1780 				goto exit;
1781 			}
1782 			count++;
1783 		}
1784 		SCH_UNLOCK(sch);
1785 	}
1786 exit:
1787 	*pcbs_exported = count;
1788 	return error;
1789 }
1790