2 * Copyright (c) 2001 McAfee, Inc.
3 * Copyright (c) 2006 Andre Oppermann, Internet Business Solutions AG
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.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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
36 #include "opt_inet6.h"
37 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 #include "opt_tcp_sack.h"
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/sysctl.h>
47 #include <sys/mutex.h>
48 #include <sys/malloc.h>
52 #include <sys/proc.h> /* for proc0 declaration */
53 #include <sys/random.h>
54 #include <sys/rwlock.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
59 #include <net/route.h>
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/in_var.h>
65 #include <netinet/in_pcb.h>
66 #include <netinet/ip_var.h>
67 #include <netinet/ip_options.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <netinet6/nd6.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/in6_pcb.h>
75 #include <netinet/tcp.h>
77 #include <netinet/tcpip.h>
79 #include <netinet/tcp_fsm.h>
80 #include <netinet/tcp_seq.h>
81 #include <netinet/tcp_timer.h>
82 #include <netinet/tcp_var.h>
84 #include <netinet/tcp_debug.h>
87 #include <netinet6/tcp6_var.h>
91 #include <netinet6/ipsec.h>
93 #include <netinet6/ipsec6.h>
98 #include <netipsec/ipsec.h>
100 #include <netipsec/ipsec6.h>
102 #include <netipsec/key.h>
103 #endif /*FAST_IPSEC*/
105 #include <machine/in_cksum.h>
108 static int tcp_syncookies = 1;
109 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
111 "Use TCP SYN cookies if the syncache overflows");
113 static void syncache_drop(struct syncache *, struct syncache_head *);
114 static void syncache_free(struct syncache *);
115 static void syncache_insert(struct syncache *, struct syncache_head *);
116 struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
117 static int syncache_respond(struct syncache *, struct mbuf *);
118 static struct socket *syncache_socket(struct syncache *, struct socket *,
120 static void syncache_timer(void *);
121 static void syncookie_init(void);
122 static u_int32_t syncookie_generate(struct syncache *, u_int32_t *);
123 static struct syncache
124 *syncookie_lookup(struct in_conninfo *, struct tcphdr *,
128 * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
129 * 3 retransmits corresponds to a timeout of (1 + 2 + 4 + 8 == 15) seconds,
130 * the odds are that the user has given up attempting to connect by then.
132 #define SYNCACHE_MAXREXMTS 3
134 /* Arbitrary values */
135 #define TCP_SYNCACHE_HASHSIZE 512
136 #define TCP_SYNCACHE_BUCKETLIMIT 30
138 struct tcp_syncache {
139 struct syncache_head *hashbase;
144 u_int cache_count; /* XXX: unprotected */
149 static struct tcp_syncache tcp_syncache;
151 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
153 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RDTUN,
154 &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
156 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RDTUN,
157 &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
159 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
160 &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
162 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RDTUN,
163 &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
165 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
166 &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
168 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
170 #define SYNCACHE_HASH(inc, mask) \
171 ((tcp_syncache.hash_secret ^ \
172 (inc)->inc_faddr.s_addr ^ \
173 ((inc)->inc_faddr.s_addr >> 16) ^ \
174 (inc)->inc_fport ^ (inc)->inc_lport) & mask)
176 #define SYNCACHE_HASH6(inc, mask) \
177 ((tcp_syncache.hash_secret ^ \
178 (inc)->inc6_faddr.s6_addr32[0] ^ \
179 (inc)->inc6_faddr.s6_addr32[3] ^ \
180 (inc)->inc_fport ^ (inc)->inc_lport) & mask)
182 #define ENDPTS_EQ(a, b) ( \
183 (a)->ie_fport == (b)->ie_fport && \
184 (a)->ie_lport == (b)->ie_lport && \
185 (a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr && \
186 (a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr \
189 #define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
191 #define SYNCACHE_TIMEOUT(sc, sch, co) do { \
193 (sc)->sc_rxttime = ticks + \
194 TCPTV_RTOBASE * tcp_backoff[(sc)->sc_rxmits - 1]; \
195 if ((sch)->sch_nextc > (sc)->sc_rxttime) \
196 (sch)->sch_nextc = (sc)->sc_rxttime; \
197 if (!TAILQ_EMPTY(&(sch)->sch_bucket) && !(co)) \
198 callout_reset(&(sch)->sch_timer, \
199 (sch)->sch_nextc - ticks, \
200 syncache_timer, (void *)(sch)); \
203 #define SCH_LOCK(sch) mtx_lock(&(sch)->sch_mtx)
204 #define SCH_UNLOCK(sch) mtx_unlock(&(sch)->sch_mtx)
205 #define SCH_LOCK_ASSERT(sch) mtx_assert(&(sch)->sch_mtx, MA_OWNED)
208 * Requires the syncache entry to be already removed from the bucket list.
211 syncache_free(struct syncache *sc)
214 (void) m_free(sc->sc_ipopts);
216 uma_zfree(tcp_syncache.zone, sc);
224 tcp_syncache.cache_count = 0;
225 tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
226 tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
227 tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
228 tcp_syncache.hash_secret = arc4random();
230 TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
231 &tcp_syncache.hashsize);
232 TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
233 &tcp_syncache.bucket_limit);
234 if (!powerof2(tcp_syncache.hashsize) || tcp_syncache.hashsize == 0) {
235 printf("WARNING: syncache hash size is not a power of 2.\n");
236 tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
238 tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
241 tcp_syncache.cache_limit =
242 tcp_syncache.hashsize * tcp_syncache.bucket_limit;
243 TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
244 &tcp_syncache.cache_limit);
246 /* Allocate the hash table. */
247 MALLOC(tcp_syncache.hashbase, struct syncache_head *,
248 tcp_syncache.hashsize * sizeof(struct syncache_head),
249 M_SYNCACHE, M_WAITOK);
251 /* Initialize the hash buckets. */
252 for (i = 0; i < tcp_syncache.hashsize; i++) {
253 TAILQ_INIT(&tcp_syncache.hashbase[i].sch_bucket);
254 mtx_init(&tcp_syncache.hashbase[i].sch_mtx, "tcp_sc_head",
256 callout_init_mtx(&tcp_syncache.hashbase[i].sch_timer,
257 &tcp_syncache.hashbase[i].sch_mtx, 0);
258 tcp_syncache.hashbase[i].sch_length = 0;
263 /* Create the syncache entry zone. */
264 tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
265 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
266 uma_zone_set_max(tcp_syncache.zone, tcp_syncache.cache_limit);
270 * Inserts a syncache entry into the specified bucket row.
271 * Locks and unlocks the syncache_head autonomously.
274 syncache_insert(struct syncache *sc, struct syncache_head *sch)
276 struct syncache *sc2;
281 * Make sure that we don't overflow the per-bucket limit.
282 * If the bucket is full, toss the oldest element.
284 if (sch->sch_length >= tcp_syncache.bucket_limit) {
285 KASSERT(!TAILQ_EMPTY(&sch->sch_bucket),
286 ("sch->sch_length incorrect"));
287 sc2 = TAILQ_LAST(&sch->sch_bucket, sch_head);
288 syncache_drop(sc2, sch);
289 tcpstat.tcps_sc_bucketoverflow++;
292 /* Put it into the bucket. */
293 TAILQ_INSERT_HEAD(&sch->sch_bucket, sc, sc_hash);
296 /* Reinitialize the bucket row's timer. */
297 SYNCACHE_TIMEOUT(sc, sch, 1);
301 tcp_syncache.cache_count++;
302 tcpstat.tcps_sc_added++;
306 * Remove and free entry from syncache bucket row.
307 * Expects locked syncache head.
310 syncache_drop(struct syncache *sc, struct syncache_head *sch)
313 SCH_LOCK_ASSERT(sch);
315 TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
319 tcp_syncache.cache_count--;
323 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
324 * If we have retransmitted an entry the maximum number of times, expire it.
325 * One separate timer for each bucket row.
328 syncache_timer(void *xsch)
330 struct syncache_head *sch = (struct syncache_head *)xsch;
331 struct syncache *sc, *nsc;
334 /* NB: syncache_head has already been locked by the callout. */
335 SCH_LOCK_ASSERT(sch);
337 TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) {
339 * We do not check if the listen socket still exists
340 * and accept the case where the listen socket may be
341 * gone by the time we resend the SYN/ACK. We do
342 * not expect this to happens often. If it does,
343 * then the RST will be sent by the time the remote
344 * host does the SYN/ACK->ACK.
346 if (sc->sc_rxttime >= tick) {
347 if (sc->sc_rxttime < sch->sch_nextc)
348 sch->sch_nextc = sc->sc_rxttime;
352 if (sc->sc_rxmits > tcp_syncache.rexmt_limit) {
353 syncache_drop(sc, sch);
354 tcpstat.tcps_sc_stale++;
358 (void) syncache_respond(sc, NULL);
359 tcpstat.tcps_sc_retransmitted++;
360 SYNCACHE_TIMEOUT(sc, sch, 0);
362 if (!TAILQ_EMPTY(&(sch)->sch_bucket))
363 callout_reset(&(sch)->sch_timer, (sch)->sch_nextc - tick,
364 syncache_timer, (void *)(sch));
368 * Find an entry in the syncache.
369 * Returns always with locked syncache_head plus a matching entry or NULL.
372 syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
375 struct syncache_head *sch;
378 if (inc->inc_isipv6) {
379 sch = &tcp_syncache.hashbase[
380 SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
385 /* Circle through bucket row to find matching entry. */
386 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
387 if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
393 sch = &tcp_syncache.hashbase[
394 SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
399 /* Circle through bucket row to find matching entry. */
400 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
402 if (sc->sc_inc.inc_isipv6)
405 if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
409 SCH_LOCK_ASSERT(*schp);
410 return (NULL); /* always returns with locked sch */
414 * This function is called when we get a RST for a
415 * non-existent connection, so that we can see if the
416 * connection is in the syn cache. If it is, zap it.
419 syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th)
422 struct syncache_head *sch;
424 sc = syncache_lookup(inc, &sch); /* returns locked sch */
425 SCH_LOCK_ASSERT(sch);
430 * If the RST bit is set, check the sequence number to see
431 * if this is a valid reset segment.
433 * In all states except SYN-SENT, all reset (RST) segments
434 * are validated by checking their SEQ-fields. A reset is
435 * valid if its sequence number is in the window.
437 * The sequence number in the reset segment is normally an
438 * echo of our outgoing acknowlegement numbers, but some hosts
439 * send a reset with the sequence number at the rightmost edge
440 * of our receive window, and we have to handle this case.
442 if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
443 SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
444 syncache_drop(sc, sch);
445 tcpstat.tcps_sc_reset++;
452 syncache_badack(struct in_conninfo *inc)
455 struct syncache_head *sch;
457 sc = syncache_lookup(inc, &sch); /* returns locked sch */
458 SCH_LOCK_ASSERT(sch);
460 syncache_drop(sc, sch);
461 tcpstat.tcps_sc_badack++;
467 syncache_unreach(struct in_conninfo *inc, struct tcphdr *th)
470 struct syncache_head *sch;
472 sc = syncache_lookup(inc, &sch); /* returns locked sch */
473 SCH_LOCK_ASSERT(sch);
477 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
478 if (ntohl(th->th_seq) != sc->sc_iss)
482 * If we've rertransmitted 3 times and this is our second error,
483 * we remove the entry. Otherwise, we allow it to continue on.
484 * This prevents us from incorrectly nuking an entry during a
485 * spurious network outage.
489 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxmits < 3 + 1) {
490 sc->sc_flags |= SCF_UNREACH;
493 syncache_drop(sc, sch);
494 tcpstat.tcps_sc_unreach++;
500 * Build a new TCP socket structure from a syncache entry.
502 static struct socket *
503 syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m)
505 struct inpcb *inp = NULL;
510 INP_INFO_WLOCK_ASSERT(&tcbinfo);
513 * Ok, create the full blown connection, and set things up
514 * as they would have been set up if we had created the
515 * connection when the SYN arrived. If we can't create
516 * the connection, abort it.
518 so = sonewconn(lso, SS_ISCONNECTED);
521 * Drop the connection; we will send a RST if the peer
522 * retransmits the ACK,
524 tcpstat.tcps_listendrop++;
529 mac_set_socket_peer_from_mbuf(m, so);
536 /* Insert new socket into PCB hash list. */
537 inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
539 if (sc->sc_inc.inc_isipv6) {
540 inp->in6p_laddr = sc->sc_inc.inc6_laddr;
542 inp->inp_vflag &= ~INP_IPV6;
543 inp->inp_vflag |= INP_IPV4;
545 inp->inp_laddr = sc->sc_inc.inc_laddr;
549 inp->inp_lport = sc->sc_inc.inc_lport;
550 if (in_pcbinshash(inp) != 0) {
552 * Undo the assignments above if we failed to
553 * put the PCB on the hash lists.
556 if (sc->sc_inc.inc_isipv6)
557 inp->in6p_laddr = in6addr_any;
560 inp->inp_laddr.s_addr = INADDR_ANY;
565 /* Copy old policy into new socket's. */
566 if (ipsec_copy_pcbpolicy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
567 printf("syncache_expand: could not copy policy\n");
570 /* Copy old policy into new socket's. */
571 if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
572 printf("syncache_expand: could not copy policy\n");
575 if (sc->sc_inc.inc_isipv6) {
576 struct inpcb *oinp = sotoinpcb(lso);
577 struct in6_addr laddr6;
578 struct sockaddr_in6 sin6;
580 * Inherit socket options from the listening socket.
581 * Note that in6p_inputopts are not (and should not be)
582 * copied, since it stores previously received options and is
583 * used to detect if each new option is different than the
584 * previous one and hence should be passed to a user.
585 * If we copied in6p_inputopts, a user would not be able to
586 * receive options just after calling the accept system call.
588 inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
589 if (oinp->in6p_outputopts)
590 inp->in6p_outputopts =
591 ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
593 sin6.sin6_family = AF_INET6;
594 sin6.sin6_len = sizeof(sin6);
595 sin6.sin6_addr = sc->sc_inc.inc6_faddr;
596 sin6.sin6_port = sc->sc_inc.inc_fport;
597 sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
598 laddr6 = inp->in6p_laddr;
599 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
600 inp->in6p_laddr = sc->sc_inc.inc6_laddr;
601 if (in6_pcbconnect(inp, (struct sockaddr *)&sin6,
603 inp->in6p_laddr = laddr6;
606 /* Override flowlabel from in6_pcbconnect. */
607 inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
608 inp->in6p_flowinfo |= sc->sc_flowlabel;
612 struct in_addr laddr;
613 struct sockaddr_in sin;
615 inp->inp_options = ip_srcroute(m);
616 if (inp->inp_options == NULL) {
617 inp->inp_options = sc->sc_ipopts;
618 sc->sc_ipopts = NULL;
621 sin.sin_family = AF_INET;
622 sin.sin_len = sizeof(sin);
623 sin.sin_addr = sc->sc_inc.inc_faddr;
624 sin.sin_port = sc->sc_inc.inc_fport;
625 bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
626 laddr = inp->inp_laddr;
627 if (inp->inp_laddr.s_addr == INADDR_ANY)
628 inp->inp_laddr = sc->sc_inc.inc_laddr;
629 if (in_pcbconnect(inp, (struct sockaddr *)&sin,
631 inp->inp_laddr = laddr;
636 tp->t_state = TCPS_SYN_RECEIVED;
637 tp->iss = sc->sc_iss;
638 tp->irs = sc->sc_irs;
641 tp->snd_wl1 = sc->sc_irs;
642 tp->rcv_up = sc->sc_irs + 1;
643 tp->rcv_wnd = sc->sc_wnd;
644 tp->rcv_adv += tp->rcv_wnd;
646 tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
647 if (sc->sc_flags & SCF_NOOPT)
648 tp->t_flags |= TF_NOOPT;
649 if (sc->sc_flags & SCF_WINSCALE) {
650 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
651 tp->snd_scale = sc->sc_requested_s_scale;
652 tp->request_r_scale = sc->sc_request_r_scale;
654 if (sc->sc_flags & SCF_TIMESTAMP) {
655 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
656 tp->ts_recent = sc->sc_tsrecent;
657 tp->ts_recent_age = ticks;
660 if (sc->sc_flags & SCF_SIGNATURE)
661 tp->t_flags |= TF_SIGNATURE;
663 if (sc->sc_flags & SCF_SACK) {
665 tp->t_flags |= TF_SACK_PERMIT;
669 * Set up MSS and get cached values from tcp_hostcache.
670 * This might overwrite some of the defaults we just set.
672 tcp_mss(tp, sc->sc_peer_mss);
675 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
677 if (sc->sc_rxmits > 1)
678 tp->snd_cwnd = tp->t_maxseg;
679 callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
683 tcpstat.tcps_accepts++;
695 * This function gets called when we receive an ACK for a
696 * socket in the LISTEN state. We look up the connection
697 * in the syncache, and if its there, we pull it out of
698 * the cache and turn it into a full-blown connection in
699 * the SYN-RECEIVED state.
702 syncache_expand(struct in_conninfo *inc, struct tcphdr *th,
703 struct socket **lsop, struct mbuf *m)
706 struct syncache_head *sch;
710 * Global TCP locks are held because we manipulate the PCB lists
711 * and create a new socket.
713 INP_INFO_WLOCK_ASSERT(&tcbinfo);
715 sc = syncache_lookup(inc, &sch); /* returns locked sch */
716 SCH_LOCK_ASSERT(sch);
719 * There is no syncache entry, so see if this ACK is
720 * a returning syncookie. To do this, first:
721 * A. See if this socket has had a syncache entry dropped in
722 * the past. We don't want to accept a bogus syncookie
723 * if we've never received a SYN.
724 * B. check that the syncookie is valid. If it is, then
725 * cobble up a fake syncache entry, and return.
732 sc = syncookie_lookup(inc, th, *lsop);
735 tcpstat.tcps_sc_recvcookie++;
737 /* Pull out the entry to unlock the bucket row. */
738 TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
744 * If seg contains an ACK, but not for our SYN/ACK, send a RST.
746 if (th->th_ack != sc->sc_iss + 1)
749 so = syncache_socket(sc, *lsop, m);
754 /* XXXjlemon check this - is this correct? */
755 (void) tcp_respond(NULL, m, m, th,
756 th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
758 m_freem(m); /* XXX: only needed for above */
759 tcpstat.tcps_sc_aborted++;
761 syncache_insert(sc, sch); /* try again later */
766 tcpstat.tcps_sc_completed++;
778 * Given a LISTEN socket and an inbound SYN request, add
779 * this to the syn cache, and send back a segment:
780 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
783 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
784 * Doing so would require that we hold onto the data and deliver it
785 * to the application. However, if we are the target of a SYN-flood
786 * DoS attack, an attacker could send data which would eventually
787 * consume all available buffer space if it were ACKed. By not ACKing
788 * the data, we avoid this DoS scenario.
791 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
792 struct inpcb *inp, struct socket **lsop, struct mbuf *m)
796 struct syncache *sc = NULL;
797 struct syncache_head *sch;
798 struct mbuf *ipopts = NULL;
800 int win, sb_hiwat, ip_ttl, ip_tos;
802 int autoflowlabel = 0;
805 INP_INFO_WLOCK_ASSERT(&tcbinfo);
806 INP_LOCK_ASSERT(inp); /* listen socket */
809 * Combine all so/tp operations very early to drop the INP lock as
816 if (inc->inc_isipv6 &&
817 (inp->in6p_flags & IN6P_AUTOFLOWLABEL))
820 ip_ttl = inp->inp_ip_ttl;
821 ip_tos = inp->inp_ip_tos;
822 win = sbspace(&so->so_rcv);
823 sb_hiwat = so->so_rcv.sb_hiwat;
824 if (tp->t_flags & TF_NOOPT)
825 sc->sc_flags = SCF_NOOPT;
831 INP_INFO_WUNLOCK(&tcbinfo);
834 * Remember the IP options, if any.
837 if (!inc->inc_isipv6)
839 ipopts = ip_srcroute(m);
842 * See if we already have an entry for this connection.
843 * If we do, resend the SYN,ACK, and reset the retransmit timer.
845 * XXX: should the syncache be re-initialized with the contents
846 * of the new SYN here (which may have different options?)
848 sc = syncache_lookup(inc, &sch); /* returns locked entry */
849 SCH_LOCK_ASSERT(sch);
851 tcpstat.tcps_sc_dupsyn++;
854 * If we were remembering a previous source route,
855 * forget it and use the new one we've been given.
858 (void) m_free(sc->sc_ipopts);
859 sc->sc_ipopts = ipopts;
862 * Update timestamp if present.
864 if (sc->sc_flags & SCF_TIMESTAMP)
865 sc->sc_tsrecent = to->to_tsval;
866 if (syncache_respond(sc, m) == 0) {
867 SYNCACHE_TIMEOUT(sc, sch, 1);
868 tcpstat.tcps_sndacks++;
869 tcpstat.tcps_sndtotal++;
875 sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
878 * The zone allocator couldn't provide more entries.
879 * Treat this as if the cache was full; drop the oldest
880 * entry and insert the new one.
882 tcpstat.tcps_sc_zonefail++;
883 sc = TAILQ_LAST(&sch->sch_bucket, sch_head);
884 syncache_drop(sc, sch);
886 sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
889 (void) m_free(ipopts);
896 * Fill in the syncache values.
898 sc->sc_ipopts = ipopts;
899 sc->sc_inc.inc_fport = inc->inc_fport;
900 sc->sc_inc.inc_lport = inc->inc_lport;
902 sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
903 if (inc->inc_isipv6) {
904 sc->sc_inc.inc6_faddr = inc->inc6_faddr;
905 sc->sc_inc.inc6_laddr = inc->inc6_laddr;
909 sc->sc_inc.inc_faddr = inc->inc_faddr;
910 sc->sc_inc.inc_laddr = inc->inc_laddr;
911 sc->sc_ip_tos = ip_tos;
912 sc->sc_ip_ttl = ip_ttl;
914 sc->sc_irs = th->th_seq;
916 sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
917 sc->sc_flowlabel = 0;
918 if (tcp_syncookies) {
919 sc->sc_iss = syncookie_generate(sc, &flowtmp);
922 sc->sc_flowlabel = flowtmp & IPV6_FLOWLABEL_MASK;
925 sc->sc_iss = arc4random();
929 (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
934 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
935 * win was derived from socket earlier in the function.
938 win = imin(win, TCP_MAXWIN);
941 if (tcp_do_rfc1323) {
943 * A timestamp received in a SYN makes
944 * it ok to send timestamp requests and replies.
946 if (to->to_flags & TOF_TS) {
947 sc->sc_tsrecent = to->to_tsval;
948 sc->sc_flags |= SCF_TIMESTAMP;
950 if (to->to_flags & TOF_SCALE) {
953 /* Compute proper scaling value from buffer space */
954 while (wscale < TCP_MAX_WINSHIFT &&
955 (TCP_MAXWIN << wscale) < sb_hiwat)
957 sc->sc_request_r_scale = wscale;
958 sc->sc_requested_s_scale = to->to_requested_s_scale;
959 sc->sc_flags |= SCF_WINSCALE;
964 * If listening socket requested TCP digests, and received SYN
965 * contains the option, flag this in the syncache so that
966 * syncache_respond() will do the right thing with the SYN+ACK.
967 * XXX: Currently we always record the option by default and will
968 * attempt to use it in syncache_respond().
970 if (to->to_flags & TOF_SIGNATURE)
971 sc->sc_flags |= SCF_SIGNATURE;
974 if (to->to_flags & TOF_SACK)
975 sc->sc_flags |= SCF_SACK;
978 * Do a standard 3-way handshake.
980 if (syncache_respond(sc, m) == 0) {
981 syncache_insert(sc, sch); /* locks and unlocks sch */
982 tcpstat.tcps_sndacks++;
983 tcpstat.tcps_sndtotal++;
986 tcpstat.tcps_sc_dropped++;
995 syncache_respond(struct syncache *sc, struct mbuf *m)
999 u_int16_t tlen, hlen, mssopt;
1000 struct ip *ip = NULL;
1003 struct ip6_hdr *ip6 = NULL;
1006 struct inpcb *inp = NULL;
1011 (sc->sc_inc.inc_isipv6) ? sizeof(struct ip6_hdr) :
1015 KASSERT((&sc->sc_inc) != NULL, ("syncache_respond with NULL in_conninfo pointer"));
1017 /* Determine MSS we advertize to other end of connection. */
1018 mssopt = tcp_mssopt(&sc->sc_inc);
1020 /* Compute the size of the TCP options. */
1021 if (sc->sc_flags & SCF_NOOPT) {
1024 optlen = TCPOLEN_MAXSEG +
1025 ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
1026 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
1027 #ifdef TCP_SIGNATURE
1028 if (sc->sc_flags & SCF_SIGNATURE)
1029 optlen += TCPOLEN_SIGNATURE;
1031 if (sc->sc_flags & SCF_SACK)
1032 optlen += TCPOLEN_SACK_PERMITTED;
1033 optlen = roundup2(optlen, 4);
1035 tlen = hlen + sizeof(struct tcphdr) + optlen;
1038 * XXX: Assume that the entire packet will fit in a header mbuf.
1040 KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
1042 /* Create the IP+TCP header from scratch. */
1046 m = m_gethdr(M_DONTWAIT, MT_DATA);
1049 m->m_data += max_linkhdr;
1051 m->m_pkthdr.len = tlen;
1052 m->m_pkthdr.rcvif = NULL;
1056 * For MAC look up the inpcb to get access to the label information.
1057 * We don't store the inpcb pointer in struct syncache to make locking
1058 * less complicated and to save locking operations. However for MAC
1059 * this gives a slight overhead as we have to do a full pcblookup here.
1061 INP_INFO_RLOCK(&tcbinfo);
1063 #ifdef INET6 /* && MAC */
1064 if (sc->sc_inc.inc_isipv6)
1065 inp = in6_pcblookup_hash(&tcbinfo,
1066 &sc->sc_inc.inc6_laddr, sc->sc_inc.inc_lport,
1067 &sc->sc_inc.inc6_faddr, sc->sc_inc.inc_fport,
1071 inp = in_pcblookup_hash(&tcbinfo,
1072 sc->sc_inc.inc_laddr, sc->sc_inc.inc_lport,
1073 sc->sc_inc.inc_faddr, sc->sc_inc.inc_fport,
1077 INP_INFO_RUNLOCK(&tcbinfo);
1082 if (!inp->inp_socket->so_options & SO_ACCEPTCONN) {
1085 INP_INFO_RUNLOCK(&tcbinfo);
1088 mac_create_mbuf_from_inpcb(inp, m);
1090 INP_INFO_RUNLOCK(&tcbinfo);
1094 if (sc->sc_inc.inc_isipv6) {
1095 ip6 = mtod(m, struct ip6_hdr *);
1096 ip6->ip6_vfc = IPV6_VERSION;
1097 ip6->ip6_nxt = IPPROTO_TCP;
1098 ip6->ip6_src = sc->sc_inc.inc6_laddr;
1099 ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1100 ip6->ip6_plen = htons(tlen - hlen);
1101 /* ip6_hlim is set after checksum */
1102 ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
1103 ip6->ip6_flow |= sc->sc_flowlabel;
1105 th = (struct tcphdr *)(ip6 + 1);
1109 ip = mtod(m, struct ip *);
1110 ip->ip_v = IPVERSION;
1111 ip->ip_hl = sizeof(struct ip) >> 2;
1116 ip->ip_p = IPPROTO_TCP;
1117 ip->ip_src = sc->sc_inc.inc_laddr;
1118 ip->ip_dst = sc->sc_inc.inc_faddr;
1119 ip->ip_ttl = sc->sc_ip_ttl;
1120 ip->ip_tos = sc->sc_ip_tos;
1123 * See if we should do MTU discovery. Route lookups are
1124 * expensive, so we will only unset the DF bit if:
1126 * 1) path_mtu_discovery is disabled
1127 * 2) the SCF_UNREACH flag has been set
1129 if (path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1130 ip->ip_off |= IP_DF;
1132 th = (struct tcphdr *)(ip + 1);
1134 th->th_sport = sc->sc_inc.inc_lport;
1135 th->th_dport = sc->sc_inc.inc_fport;
1137 th->th_seq = htonl(sc->sc_iss);
1138 th->th_ack = htonl(sc->sc_irs + 1);
1139 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1141 th->th_flags = TH_SYN|TH_ACK;
1142 th->th_win = htons(sc->sc_wnd);
1145 /* Tack on the TCP options. */
1147 optp = (u_int8_t *)(th + 1);
1148 *optp++ = TCPOPT_MAXSEG;
1149 *optp++ = TCPOLEN_MAXSEG;
1150 *optp++ = (mssopt >> 8) & 0xff;
1151 *optp++ = mssopt & 0xff;
1153 if (sc->sc_flags & SCF_WINSCALE) {
1154 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1155 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1156 sc->sc_request_r_scale);
1160 if (sc->sc_flags & SCF_TIMESTAMP) {
1161 u_int32_t *lp = (u_int32_t *)(optp);
1163 /* Form timestamp option per appendix A of RFC 1323. */
1164 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
1165 *lp++ = htonl(ticks);
1166 *lp = htonl(sc->sc_tsrecent);
1167 optp += TCPOLEN_TSTAMP_APPA;
1170 #ifdef TCP_SIGNATURE
1172 * Handle TCP-MD5 passive opener response.
1174 if (sc->sc_flags & SCF_SIGNATURE) {
1175 u_int8_t *bp = optp;
1178 *bp++ = TCPOPT_SIGNATURE;
1179 *bp++ = TCPOLEN_SIGNATURE;
1180 for (i = 0; i < TCP_SIGLEN; i++)
1182 tcp_signature_compute(m, sizeof(struct ip), 0, optlen,
1183 optp + 2, IPSEC_DIR_OUTBOUND);
1184 optp += TCPOLEN_SIGNATURE;
1186 #endif /* TCP_SIGNATURE */
1188 if (sc->sc_flags & SCF_SACK) {
1189 *optp++ = TCPOPT_SACK_PERMITTED;
1190 *optp++ = TCPOLEN_SACK_PERMITTED;
1194 /* Pad TCP options to a 4 byte boundary */
1195 int padlen = optlen - (optp - (u_int8_t *)(th + 1));
1196 while (padlen-- > 0)
1197 *optp++ = TCPOPT_EOL;
1202 if (sc->sc_inc.inc_isipv6) {
1204 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1205 ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
1206 error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1210 th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1211 htons(tlen - hlen + IPPROTO_TCP));
1212 m->m_pkthdr.csum_flags = CSUM_TCP;
1213 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1214 error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
1222 * |. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
1224 * | MD5(laddr,faddr,secret,lport,fport) |. . . . . . .|
1226 * (A): peer mss index
1230 * The values below are chosen to minimize the size of the tcp_secret
1231 * table, as well as providing roughly a 16 second lifetime for the cookie.
1234 #define SYNCOOKIE_WNDBITS 5 /* exposed bits for window indexing */
1235 #define SYNCOOKIE_TIMESHIFT 1 /* scale ticks to window time units */
1237 #define SYNCOOKIE_WNDMASK ((1 << SYNCOOKIE_WNDBITS) - 1)
1238 #define SYNCOOKIE_NSECRETS (1 << SYNCOOKIE_WNDBITS)
1239 #define SYNCOOKIE_TIMEOUT \
1240 (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
1241 #define SYNCOOKIE_DATAMASK ((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
1243 #define SYNCOOKIE_RLOCK(ts) (rw_rlock(&(ts).ts_rwmtx))
1244 #define SYNCOOKIE_RUNLOCK(ts) (rw_runlock(&(ts).ts_rwmtx))
1245 #define SYNCOOKIE_TRY_UPGRADE(ts) (rw_try_upgrade(&(ts).ts_rwmtx))
1246 #define SYNCOOKIE_DOWNGRADE(ts) (rw_downgrade(&(ts).ts_rwmtx))
1249 struct rwlock ts_rwmtx;
1250 u_int ts_expire; /* ticks */
1251 u_int32_t ts_secbits[4];
1252 } tcp_secret[SYNCOOKIE_NSECRETS];
1254 static int tcp_msstab[] = { 0, 536, 1460, 8960 };
1256 static MD5_CTX syn_ctx;
1258 #define MD5Add(v) MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
1261 u_int32_t laddr, faddr;
1262 u_int32_t secbits[4];
1263 u_int16_t lport, fport;
1267 CTASSERT(sizeof(struct md5_add) == 28);
1271 * Consider the problem of a recreated (and retransmitted) cookie. If the
1272 * original SYN was accepted, the connection is established. The second
1273 * SYN is inflight, and if it arrives with an ISN that falls within the
1274 * receive window, the connection is killed.
1276 * However, since cookies have other problems, this may not be worth
1281 syncookie_init(void) {
1284 for (idx = 0; idx < SYNCOOKIE_NSECRETS; idx++) {
1285 rw_init(&(tcp_secret[idx].ts_rwmtx), "tcp_secret");
1290 syncookie_generate(struct syncache *sc, u_int32_t *flowid)
1292 u_int32_t md5_buffer[4];
1297 idx = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
1298 SYNCOOKIE_RLOCK(tcp_secret[idx]);
1299 if (tcp_secret[idx].ts_expire < time_uptime &&
1300 SYNCOOKIE_TRY_UPGRADE(tcp_secret[idx]) ) {
1301 /* need write access */
1302 for (i = 0; i < 4; i++)
1303 tcp_secret[idx].ts_secbits[i] = arc4random();
1304 tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
1305 SYNCOOKIE_DOWNGRADE(tcp_secret[idx]);
1307 for (data = sizeof(tcp_msstab) / sizeof(int) - 1; data > 0; data--)
1308 if (tcp_msstab[data] <= sc->sc_peer_mss)
1310 data = (data << SYNCOOKIE_WNDBITS) | idx;
1311 data ^= sc->sc_irs; /* peer's iss */
1314 if (sc->sc_inc.inc_isipv6) {
1315 MD5Add(sc->sc_inc.inc6_laddr);
1316 MD5Add(sc->sc_inc.inc6_faddr);
1322 add.laddr = sc->sc_inc.inc_laddr.s_addr;
1323 add.faddr = sc->sc_inc.inc_faddr.s_addr;
1325 add.lport = sc->sc_inc.inc_lport;
1326 add.fport = sc->sc_inc.inc_fport;
1327 add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1328 add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1329 add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1330 add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1331 SYNCOOKIE_RUNLOCK(tcp_secret[idx]);
1333 MD5Final((u_char *)&md5_buffer, &syn_ctx);
1334 data ^= (md5_buffer[0] & ~SYNCOOKIE_WNDMASK);
1335 *flowid = md5_buffer[1];
1339 static struct syncache *
1340 syncookie_lookup(struct in_conninfo *inc, struct tcphdr *th, struct socket *so)
1342 u_int32_t md5_buffer[4];
1343 struct syncache *sc;
1348 data = (th->th_ack - 1) ^ (th->th_seq - 1); /* remove ISS */
1349 idx = data & SYNCOOKIE_WNDMASK;
1350 rw_rlock(&(tcp_secret[idx].ts_rwmtx));
1351 SYNCOOKIE_RLOCK(tcp_secret[idx]);
1352 if (tcp_secret[idx].ts_expire < ticks ||
1353 sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks) {
1354 SYNCOOKIE_RUNLOCK(tcp_secret[idx]);
1359 if (inc->inc_isipv6) {
1360 MD5Add(inc->inc6_laddr);
1361 MD5Add(inc->inc6_faddr);
1367 add.laddr = inc->inc_laddr.s_addr;
1368 add.faddr = inc->inc_faddr.s_addr;
1370 add.lport = inc->inc_lport;
1371 add.fport = inc->inc_fport;
1372 add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1373 add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1374 add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1375 add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1376 SYNCOOKIE_RUNLOCK(tcp_secret[idx]);
1378 MD5Final((u_char *)&md5_buffer, &syn_ctx);
1379 data ^= md5_buffer[0];
1380 if ((data & ~SYNCOOKIE_DATAMASK) != 0)
1382 data = data >> SYNCOOKIE_WNDBITS;
1384 sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT | M_ZERO);
1388 * Fill in the syncache values.
1389 * XXX: duplicate code from syncache_add
1391 sc->sc_ipopts = NULL;
1392 sc->sc_inc.inc_fport = inc->inc_fport;
1393 sc->sc_inc.inc_lport = inc->inc_lport;
1395 sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1396 if (inc->inc_isipv6) {
1397 sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1398 sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1399 if (sotoinpcb(so)->in6p_flags & IN6P_AUTOFLOWLABEL)
1400 sc->sc_flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1404 sc->sc_inc.inc_faddr = inc->inc_faddr;
1405 sc->sc_inc.inc_laddr = inc->inc_laddr;
1406 sc->sc_ip_ttl = sotoinpcb(so)->inp_ip_ttl;
1407 sc->sc_ip_tos = sotoinpcb(so)->inp_ip_tos;
1409 sc->sc_irs = th->th_seq - 1;
1410 sc->sc_iss = th->th_ack - 1;
1411 wnd = sbspace(&so->so_rcv);
1413 wnd = imin(wnd, TCP_MAXWIN);
1417 sc->sc_peer_mss = tcp_msstab[data];