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