xref: /freebsd/sys/netinet/tcp_syncache.c (revision b8aa2713423518bc3d708a08b52433096de96e9b)
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  * $FreeBSD$
33  */
34 
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 #include "opt_ipsec.h"
38 #include "opt_mac.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/sysctl.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/md5.h>
49 #include <sys/proc.h>		/* for proc0 declaration */
50 #include <sys/random.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 
54 #include <vm/uma.h>
55 
56 #include <net/if.h>
57 #include <net/route.h>
58 
59 #include <netinet/in.h>
60 #include <netinet/in_systm.h>
61 #include <netinet/ip.h>
62 #include <netinet/in_var.h>
63 #include <netinet/in_pcb.h>
64 #include <netinet/ip_var.h>
65 #include <netinet/ip_options.h>
66 #ifdef INET6
67 #include <netinet/ip6.h>
68 #include <netinet/icmp6.h>
69 #include <netinet6/nd6.h>
70 #include <netinet6/ip6_var.h>
71 #include <netinet6/in6_pcb.h>
72 #endif
73 #include <netinet/tcp.h>
74 #include <netinet/tcp_fsm.h>
75 #include <netinet/tcp_seq.h>
76 #include <netinet/tcp_timer.h>
77 #include <netinet/tcp_var.h>
78 #ifdef INET6
79 #include <netinet6/tcp6_var.h>
80 #endif
81 
82 #ifdef IPSEC
83 #include <netinet6/ipsec.h>
84 #ifdef INET6
85 #include <netinet6/ipsec6.h>
86 #endif
87 #endif /*IPSEC*/
88 
89 #ifdef FAST_IPSEC
90 #include <netipsec/ipsec.h>
91 #ifdef INET6
92 #include <netipsec/ipsec6.h>
93 #endif
94 #include <netipsec/key.h>
95 #endif /*FAST_IPSEC*/
96 
97 #include <machine/in_cksum.h>
98 
99 #include <security/mac/mac_framework.h>
100 
101 static int tcp_syncookies = 1;
102 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
103     &tcp_syncookies, 0,
104     "Use TCP SYN cookies if the syncache overflows");
105 
106 static int tcp_syncookiesonly = 0;
107 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies_only, CTLFLAG_RW,
108     &tcp_syncookiesonly, 0,
109     "Use only TCP SYN cookies");
110 
111 #define	SYNCOOKIE_SECRET_SIZE	8	/* dwords */
112 #define	SYNCOOKIE_LIFETIME	16	/* seconds */
113 
114 struct syncache {
115 	TAILQ_ENTRY(syncache)	sc_hash;
116 	struct		in_conninfo sc_inc;	/* addresses */
117 	u_long		sc_rxttime;		/* retransmit time */
118 	u_int16_t	sc_rxmits;		/* retransmit counter */
119 
120 	u_int32_t	sc_tsreflect;		/* timestamp to reflect */
121 	u_int32_t	sc_ts;			/* our timestamp to send */
122 	u_int32_t	sc_tsoff;		/* ts offset w/ syncookies */
123 	u_int32_t	sc_flowlabel;		/* IPv6 flowlabel */
124 	tcp_seq		sc_irs;			/* seq from peer */
125 	tcp_seq		sc_iss;			/* our ISS */
126 	struct		mbuf *sc_ipopts;	/* source route */
127 
128 	u_int16_t	sc_peer_mss;		/* peer's MSS */
129 	u_int16_t	sc_wnd;			/* advertised window */
130 	u_int8_t	sc_ip_ttl;		/* IPv4 TTL */
131 	u_int8_t	sc_ip_tos;		/* IPv4 TOS */
132 	u_int8_t	sc_requested_s_scale:4,
133 			sc_requested_r_scale:4;
134 	u_int8_t	sc_flags;
135 #define SCF_NOOPT	0x01			/* no TCP options */
136 #define SCF_WINSCALE	0x02			/* negotiated window scaling */
137 #define SCF_TIMESTAMP	0x04			/* negotiated timestamps */
138 						/* MSS is implicit */
139 #define SCF_UNREACH	0x10			/* icmp unreachable received */
140 #define SCF_SIGNATURE	0x20			/* send MD5 digests */
141 #define SCF_SACK	0x80			/* send SACK option */
142 };
143 
144 struct syncache_head {
145 	struct mtx	sch_mtx;
146 	TAILQ_HEAD(sch_head, syncache)	sch_bucket;
147 	struct callout	sch_timer;
148 	int		sch_nextc;
149 	u_int		sch_length;
150 	u_int		sch_oddeven;
151 	u_int32_t	sch_secbits_odd[SYNCOOKIE_SECRET_SIZE];
152 	u_int32_t	sch_secbits_even[SYNCOOKIE_SECRET_SIZE];
153 	u_int		sch_reseed;		/* time_uptime, seconds */
154 };
155 
156 static void	 syncache_drop(struct syncache *, struct syncache_head *);
157 static void	 syncache_free(struct syncache *);
158 static void	 syncache_insert(struct syncache *, struct syncache_head *);
159 struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
160 static int	 syncache_respond(struct syncache *, struct mbuf *);
161 static struct	 socket *syncache_socket(struct syncache *, struct socket *,
162 		    struct mbuf *m);
163 static void	 syncache_timer(void *);
164 static void	 syncookie_generate(struct syncache_head *, struct syncache *,
165 		    u_int32_t *);
166 static struct syncache
167 		*syncookie_lookup(struct in_conninfo *, struct syncache_head *,
168 		    struct syncache *, struct tcpopt *, struct tcphdr *,
169 		    struct socket *);
170 
171 /*
172  * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
173  * 3 retransmits corresponds to a timeout of (1 + 2 + 4 + 8 == 15) seconds,
174  * the odds are that the user has given up attempting to connect by then.
175  */
176 #define SYNCACHE_MAXREXMTS		3
177 
178 /* Arbitrary values */
179 #define TCP_SYNCACHE_HASHSIZE		512
180 #define TCP_SYNCACHE_BUCKETLIMIT	30
181 
182 struct tcp_syncache {
183 	struct	syncache_head *hashbase;
184 	uma_zone_t zone;
185 	u_int	hashsize;
186 	u_int	hashmask;
187 	u_int	bucket_limit;
188 	u_int	cache_count;		/* XXX: unprotected */
189 	u_int	cache_limit;
190 	u_int	rexmt_limit;
191 	u_int	hash_secret;
192 };
193 static struct tcp_syncache tcp_syncache;
194 
195 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
196 
197 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RDTUN,
198      &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
199 
200 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RDTUN,
201      &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
202 
203 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
204      &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
205 
206 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RDTUN,
207      &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
208 
209 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
210      &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
211 
212 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
213 
214 #define SYNCACHE_HASH(inc, mask)					\
215 	((tcp_syncache.hash_secret ^					\
216 	  (inc)->inc_faddr.s_addr ^					\
217 	  ((inc)->inc_faddr.s_addr >> 16) ^				\
218 	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
219 
220 #define SYNCACHE_HASH6(inc, mask)					\
221 	((tcp_syncache.hash_secret ^					\
222 	  (inc)->inc6_faddr.s6_addr32[0] ^				\
223 	  (inc)->inc6_faddr.s6_addr32[3] ^				\
224 	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
225 
226 #define ENDPTS_EQ(a, b) (						\
227 	(a)->ie_fport == (b)->ie_fport &&				\
228 	(a)->ie_lport == (b)->ie_lport &&				\
229 	(a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&			\
230 	(a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr			\
231 )
232 
233 #define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
234 
235 #define SYNCACHE_TIMEOUT(sc, sch, co) do {				\
236 	(sc)->sc_rxmits++;						\
237 	(sc)->sc_rxttime = ticks +					\
238 		TCPTV_RTOBASE * tcp_backoff[(sc)->sc_rxmits - 1];	\
239 	if ((sch)->sch_nextc > (sc)->sc_rxttime)			\
240 		(sch)->sch_nextc = (sc)->sc_rxttime;			\
241 	if (!TAILQ_EMPTY(&(sch)->sch_bucket) && !(co))			\
242 		callout_reset(&(sch)->sch_timer,			\
243 			(sch)->sch_nextc - ticks,			\
244 			syncache_timer, (void *)(sch));			\
245 } while (0)
246 
247 #define	SCH_LOCK(sch)		mtx_lock(&(sch)->sch_mtx)
248 #define	SCH_UNLOCK(sch)		mtx_unlock(&(sch)->sch_mtx)
249 #define	SCH_LOCK_ASSERT(sch)	mtx_assert(&(sch)->sch_mtx, MA_OWNED)
250 
251 /*
252  * Requires the syncache entry to be already removed from the bucket list.
253  */
254 static void
255 syncache_free(struct syncache *sc)
256 {
257 	if (sc->sc_ipopts)
258 		(void) m_free(sc->sc_ipopts);
259 
260 	uma_zfree(tcp_syncache.zone, sc);
261 }
262 
263 void
264 syncache_init(void)
265 {
266 	int i;
267 
268 	tcp_syncache.cache_count = 0;
269 	tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
270 	tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
271 	tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
272 	tcp_syncache.hash_secret = arc4random();
273 
274 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
275 	    &tcp_syncache.hashsize);
276 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
277 	    &tcp_syncache.bucket_limit);
278 	if (!powerof2(tcp_syncache.hashsize) || tcp_syncache.hashsize == 0) {
279 		printf("WARNING: syncache hash size is not a power of 2.\n");
280 		tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
281 	}
282 	tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
283 
284 	/* Set limits. */
285 	tcp_syncache.cache_limit =
286 	    tcp_syncache.hashsize * tcp_syncache.bucket_limit;
287 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
288 	    &tcp_syncache.cache_limit);
289 
290 	/* Allocate the hash table. */
291 	MALLOC(tcp_syncache.hashbase, struct syncache_head *,
292 	    tcp_syncache.hashsize * sizeof(struct syncache_head),
293 	    M_SYNCACHE, M_WAITOK | M_ZERO);
294 
295 	/* Initialize the hash buckets. */
296 	for (i = 0; i < tcp_syncache.hashsize; i++) {
297 		TAILQ_INIT(&tcp_syncache.hashbase[i].sch_bucket);
298 		mtx_init(&tcp_syncache.hashbase[i].sch_mtx, "tcp_sc_head",
299 			 NULL, MTX_DEF);
300 		callout_init_mtx(&tcp_syncache.hashbase[i].sch_timer,
301 			 &tcp_syncache.hashbase[i].sch_mtx, 0);
302 		tcp_syncache.hashbase[i].sch_length = 0;
303 	}
304 
305 	/* Create the syncache entry zone. */
306 	tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
307 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
308 	uma_zone_set_max(tcp_syncache.zone, tcp_syncache.cache_limit);
309 }
310 
311 /*
312  * Inserts a syncache entry into the specified bucket row.
313  * Locks and unlocks the syncache_head autonomously.
314  */
315 static void
316 syncache_insert(struct syncache *sc, struct syncache_head *sch)
317 {
318 	struct syncache *sc2;
319 
320 	SCH_LOCK(sch);
321 
322 	/*
323 	 * Make sure that we don't overflow the per-bucket limit.
324 	 * If the bucket is full, toss the oldest element.
325 	 */
326 	if (sch->sch_length >= tcp_syncache.bucket_limit) {
327 		KASSERT(!TAILQ_EMPTY(&sch->sch_bucket),
328 			("sch->sch_length incorrect"));
329 		sc2 = TAILQ_LAST(&sch->sch_bucket, sch_head);
330 		syncache_drop(sc2, sch);
331 		tcpstat.tcps_sc_bucketoverflow++;
332 	}
333 
334 	/* Put it into the bucket. */
335 	TAILQ_INSERT_HEAD(&sch->sch_bucket, sc, sc_hash);
336 	sch->sch_length++;
337 
338 	/* Reinitialize the bucket row's timer. */
339 	SYNCACHE_TIMEOUT(sc, sch, 1);
340 
341 	SCH_UNLOCK(sch);
342 
343 	tcp_syncache.cache_count++;
344 	tcpstat.tcps_sc_added++;
345 }
346 
347 /*
348  * Remove and free entry from syncache bucket row.
349  * Expects locked syncache head.
350  */
351 static void
352 syncache_drop(struct syncache *sc, struct syncache_head *sch)
353 {
354 
355 	SCH_LOCK_ASSERT(sch);
356 
357 	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
358 	sch->sch_length--;
359 
360 	syncache_free(sc);
361 	tcp_syncache.cache_count--;
362 }
363 
364 /*
365  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
366  * If we have retransmitted an entry the maximum number of times, expire it.
367  * One separate timer for each bucket row.
368  */
369 static void
370 syncache_timer(void *xsch)
371 {
372 	struct syncache_head *sch = (struct syncache_head *)xsch;
373 	struct syncache *sc, *nsc;
374 	int tick = ticks;
375 
376 	/* NB: syncache_head has already been locked by the callout. */
377 	SCH_LOCK_ASSERT(sch);
378 
379 	TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) {
380 		/*
381 		 * We do not check if the listen socket still exists
382 		 * and accept the case where the listen socket may be
383 		 * gone by the time we resend the SYN/ACK.  We do
384 		 * not expect this to happens often. If it does,
385 		 * then the RST will be sent by the time the remote
386 		 * host does the SYN/ACK->ACK.
387 		 */
388 		if (sc->sc_rxttime >= tick) {
389 			if (sc->sc_rxttime < sch->sch_nextc)
390 				sch->sch_nextc = sc->sc_rxttime;
391 			continue;
392 		}
393 
394 		if (sc->sc_rxmits > tcp_syncache.rexmt_limit) {
395 			syncache_drop(sc, sch);
396 			tcpstat.tcps_sc_stale++;
397 			continue;
398 		}
399 
400 		(void) syncache_respond(sc, NULL);
401 		tcpstat.tcps_sc_retransmitted++;
402 		SYNCACHE_TIMEOUT(sc, sch, 0);
403 	}
404 	if (!TAILQ_EMPTY(&(sch)->sch_bucket))
405 		callout_reset(&(sch)->sch_timer, (sch)->sch_nextc - tick,
406 			syncache_timer, (void *)(sch));
407 }
408 
409 /*
410  * Find an entry in the syncache.
411  * Returns always with locked syncache_head plus a matching entry or NULL.
412  */
413 struct syncache *
414 syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
415 {
416 	struct syncache *sc;
417 	struct syncache_head *sch;
418 
419 #ifdef INET6
420 	if (inc->inc_isipv6) {
421 		sch = &tcp_syncache.hashbase[
422 		    SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
423 		*schp = sch;
424 
425 		SCH_LOCK(sch);
426 
427 		/* Circle through bucket row to find matching entry. */
428 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
429 			if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
430 				return (sc);
431 		}
432 	} else
433 #endif
434 	{
435 		sch = &tcp_syncache.hashbase[
436 		    SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
437 		*schp = sch;
438 
439 		SCH_LOCK(sch);
440 
441 		/* Circle through bucket row to find matching entry. */
442 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
443 #ifdef INET6
444 			if (sc->sc_inc.inc_isipv6)
445 				continue;
446 #endif
447 			if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
448 				return (sc);
449 		}
450 	}
451 	SCH_LOCK_ASSERT(*schp);
452 	return (NULL);			/* always returns with locked sch */
453 }
454 
455 /*
456  * This function is called when we get a RST for a
457  * non-existent connection, so that we can see if the
458  * connection is in the syn cache.  If it is, zap it.
459  */
460 void
461 syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th)
462 {
463 	struct syncache *sc;
464 	struct syncache_head *sch;
465 
466 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
467 	SCH_LOCK_ASSERT(sch);
468 	if (sc == NULL)
469 		goto done;
470 
471 	/*
472 	 * If the RST bit is set, check the sequence number to see
473 	 * if this is a valid reset segment.
474 	 * RFC 793 page 37:
475 	 *   In all states except SYN-SENT, all reset (RST) segments
476 	 *   are validated by checking their SEQ-fields.  A reset is
477 	 *   valid if its sequence number is in the window.
478 	 *
479 	 *   The sequence number in the reset segment is normally an
480 	 *   echo of our outgoing acknowlegement numbers, but some hosts
481 	 *   send a reset with the sequence number at the rightmost edge
482 	 *   of our receive window, and we have to handle this case.
483 	 */
484 	if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
485 	    SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
486 		syncache_drop(sc, sch);
487 		tcpstat.tcps_sc_reset++;
488 	}
489 done:
490 	SCH_UNLOCK(sch);
491 }
492 
493 void
494 syncache_badack(struct in_conninfo *inc)
495 {
496 	struct syncache *sc;
497 	struct syncache_head *sch;
498 
499 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
500 	SCH_LOCK_ASSERT(sch);
501 	if (sc != NULL) {
502 		syncache_drop(sc, sch);
503 		tcpstat.tcps_sc_badack++;
504 	}
505 	SCH_UNLOCK(sch);
506 }
507 
508 void
509 syncache_unreach(struct in_conninfo *inc, struct tcphdr *th)
510 {
511 	struct syncache *sc;
512 	struct syncache_head *sch;
513 
514 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
515 	SCH_LOCK_ASSERT(sch);
516 	if (sc == NULL)
517 		goto done;
518 
519 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
520 	if (ntohl(th->th_seq) != sc->sc_iss)
521 		goto done;
522 
523 	/*
524 	 * If we've rertransmitted 3 times and this is our second error,
525 	 * we remove the entry.  Otherwise, we allow it to continue on.
526 	 * This prevents us from incorrectly nuking an entry during a
527 	 * spurious network outage.
528 	 *
529 	 * See tcp_notify().
530 	 */
531 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxmits < 3 + 1) {
532 		sc->sc_flags |= SCF_UNREACH;
533 		goto done;
534 	}
535 	syncache_drop(sc, sch);
536 	tcpstat.tcps_sc_unreach++;
537 done:
538 	SCH_UNLOCK(sch);
539 }
540 
541 /*
542  * Build a new TCP socket structure from a syncache entry.
543  */
544 static struct socket *
545 syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m)
546 {
547 	struct inpcb *inp = NULL;
548 	struct socket *so;
549 	struct tcpcb *tp;
550 
551 	NET_ASSERT_GIANT();
552 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
553 
554 	/*
555 	 * Ok, create the full blown connection, and set things up
556 	 * as they would have been set up if we had created the
557 	 * connection when the SYN arrived.  If we can't create
558 	 * the connection, abort it.
559 	 */
560 	so = sonewconn(lso, SS_ISCONNECTED);
561 	if (so == NULL) {
562 		/*
563 		 * Drop the connection; we will send a RST if the peer
564 		 * retransmits the ACK,
565 		 */
566 		tcpstat.tcps_listendrop++;
567 		goto abort2;
568 	}
569 #ifdef MAC
570 	SOCK_LOCK(so);
571 	mac_set_socket_peer_from_mbuf(m, so);
572 	SOCK_UNLOCK(so);
573 #endif
574 
575 	inp = sotoinpcb(so);
576 	INP_LOCK(inp);
577 
578 	/* Insert new socket into PCB hash list. */
579 	inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
580 #ifdef INET6
581 	if (sc->sc_inc.inc_isipv6) {
582 		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
583 	} else {
584 		inp->inp_vflag &= ~INP_IPV6;
585 		inp->inp_vflag |= INP_IPV4;
586 #endif
587 		inp->inp_laddr = sc->sc_inc.inc_laddr;
588 #ifdef INET6
589 	}
590 #endif
591 	inp->inp_lport = sc->sc_inc.inc_lport;
592 	if (in_pcbinshash(inp) != 0) {
593 		/*
594 		 * Undo the assignments above if we failed to
595 		 * put the PCB on the hash lists.
596 		 */
597 #ifdef INET6
598 		if (sc->sc_inc.inc_isipv6)
599 			inp->in6p_laddr = in6addr_any;
600 		else
601 #endif
602 			inp->inp_laddr.s_addr = INADDR_ANY;
603 		inp->inp_lport = 0;
604 		goto abort;
605 	}
606 #ifdef IPSEC
607 	/* Copy old policy into new socket's. */
608 	if (ipsec_copy_pcbpolicy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
609 		printf("syncache_socket: could not copy policy\n");
610 #endif
611 #ifdef FAST_IPSEC
612 	/* Copy old policy into new socket's. */
613 	if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
614 		printf("syncache_socket: could not copy policy\n");
615 #endif
616 #ifdef INET6
617 	if (sc->sc_inc.inc_isipv6) {
618 		struct inpcb *oinp = sotoinpcb(lso);
619 		struct in6_addr laddr6;
620 		struct sockaddr_in6 sin6;
621 		/*
622 		 * Inherit socket options from the listening socket.
623 		 * Note that in6p_inputopts are not (and should not be)
624 		 * copied, since it stores previously received options and is
625 		 * used to detect if each new option is different than the
626 		 * previous one and hence should be passed to a user.
627 		 * If we copied in6p_inputopts, a user would not be able to
628 		 * receive options just after calling the accept system call.
629 		 */
630 		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
631 		if (oinp->in6p_outputopts)
632 			inp->in6p_outputopts =
633 			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
634 
635 		sin6.sin6_family = AF_INET6;
636 		sin6.sin6_len = sizeof(sin6);
637 		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
638 		sin6.sin6_port = sc->sc_inc.inc_fport;
639 		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
640 		laddr6 = inp->in6p_laddr;
641 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
642 			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
643 		if (in6_pcbconnect(inp, (struct sockaddr *)&sin6,
644 		    thread0.td_ucred)) {
645 			inp->in6p_laddr = laddr6;
646 			goto abort;
647 		}
648 		/* Override flowlabel from in6_pcbconnect. */
649 		inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
650 		inp->in6p_flowinfo |= sc->sc_flowlabel;
651 	} else
652 #endif
653 	{
654 		struct in_addr laddr;
655 		struct sockaddr_in sin;
656 
657 		inp->inp_options = ip_srcroute(m);
658 		if (inp->inp_options == NULL) {
659 			inp->inp_options = sc->sc_ipopts;
660 			sc->sc_ipopts = NULL;
661 		}
662 
663 		sin.sin_family = AF_INET;
664 		sin.sin_len = sizeof(sin);
665 		sin.sin_addr = sc->sc_inc.inc_faddr;
666 		sin.sin_port = sc->sc_inc.inc_fport;
667 		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
668 		laddr = inp->inp_laddr;
669 		if (inp->inp_laddr.s_addr == INADDR_ANY)
670 			inp->inp_laddr = sc->sc_inc.inc_laddr;
671 		if (in_pcbconnect(inp, (struct sockaddr *)&sin,
672 		    thread0.td_ucred)) {
673 			inp->inp_laddr = laddr;
674 			goto abort;
675 		}
676 	}
677 	tp = intotcpcb(inp);
678 	tp->t_state = TCPS_SYN_RECEIVED;
679 	tp->iss = sc->sc_iss;
680 	tp->irs = sc->sc_irs;
681 	tcp_rcvseqinit(tp);
682 	tcp_sendseqinit(tp);
683 	tp->snd_wl1 = sc->sc_irs;
684 	tp->rcv_up = sc->sc_irs + 1;
685 	tp->rcv_wnd = sc->sc_wnd;
686 	tp->rcv_adv += tp->rcv_wnd;
687 
688 	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
689 	if (sc->sc_flags & SCF_NOOPT)
690 		tp->t_flags |= TF_NOOPT;
691 	else {
692 		if (sc->sc_flags & SCF_WINSCALE) {
693 			tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
694 			tp->snd_scale = sc->sc_requested_s_scale;
695 			tp->request_r_scale = sc->sc_requested_r_scale;
696 		}
697 		if (sc->sc_flags & SCF_TIMESTAMP) {
698 			tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
699 			tp->ts_recent = sc->sc_tsreflect;
700 			tp->ts_recent_age = ticks;
701 			tp->ts_offset = sc->sc_tsoff;
702 		}
703 #ifdef TCP_SIGNATURE
704 		if (sc->sc_flags & SCF_SIGNATURE)
705 			tp->t_flags |= TF_SIGNATURE;
706 #endif
707 		if (sc->sc_flags & SCF_SACK) {
708 			tp->sack_enable = 1;
709 			tp->t_flags |= TF_SACK_PERMIT;
710 		}
711 	}
712 
713 	/*
714 	 * Set up MSS and get cached values from tcp_hostcache.
715 	 * This might overwrite some of the defaults we just set.
716 	 */
717 	tcp_mss(tp, sc->sc_peer_mss);
718 
719 	/*
720 	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
721 	 */
722 	if (sc->sc_rxmits > 1)
723 		tp->snd_cwnd = tp->t_maxseg;
724 	callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
725 
726 	INP_UNLOCK(inp);
727 
728 	tcpstat.tcps_accepts++;
729 	return (so);
730 
731 abort:
732 	INP_UNLOCK(inp);
733 abort2:
734 	if (so != NULL)
735 		soabort(so);
736 	return (NULL);
737 }
738 
739 /*
740  * This function gets called when we receive an ACK for a
741  * socket in the LISTEN state.  We look up the connection
742  * in the syncache, and if its there, we pull it out of
743  * the cache and turn it into a full-blown connection in
744  * the SYN-RECEIVED state.
745  */
746 int
747 syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
748     struct socket **lsop, struct mbuf *m)
749 {
750 	struct syncache *sc;
751 	struct syncache_head *sch;
752 	struct socket *so;
753 	struct syncache scs;
754 
755 	/*
756 	 * Global TCP locks are held because we manipulate the PCB lists
757 	 * and create a new socket.
758 	 */
759 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
760 
761 	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
762 	SCH_LOCK_ASSERT(sch);
763 	if (sc == NULL) {
764 		/*
765 		 * There is no syncache entry, so see if this ACK is
766 		 * a returning syncookie.  To do this, first:
767 		 *  A. See if this socket has had a syncache entry dropped in
768 		 *     the past.  We don't want to accept a bogus syncookie
769 		 *     if we've never received a SYN.
770 		 *  B. check that the syncookie is valid.  If it is, then
771 		 *     cobble up a fake syncache entry, and return.
772 		 */
773 		if (!tcp_syncookies) {
774 			SCH_UNLOCK(sch);
775 			goto failed;
776 		}
777 		bzero(&scs, sizeof(scs));
778 		sc = syncookie_lookup(inc, sch, &scs, to, th, *lsop);
779 		SCH_UNLOCK(sch);
780 		if (sc == NULL)
781 			goto failed;
782 		tcpstat.tcps_sc_recvcookie++;
783 	} else {
784 		/* Pull out the entry to unlock the bucket row. */
785 		TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
786 		sch->sch_length--;
787 		tcp_syncache.cache_count--;
788 		SCH_UNLOCK(sch);
789 	}
790 
791 	/*
792 	 * If seg contains an ACK, but not for our SYN/ACK, send a RST.
793 	 */
794 	if (th->th_ack != sc->sc_iss + 1)
795 		goto failed;
796 
797 	so = syncache_socket(sc, *lsop, m);
798 
799 	if (so == NULL) {
800 #if 0
801 resetandabort:
802 		/* XXXjlemon check this - is this correct? */
803 		(void) tcp_respond(NULL, m, m, th,
804 		    th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
805 #endif
806 		m_freem(m);			/* XXX: only needed for above */
807 		tcpstat.tcps_sc_aborted++;
808 		if (sc != &scs) {
809 			syncache_insert(sc, sch);  /* try again later */
810 			sc = NULL;
811 		}
812 		goto failed;
813 	} else
814 		tcpstat.tcps_sc_completed++;
815 	*lsop = so;
816 
817 	if (sc != &scs)
818 		syncache_free(sc);
819 	return (1);
820 failed:
821 	if (sc != NULL && sc != &scs)
822 		syncache_free(sc);
823 	return (0);
824 }
825 
826 /*
827  * Given a LISTEN socket and an inbound SYN request, add
828  * this to the syn cache, and send back a segment:
829  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
830  * to the source.
831  *
832  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
833  * Doing so would require that we hold onto the data and deliver it
834  * to the application.  However, if we are the target of a SYN-flood
835  * DoS attack, an attacker could send data which would eventually
836  * consume all available buffer space if it were ACKed.  By not ACKing
837  * the data, we avoid this DoS scenario.
838  */
839 int
840 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
841     struct inpcb *inp, struct socket **lsop, struct mbuf *m)
842 {
843 	struct tcpcb *tp;
844 	struct socket *so;
845 	struct syncache *sc = NULL;
846 	struct syncache_head *sch;
847 	struct mbuf *ipopts = NULL;
848 	u_int32_t flowtmp;
849 	int win, sb_hiwat, ip_ttl, ip_tos, noopt;
850 #ifdef INET6
851 	int autoflowlabel = 0;
852 #endif
853 	struct syncache scs;
854 
855 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
856 	INP_LOCK_ASSERT(inp);			/* listen socket */
857 
858 	/*
859 	 * Combine all so/tp operations very early to drop the INP lock as
860 	 * soon as possible.
861 	 */
862 	so = *lsop;
863 	tp = sototcpcb(so);
864 
865 #ifdef INET6
866 	if (inc->inc_isipv6 &&
867 	    (inp->in6p_flags & IN6P_AUTOFLOWLABEL))
868 		autoflowlabel = 1;
869 #endif
870 	ip_ttl = inp->inp_ip_ttl;
871 	ip_tos = inp->inp_ip_tos;
872 	win = sbspace(&so->so_rcv);
873 	sb_hiwat = so->so_rcv.sb_hiwat;
874 	noopt = (tp->t_flags & TF_NOOPT);
875 
876 	so = NULL;
877 	tp = NULL;
878 
879 	INP_UNLOCK(inp);
880 	INP_INFO_WUNLOCK(&tcbinfo);
881 
882 	/*
883 	 * Remember the IP options, if any.
884 	 */
885 #ifdef INET6
886 	if (!inc->inc_isipv6)
887 #endif
888 		ipopts = ip_srcroute(m);
889 
890 	/*
891 	 * See if we already have an entry for this connection.
892 	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
893 	 *
894 	 * XXX: should the syncache be re-initialized with the contents
895 	 * of the new SYN here (which may have different options?)
896 	 */
897 	sc = syncache_lookup(inc, &sch);	/* returns locked entry */
898 	SCH_LOCK_ASSERT(sch);
899 	if (sc != NULL) {
900 		tcpstat.tcps_sc_dupsyn++;
901 		if (ipopts) {
902 			/*
903 			 * If we were remembering a previous source route,
904 			 * forget it and use the new one we've been given.
905 			 */
906 			if (sc->sc_ipopts)
907 				(void) m_free(sc->sc_ipopts);
908 			sc->sc_ipopts = ipopts;
909 		}
910 		/*
911 		 * Update timestamp if present.
912 		 */
913 		if (sc->sc_flags & SCF_TIMESTAMP)
914 			sc->sc_tsreflect = to->to_tsval;
915 		if (syncache_respond(sc, m) == 0) {
916 			SYNCACHE_TIMEOUT(sc, sch, 1);
917 			tcpstat.tcps_sndacks++;
918 			tcpstat.tcps_sndtotal++;
919 		}
920 		SCH_UNLOCK(sch);
921 		goto done;
922 	}
923 
924 	sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
925 	if (sc == NULL) {
926 		/*
927 		 * The zone allocator couldn't provide more entries.
928 		 * Treat this as if the cache was full; drop the oldest
929 		 * entry and insert the new one.
930 		 */
931 		tcpstat.tcps_sc_zonefail++;
932 		sc = TAILQ_LAST(&sch->sch_bucket, sch_head);
933 		syncache_drop(sc, sch);
934 		sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
935 		if (sc == NULL) {
936 			if (tcp_syncookies) {
937 				bzero(&scs, sizeof(scs));
938 				sc = &scs;
939 			} else {
940 				SCH_UNLOCK(sch);
941 				if (ipopts)
942 					(void) m_free(ipopts);
943 				goto done;
944 			}
945 		}
946 	}
947 
948 	/*
949 	 * Fill in the syncache values.
950 	 */
951 	sc->sc_ipopts = ipopts;
952 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
953 #ifdef INET6
954 	if (!inc->inc_isipv6)
955 #endif
956 	{
957 		sc->sc_ip_tos = ip_tos;
958 		sc->sc_ip_ttl = ip_ttl;
959 	}
960 
961 	sc->sc_irs = th->th_seq;
962 	sc->sc_iss = arc4random();
963 	sc->sc_flags = 0;
964 	sc->sc_flowlabel = 0;
965 
966 	/*
967 	 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
968 	 * win was derived from socket earlier in the function.
969 	 */
970 	win = imax(win, 0);
971 	win = imin(win, TCP_MAXWIN);
972 	sc->sc_wnd = win;
973 
974 	if (tcp_do_rfc1323) {
975 		/*
976 		 * A timestamp received in a SYN makes
977 		 * it ok to send timestamp requests and replies.
978 		 */
979 		if (to->to_flags & TOF_TS) {
980 			sc->sc_tsreflect = to->to_tsval;
981 			sc->sc_flags |= SCF_TIMESTAMP;
982 		}
983 		if (to->to_flags & TOF_SCALE) {
984 			int wscale = 0;
985 
986 			/* Compute proper scaling value from buffer space */
987 			while (wscale < TCP_MAX_WINSHIFT &&
988 			    (TCP_MAXWIN << wscale) < sb_hiwat)
989 				wscale++;
990 			sc->sc_requested_r_scale = wscale;
991 			sc->sc_requested_s_scale = to->to_requested_s_scale;
992 			sc->sc_flags |= SCF_WINSCALE;
993 		}
994 	}
995 #ifdef TCP_SIGNATURE
996 	/*
997 	 * If listening socket requested TCP digests, and received SYN
998 	 * contains the option, flag this in the syncache so that
999 	 * syncache_respond() will do the right thing with the SYN+ACK.
1000 	 * XXX: Currently we always record the option by default and will
1001 	 * attempt to use it in syncache_respond().
1002 	 */
1003 	if (to->to_flags & TOF_SIGNATURE)
1004 		sc->sc_flags |= SCF_SIGNATURE;
1005 #endif
1006 	if (to->to_flags & TOF_SACK)
1007 		sc->sc_flags |= SCF_SACK;
1008 	if (to->to_flags & TOF_MSS)
1009 		sc->sc_peer_mss = to->to_mss;	/* peer mss may be zero */
1010 	if (noopt)
1011 		sc->sc_flags |= SCF_NOOPT;
1012 
1013 	if (tcp_syncookies) {
1014 		syncookie_generate(sch, sc, &flowtmp);
1015 #ifdef INET6
1016 		if (autoflowlabel)
1017 			sc->sc_flowlabel = flowtmp;
1018 #endif
1019 	} else {
1020 #ifdef INET6
1021 		if (autoflowlabel)
1022 			sc->sc_flowlabel =
1023 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1024 #endif
1025 	}
1026 	SCH_UNLOCK(sch);
1027 
1028 	/*
1029 	 * Do a standard 3-way handshake.
1030 	 */
1031 	if (syncache_respond(sc, m) == 0) {
1032 		if (tcp_syncookies && tcp_syncookiesonly && sc != &scs)
1033 			syncache_free(sc);
1034 		else if (sc != &scs)
1035 			syncache_insert(sc, sch);   /* locks and unlocks sch */
1036 		tcpstat.tcps_sndacks++;
1037 		tcpstat.tcps_sndtotal++;
1038 	} else {
1039 		syncache_free(sc);
1040 		tcpstat.tcps_sc_dropped++;
1041 	}
1042 
1043 done:
1044 	*lsop = NULL;
1045 	return (1);
1046 }
1047 
1048 static int
1049 syncache_respond(struct syncache *sc, struct mbuf *m)
1050 {
1051 	struct ip *ip = NULL;
1052 	struct tcphdr *th;
1053 	int optlen, error;
1054 	u_int16_t tlen, hlen, mssopt;
1055 	u_int8_t *optp;
1056 #ifdef INET6
1057 	struct ip6_hdr *ip6 = NULL;
1058 #endif
1059 #ifdef MAC
1060 	struct inpcb *inp = NULL;
1061 #endif
1062 
1063 	hlen =
1064 #ifdef INET6
1065 	       (sc->sc_inc.inc_isipv6) ? sizeof(struct ip6_hdr) :
1066 #endif
1067 		sizeof(struct ip);
1068 
1069 	/* Determine MSS we advertize to other end of connection. */
1070 	mssopt = tcp_mssopt(&sc->sc_inc);
1071 	if (sc->sc_peer_mss)
1072 		mssopt = max( min(sc->sc_peer_mss, mssopt), tcp_minmss);
1073 
1074 	/* Compute the size of the TCP options. */
1075 	if (sc->sc_flags & SCF_NOOPT) {
1076 		optlen = 0;
1077 	} else {
1078 		optlen = TCPOLEN_MAXSEG +
1079 		    ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
1080 		    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
1081 #ifdef TCP_SIGNATURE
1082 		if (sc->sc_flags & SCF_SIGNATURE)
1083 			optlen += TCPOLEN_SIGNATURE;
1084 #endif
1085 		if (sc->sc_flags & SCF_SACK)
1086 			optlen += TCPOLEN_SACK_PERMITTED;
1087 		optlen = roundup2(optlen, 4);
1088 	}
1089 	tlen = hlen + sizeof(struct tcphdr) + optlen;
1090 
1091 	/*
1092 	 * XXX: Assume that the entire packet will fit in a header mbuf.
1093 	 */
1094 	KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
1095 
1096 	/* Create the IP+TCP header from scratch. */
1097 	if (m)
1098 		m_freem(m);
1099 
1100 	m = m_gethdr(M_DONTWAIT, MT_DATA);
1101 	if (m == NULL)
1102 		return (ENOBUFS);
1103 	m->m_data += max_linkhdr;
1104 	m->m_len = tlen;
1105 	m->m_pkthdr.len = tlen;
1106 	m->m_pkthdr.rcvif = NULL;
1107 
1108 #ifdef MAC
1109 	/*
1110 	 * For MAC look up the inpcb to get access to the label information.
1111 	 * We don't store the inpcb pointer in struct syncache to make locking
1112 	 * less complicated and to save locking operations.  However for MAC
1113 	 * this gives a slight overhead as we have to do a full pcblookup here.
1114 	 */
1115 	INP_INFO_RLOCK(&tcbinfo);
1116 	if (inp == NULL) {
1117 #ifdef INET6 /* && MAC */
1118 		if (sc->sc_inc.inc_isipv6)
1119 			inp = in6_pcblookup_hash(&tcbinfo,
1120 				&sc->sc_inc.inc6_faddr, sc->sc_inc.inc_fport,
1121 				&sc->sc_inc.inc6_laddr, sc->sc_inc.inc_lport,
1122 				1, NULL);
1123 		else
1124 #endif /* INET6 */
1125 			inp = in_pcblookup_hash(&tcbinfo,
1126 				sc->sc_inc.inc_faddr, sc->sc_inc.inc_fport,
1127 				sc->sc_inc.inc_laddr, sc->sc_inc.inc_lport,
1128 				1, NULL);
1129 		if (inp == NULL) {
1130 			m_freem(m);
1131 			INP_INFO_RUNLOCK(&tcbinfo);
1132 			return (ESHUTDOWN);
1133 		}
1134 	}
1135 	INP_LOCK(inp);
1136 	if (!inp->inp_socket->so_options & SO_ACCEPTCONN) {
1137 		m_freem(m);
1138 		INP_UNLOCK(inp);
1139 		INP_INFO_RUNLOCK(&tcbinfo);
1140 		return (ESHUTDOWN);
1141 	}
1142 	mac_create_mbuf_from_inpcb(inp, m);
1143 	INP_UNLOCK(inp);
1144 	INP_INFO_RUNLOCK(&tcbinfo);
1145 #endif /* MAC */
1146 
1147 #ifdef INET6
1148 	if (sc->sc_inc.inc_isipv6) {
1149 		ip6 = mtod(m, struct ip6_hdr *);
1150 		ip6->ip6_vfc = IPV6_VERSION;
1151 		ip6->ip6_nxt = IPPROTO_TCP;
1152 		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1153 		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1154 		ip6->ip6_plen = htons(tlen - hlen);
1155 		/* ip6_hlim is set after checksum */
1156 		ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
1157 		ip6->ip6_flow |= sc->sc_flowlabel;
1158 
1159 		th = (struct tcphdr *)(ip6 + 1);
1160 	} else
1161 #endif
1162 	{
1163 		ip = mtod(m, struct ip *);
1164 		ip->ip_v = IPVERSION;
1165 		ip->ip_hl = sizeof(struct ip) >> 2;
1166 		ip->ip_len = tlen;
1167 		ip->ip_id = 0;
1168 		ip->ip_off = 0;
1169 		ip->ip_sum = 0;
1170 		ip->ip_p = IPPROTO_TCP;
1171 		ip->ip_src = sc->sc_inc.inc_laddr;
1172 		ip->ip_dst = sc->sc_inc.inc_faddr;
1173 		ip->ip_ttl = sc->sc_ip_ttl;
1174 		ip->ip_tos = sc->sc_ip_tos;
1175 
1176 		/*
1177 		 * See if we should do MTU discovery.  Route lookups are
1178 		 * expensive, so we will only unset the DF bit if:
1179 		 *
1180 		 *	1) path_mtu_discovery is disabled
1181 		 *	2) the SCF_UNREACH flag has been set
1182 		 */
1183 		if (path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1184 		       ip->ip_off |= IP_DF;
1185 
1186 		th = (struct tcphdr *)(ip + 1);
1187 	}
1188 	th->th_sport = sc->sc_inc.inc_lport;
1189 	th->th_dport = sc->sc_inc.inc_fport;
1190 
1191 	th->th_seq = htonl(sc->sc_iss);
1192 	th->th_ack = htonl(sc->sc_irs + 1);
1193 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1194 	th->th_x2 = 0;
1195 	th->th_flags = TH_SYN|TH_ACK;
1196 	th->th_win = htons(sc->sc_wnd);
1197 	th->th_urp = 0;
1198 
1199 	/* Tack on the TCP options. */
1200 	if (optlen != 0) {
1201 		optp = (u_int8_t *)(th + 1);
1202 		*optp++ = TCPOPT_MAXSEG;
1203 		*optp++ = TCPOLEN_MAXSEG;
1204 		*optp++ = (mssopt >> 8) & 0xff;
1205 		*optp++ = mssopt & 0xff;
1206 
1207 		if (sc->sc_flags & SCF_WINSCALE) {
1208 			*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1209 			    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1210 			    sc->sc_requested_r_scale);
1211 			optp += 4;
1212 		}
1213 
1214 		if (sc->sc_flags & SCF_TIMESTAMP) {
1215 			u_int32_t *lp = (u_int32_t *)(optp);
1216 
1217 			/* Form timestamp option per appendix A of RFC 1323. */
1218 			*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1219 			if (sc->sc_ts)
1220 				*lp++ = htonl(sc->sc_ts);
1221 			else
1222 				*lp++ = htonl(ticks);
1223 			*lp   = htonl(sc->sc_tsreflect);
1224 			optp += TCPOLEN_TSTAMP_APPA;
1225 		}
1226 
1227 #ifdef TCP_SIGNATURE
1228 		/*
1229 		 * Handle TCP-MD5 passive opener response.
1230 		 */
1231 		if (sc->sc_flags & SCF_SIGNATURE) {
1232 			u_int8_t *bp = optp;
1233 			int i;
1234 
1235 			*bp++ = TCPOPT_SIGNATURE;
1236 			*bp++ = TCPOLEN_SIGNATURE;
1237 			for (i = 0; i < TCP_SIGLEN; i++)
1238 				*bp++ = 0;
1239 			tcp_signature_compute(m, sizeof(struct ip), 0, optlen,
1240 			    optp + 2, IPSEC_DIR_OUTBOUND);
1241 			optp += TCPOLEN_SIGNATURE;
1242 		}
1243 #endif /* TCP_SIGNATURE */
1244 
1245 		if (sc->sc_flags & SCF_SACK) {
1246 			*optp++ = TCPOPT_SACK_PERMITTED;
1247 			*optp++ = TCPOLEN_SACK_PERMITTED;
1248 		}
1249 
1250 		{
1251 			/* Pad TCP options to a 4 byte boundary */
1252 			int padlen = optlen - (optp - (u_int8_t *)(th + 1));
1253 			while (padlen-- > 0)
1254 				*optp++ = TCPOPT_EOL;
1255 		}
1256 	}
1257 
1258 #ifdef INET6
1259 	if (sc->sc_inc.inc_isipv6) {
1260 		th->th_sum = 0;
1261 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1262 		ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
1263 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1264 	} else
1265 #endif
1266 	{
1267 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1268 		    htons(tlen - hlen + IPPROTO_TCP));
1269 		m->m_pkthdr.csum_flags = CSUM_TCP;
1270 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1271 		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
1272 	}
1273 	return (error);
1274 }
1275 
1276 /*
1277  * The purpose of SYN cookies is to avoid keeping track of all SYN's we
1278  * receive and to be able to handle SYN floods from bogus source addresses
1279  * (where we will never receive any reply).  SYN floods try to exhaust all
1280  * our memory and available slots in the SYN cache table to cause a denial
1281  * of service to legitimate users of the local host.
1282  *
1283  * The idea of SYN cookies is to encode and include all necessary information
1284  * about the connection setup state within the SYN-ACK we send back and thus
1285  * to get along without keeping any local state until the ACK to the SYN-ACK
1286  * arrives (if ever).  Everything we need to know should be available from
1287  * the information we encoded in the SYN-ACK.
1288  *
1289  * More information about the theory behind SYN cookies and its first
1290  * discussion and specification can be found at:
1291  *  http://cr.yp.to/syncookies.html    (overview)
1292  *  http://cr.yp.to/syncookies/archive (gory details)
1293  *
1294  * This implementation extends the orginal idea and first implementation
1295  * of FreeBSD by using not only the initial sequence number field to store
1296  * information but also the timestamp field if present.  This way we can
1297  * keep track of the entire state we need to know to recreate the session in
1298  * its original form.  Almost all TCP speakers implement RFC1323 timestamps
1299  * these days.  For those that do not we still have to live with the known
1300  * shortcomings of the ISN only SYN cookies.
1301  *
1302  * Cookie layers:
1303  *
1304  * Initial sequence number we send:
1305  * 31|................................|0
1306  *    DDDDDDDDDDDDDDDDDDDDDDDDDMMMRRRP
1307  *    D = MD5 Digest (first dword)
1308  *    M = MSS index
1309  *    R = Rotation of secret
1310  *    P = Odd or Even secret
1311  *
1312  * The MD5 Digest is computed with over following parameters:
1313  *  a) randomly rotated secret
1314  *  b) struct in_conninfo containing the remote/local ip/port (IPv4&IPv6)
1315  *  c) the received initial sequence number from remote host
1316  *  d) the rotation offset and odd/even bit
1317  *
1318  * Timestamp we send:
1319  * 31|................................|0
1320  *    DDDDDDDDDDDDDDDDDDDDDDSSSSRRRRA5
1321  *    D = MD5 Digest (third dword) (only as filler)
1322  *    S = Requested send window scale
1323  *    R = Requested receive window scale
1324  *    A = SACK allowed
1325  *    5 = TCP-MD5 enabled (not implemented yet)
1326  *    XORed with MD5 Digest (forth dword)
1327  *
1328  * The timestamp isn't cryptographically secure and doesn't need to be.
1329  * The double use of the MD5 digest dwords ties it to a specific remote/
1330  * local host/port, remote initial sequence number and our local time
1331  * limited secret.  A received timestamp is reverted (XORed) and then
1332  * the contained MD5 dword is compared to the computed one to ensure the
1333  * timestamp belongs to the SYN-ACK we sent.  The other parameters may
1334  * have been tampered with but this isn't different from supplying bogus
1335  * values in the SYN in the first place.
1336  *
1337  * Some problems with SYN cookies remain however:
1338  * Consider the problem of a recreated (and retransmitted) cookie.  If the
1339  * original SYN was accepted, the connection is established.  The second
1340  * SYN is inflight, and if it arrives with an ISN that falls within the
1341  * receive window, the connection is killed.
1342  *
1343  * Notes:
1344  * A heuristic to determine when to accept syn cookies is not necessary.
1345  * An ACK flood would cause the syncookie verification to be attempted,
1346  * but a SYN flood causes syncookies to be generated.  Both are of equal
1347  * cost, so there's no point in trying to optimize the ACK flood case.
1348  * Also, if you don't process certain ACKs for some reason, then all someone
1349  * would have to do is launch a SYN and ACK flood at the same time, which
1350  * would stop cookie verification and defeat the entire purpose of syncookies.
1351  */
1352 static int tcp_sc_msstab[] = { 0, 256, 468, 536, 996, 1452, 1460, 8960 };
1353 
1354 static void
1355 syncookie_generate(struct syncache_head *sch, struct syncache *sc,
1356     u_int32_t *flowlabel)
1357 {
1358 	MD5_CTX ctx;
1359 	u_int32_t md5_buffer[MD5_DIGEST_LENGTH / sizeof(u_int32_t)];
1360 	u_int32_t data;
1361 	u_int32_t *secbits;
1362 	u_int off, pmss, mss;
1363 	int i;
1364 
1365 	SCH_LOCK_ASSERT(sch);
1366 
1367 	/* Which of the two secrets to use. */
1368 	secbits = sch->sch_oddeven ?
1369 			sch->sch_secbits_odd : sch->sch_secbits_even;
1370 
1371 	/* Reseed secret if too old. */
1372 	if (sch->sch_reseed < time_uptime) {
1373 		sch->sch_oddeven = sch->sch_oddeven ? 0 : 1;	/* toggle */
1374 		secbits = sch->sch_oddeven ?
1375 				sch->sch_secbits_odd : sch->sch_secbits_even;
1376 		for (i = 0; i < SYNCOOKIE_SECRET_SIZE; i++)
1377 			secbits[i] = arc4random();
1378 		sch->sch_reseed = time_uptime + SYNCOOKIE_LIFETIME;
1379 	}
1380 
1381 	/* Secret rotation offset. */
1382 	off = sc->sc_iss & 0x7;			/* iss was randomized before */
1383 
1384 	/* Maximum segment size calculation. */
1385 	pmss = max( min(sc->sc_peer_mss, tcp_mssopt(&sc->sc_inc)), tcp_minmss);
1386 	for (mss = sizeof(tcp_sc_msstab) / sizeof(int) - 1; mss > 0; mss--)
1387 		if (tcp_sc_msstab[mss] <= pmss)
1388 			break;
1389 
1390 	/* Fold parameters and MD5 digest into the ISN we will send. */
1391 	data = sch->sch_oddeven;/* odd or even secret, 1 bit */
1392 	data |= off << 1;	/* secret offset, derived from iss, 3 bits */
1393 	data |= mss << 4;	/* mss, 3 bits */
1394 
1395 	MD5Init(&ctx);
1396 	MD5Update(&ctx, ((u_int8_t *)secbits) + off,
1397 	    SYNCOOKIE_SECRET_SIZE * sizeof(*secbits) - off);
1398 	MD5Update(&ctx, secbits, off);
1399 	MD5Update(&ctx, &sc->sc_inc, sizeof(sc->sc_inc));
1400 	MD5Update(&ctx, &sc->sc_irs, sizeof(sc->sc_irs));
1401 	MD5Update(&ctx, &data, sizeof(data));
1402 	MD5Final((u_int8_t *)&md5_buffer, &ctx);
1403 
1404 	data |= (md5_buffer[0] << 7);
1405 	sc->sc_iss = data;
1406 
1407 #ifdef INET6
1408 	*flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1409 #endif
1410 
1411 	/* Additional parameters are stored in the timestamp if present. */
1412 	if (sc->sc_flags & SCF_TIMESTAMP) {
1413 		data =  ((sc->sc_flags & SCF_SIGNATURE) ? 1 : 0); /* TCP-MD5, 1 bit */
1414 		data |= ((sc->sc_flags & SCF_SACK) ? 1 : 0) << 1; /* SACK, 1 bit */
1415 		data |= sc->sc_requested_s_scale << 2;  /* SWIN scale, 4 bits */
1416 		data |= sc->sc_requested_r_scale << 6;  /* RWIN scale, 4 bits */
1417 		data |= md5_buffer[2] << 10;		/* more digest bits */
1418 		data ^= md5_buffer[3];
1419 		sc->sc_ts = data;
1420 		sc->sc_tsoff = data - ticks;		/* after XOR */
1421 	} else
1422 		sc->sc_ts = 0;
1423 
1424 	return;
1425 }
1426 
1427 static struct syncache *
1428 syncookie_lookup(struct in_conninfo *inc, struct syncache_head *sch,
1429     struct syncache *sc, struct tcpopt *to, struct tcphdr *th,
1430     struct socket *so)
1431 {
1432 	MD5_CTX ctx;
1433 	u_int32_t md5_buffer[MD5_DIGEST_LENGTH / sizeof(u_int32_t)];
1434 	u_int32_t data = 0;
1435 	u_int32_t *secbits;
1436 	tcp_seq ack, seq;
1437 	int off, mss, wnd, flags;
1438 
1439 	SCH_LOCK_ASSERT(sch);
1440 
1441 	/*
1442 	 * Pull information out of SYN-ACK/ACK and
1443 	 * revert sequence number advances.
1444 	 */
1445 	ack = th->th_ack - 1;
1446 	seq = th->th_seq - 1;
1447 	off = (ack >> 1) & 0x7;
1448 	mss = (ack >> 4) & 0x7;
1449 	flags = ack & 0x7f;
1450 
1451 	/* Which of the two secrets to use. */
1452 	secbits = (flags & 0x1) ? sch->sch_secbits_odd : sch->sch_secbits_even;
1453 
1454 	/*
1455 	 * The secret wasn't updated for the lifetime of a syncookie,
1456 	 * so this SYN-ACK/ACK is either too old (replay) or totally bogus.
1457 	 */
1458 	if (sch->sch_reseed < time_uptime) {
1459 		return (NULL);
1460 	}
1461 
1462 	/* Recompute the digest so we can compare it. */
1463 	MD5Init(&ctx);
1464 	MD5Update(&ctx, ((u_int8_t *)secbits) + off,
1465 	    SYNCOOKIE_SECRET_SIZE * sizeof(*secbits) - off);
1466 	MD5Update(&ctx, secbits, off);
1467 	MD5Update(&ctx, inc, sizeof(*inc));
1468 	MD5Update(&ctx, &seq, sizeof(seq));
1469 	MD5Update(&ctx, &flags, sizeof(flags));
1470 	MD5Final((u_int8_t *)&md5_buffer, &ctx);
1471 
1472 	/* Does the digest part of or ACK'ed ISS match? */
1473 	if ((ack & (~0x7f)) != (md5_buffer[0] << 7))
1474 		return (NULL);
1475 
1476 	/* Does the digest part of our reflected timestamp match? */
1477 	if (to->to_flags & TOF_TS) {
1478 		data = md5_buffer[3] ^ to->to_tsecr;
1479 		if ((data & (~0x3ff)) != (md5_buffer[2] << 10))
1480 			return (NULL);
1481 	}
1482 
1483 	/* Fill in the syncache values. */
1484 	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1485 	sc->sc_ipopts = NULL;
1486 
1487 	sc->sc_irs = seq;
1488 	sc->sc_iss = ack;
1489 
1490 #ifdef INET6
1491 	if (inc->inc_isipv6) {
1492 		if (sotoinpcb(so)->in6p_flags & IN6P_AUTOFLOWLABEL)
1493 			sc->sc_flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1494 	} else
1495 #endif
1496 	{
1497 		sc->sc_ip_ttl = sotoinpcb(so)->inp_ip_ttl;
1498 		sc->sc_ip_tos = sotoinpcb(so)->inp_ip_tos;
1499 	}
1500 
1501 	/* Additional parameters that were encoded in the timestamp. */
1502 	if (data) {
1503 		sc->sc_flags |= SCF_TIMESTAMP;
1504 		sc->sc_tsreflect = to->to_tsval;
1505 		sc->sc_tsoff = to->to_tsecr - ticks;
1506 		sc->sc_flags |= (data & 0x1) ? SCF_SIGNATURE : 0;
1507 		sc->sc_flags |= ((data >> 1) & 0x1) ? SCF_SACK : 0;
1508 		sc->sc_requested_s_scale = min((data >> 2) & 0xf,
1509 		    TCP_MAX_WINSHIFT);
1510 		sc->sc_requested_r_scale = min((data >> 6) & 0xf,
1511 		    TCP_MAX_WINSHIFT);
1512 		if (sc->sc_requested_s_scale || sc->sc_requested_r_scale)
1513 			sc->sc_flags |= SCF_WINSCALE;
1514 	} else
1515 		sc->sc_flags |= SCF_NOOPT;
1516 
1517 	wnd = sbspace(&so->so_rcv);
1518 	wnd = imax(wnd, 0);
1519 	wnd = imin(wnd, TCP_MAXWIN);
1520 	sc->sc_wnd = wnd;
1521 
1522 	sc->sc_rxmits = 0;
1523 	sc->sc_peer_mss = tcp_sc_msstab[mss];
1524 
1525 	return (sc);
1526 }
1527