The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netinet/tcp_syncache.c

Version: -  FREEBSD  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 2001 Networks Associates Technology, Inc.
    3  * All rights reserved.
    4  *
    5  * This software was developed for the FreeBSD Project by Jonathan Lemon
    6  * and NAI Labs, the Security Research Division of Network Associates, Inc.
    7  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
    8  * DARPA CHATS research program.
    9  *
   10  * Redistribution and use in source and binary forms, with or without
   11  * modification, are permitted provided that the following conditions
   12  * are met:
   13  * 1. Redistributions of source code must retain the above copyright
   14  *    notice, this list of conditions and the following disclaimer.
   15  * 2. Redistributions in binary form must reproduce the above copyright
   16  *    notice, this list of conditions and the following disclaimer in the
   17  *    documentation and/or other materials provided with the distribution.
   18  * 3. The name of the author may not be used to endorse or promote
   19  *    products derived from this software without specific prior written
   20  *    permission.
   21  *
   22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   32  * SUCH DAMAGE.
   33  *
   34  * $FreeBSD: releng/5.3/sys/netinet/tcp_syncache.c 136588 2004-10-16 08:43:07Z cvs2svn $
   35  */
   36 
   37 #include "opt_inet.h"
   38 #include "opt_inet6.h"
   39 #include "opt_ipsec.h"
   40 #include "opt_mac.h"
   41 #include "opt_tcpdebug.h"
   42 #include "opt_tcp_sack.h"
   43 
   44 #include <sys/param.h>
   45 #include <sys/systm.h>
   46 #include <sys/kernel.h>
   47 #include <sys/sysctl.h>
   48 #include <sys/malloc.h>
   49 #include <sys/mac.h>
   50 #include <sys/mbuf.h>
   51 #include <sys/md5.h>
   52 #include <sys/proc.h>           /* for proc0 declaration */
   53 #include <sys/random.h>
   54 #include <sys/socket.h>
   55 #include <sys/socketvar.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 #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 #ifdef TCPDEBUG
   75 #include <netinet/tcpip.h>
   76 #endif
   77 #include <netinet/tcp_fsm.h>
   78 #include <netinet/tcp_seq.h>
   79 #include <netinet/tcp_timer.h>
   80 #include <netinet/tcp_var.h>
   81 #ifdef TCPDEBUG
   82 #include <netinet/tcp_debug.h>
   83 #endif
   84 #ifdef INET6
   85 #include <netinet6/tcp6_var.h>
   86 #endif
   87 
   88 #ifdef IPSEC
   89 #include <netinet6/ipsec.h>
   90 #ifdef INET6
   91 #include <netinet6/ipsec6.h>
   92 #endif
   93 #endif /*IPSEC*/
   94 
   95 #ifdef FAST_IPSEC
   96 #include <netipsec/ipsec.h>
   97 #ifdef INET6
   98 #include <netipsec/ipsec6.h>
   99 #endif
  100 #include <netipsec/key.h>
  101 #endif /*FAST_IPSEC*/
  102 
  103 #include <machine/in_cksum.h>
  104 #include <vm/uma.h>
  105 
  106 static int tcp_syncookies = 1;
  107 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
  108     &tcp_syncookies, 0,
  109     "Use TCP SYN cookies if the syncache overflows");
  110 
  111 static void      syncache_drop(struct syncache *, struct syncache_head *);
  112 static void      syncache_free(struct syncache *);
  113 static void      syncache_insert(struct syncache *, struct syncache_head *);
  114 struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
  115 #ifdef TCPDEBUG
  116 static int       syncache_respond(struct syncache *, struct mbuf *, struct socket *);
  117 #else
  118 static int       syncache_respond(struct syncache *, struct mbuf *);
  119 #endif
  120 static struct    socket *syncache_socket(struct syncache *, struct socket *,
  121                     struct mbuf *m);
  122 static void      syncache_timer(void *);
  123 static u_int32_t syncookie_generate(struct syncache *, u_int32_t *);
  124 static struct syncache *syncookie_lookup(struct in_conninfo *,
  125                     struct tcphdr *, struct socket *);
  126 
  127 /*
  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.
  131  */
  132 #define SYNCACHE_MAXREXMTS              3
  133 
  134 /* Arbitrary values */
  135 #define TCP_SYNCACHE_HASHSIZE           512
  136 #define TCP_SYNCACHE_BUCKETLIMIT        30
  137 
  138 struct tcp_syncache {
  139         struct  syncache_head *hashbase;
  140         uma_zone_t zone;
  141         u_int   hashsize;
  142         u_int   hashmask;
  143         u_int   bucket_limit;
  144         u_int   cache_count;
  145         u_int   cache_limit;
  146         u_int   rexmt_limit;
  147         u_int   hash_secret;
  148         TAILQ_HEAD(, syncache) timerq[SYNCACHE_MAXREXMTS + 1];
  149         struct  callout tt_timerq[SYNCACHE_MAXREXMTS + 1];
  150 };
  151 static struct tcp_syncache tcp_syncache;
  152 
  153 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
  154 
  155 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RDTUN,
  156      &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
  157 
  158 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RDTUN,
  159      &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
  160 
  161 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
  162      &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
  163 
  164 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RDTUN,
  165      &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
  166 
  167 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
  168      &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
  169 
  170 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
  171 
  172 #define SYNCACHE_HASH(inc, mask)                                        \
  173         ((tcp_syncache.hash_secret ^                                    \
  174           (inc)->inc_faddr.s_addr ^                                     \
  175           ((inc)->inc_faddr.s_addr >> 16) ^                             \
  176           (inc)->inc_fport ^ (inc)->inc_lport) & mask)
  177 
  178 #define SYNCACHE_HASH6(inc, mask)                                       \
  179         ((tcp_syncache.hash_secret ^                                    \
  180           (inc)->inc6_faddr.s6_addr32[0] ^                              \
  181           (inc)->inc6_faddr.s6_addr32[3] ^                              \
  182           (inc)->inc_fport ^ (inc)->inc_lport) & mask)
  183 
  184 #define ENDPTS_EQ(a, b) (                                               \
  185         (a)->ie_fport == (b)->ie_fport &&                               \
  186         (a)->ie_lport == (b)->ie_lport &&                               \
  187         (a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&                 \
  188         (a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr                    \
  189 )
  190 
  191 #define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
  192 
  193 #define SYNCACHE_TIMEOUT(sc, slot) do {                         \
  194         sc->sc_rxtslot = (slot);                                        \
  195         sc->sc_rxttime = ticks + TCPTV_RTOBASE * tcp_backoff[(slot)];   \
  196         TAILQ_INSERT_TAIL(&tcp_syncache.timerq[(slot)], sc, sc_timerq); \
  197         if (!callout_active(&tcp_syncache.tt_timerq[(slot)]))           \
  198                 callout_reset(&tcp_syncache.tt_timerq[(slot)],          \
  199                     TCPTV_RTOBASE * tcp_backoff[(slot)],                \
  200                     syncache_timer, (void *)((intptr_t)(slot)));        \
  201 } while (0)
  202 
  203 static void
  204 syncache_free(struct syncache *sc)
  205 {
  206         if (sc->sc_ipopts)
  207                 (void) m_free(sc->sc_ipopts);
  208 
  209         uma_zfree(tcp_syncache.zone, sc);
  210 }
  211 
  212 void
  213 syncache_init(void)
  214 {
  215         int i;
  216 
  217         tcp_syncache.cache_count = 0;
  218         tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
  219         tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
  220         tcp_syncache.cache_limit =
  221             tcp_syncache.hashsize * tcp_syncache.bucket_limit;
  222         tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
  223         tcp_syncache.hash_secret = arc4random();
  224 
  225         TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
  226             &tcp_syncache.hashsize);
  227         TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
  228             &tcp_syncache.cache_limit);
  229         TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
  230             &tcp_syncache.bucket_limit);
  231         if (!powerof2(tcp_syncache.hashsize)) {
  232                 printf("WARNING: syncache hash size is not a power of 2.\n");
  233                 tcp_syncache.hashsize = 512;    /* safe default */
  234         }
  235         tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
  236 
  237         /* Allocate the hash table. */
  238         MALLOC(tcp_syncache.hashbase, struct syncache_head *,
  239             tcp_syncache.hashsize * sizeof(struct syncache_head),
  240             M_SYNCACHE, M_WAITOK);
  241 
  242         /* Initialize the hash buckets. */
  243         for (i = 0; i < tcp_syncache.hashsize; i++) {
  244                 TAILQ_INIT(&tcp_syncache.hashbase[i].sch_bucket);
  245                 tcp_syncache.hashbase[i].sch_length = 0;
  246         }
  247 
  248         /* Initialize the timer queues. */
  249         for (i = 0; i <= SYNCACHE_MAXREXMTS; i++) {
  250                 TAILQ_INIT(&tcp_syncache.timerq[i]);
  251                 callout_init(&tcp_syncache.tt_timerq[i],
  252                         debug_mpsafenet ? CALLOUT_MPSAFE : 0);
  253         }
  254 
  255         /*
  256          * Allocate the syncache entries.  Allow the zone to allocate one
  257          * more entry than cache limit, so a new entry can bump out an
  258          * older one.
  259          */
  260         tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
  261             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  262         uma_zone_set_max(tcp_syncache.zone, tcp_syncache.cache_limit);
  263         tcp_syncache.cache_limit -= 1;
  264 }
  265 
  266 static void
  267 syncache_insert(sc, sch)
  268         struct syncache *sc;
  269         struct syncache_head *sch;
  270 {
  271         struct syncache *sc2;
  272         int i;
  273 
  274         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  275 
  276         /*
  277          * Make sure that we don't overflow the per-bucket
  278          * limit or the total cache size limit.
  279          */
  280         if (sch->sch_length >= tcp_syncache.bucket_limit) {
  281                 /*
  282                  * The bucket is full, toss the oldest element.
  283                  */
  284                 sc2 = TAILQ_FIRST(&sch->sch_bucket);
  285                 sc2->sc_tp->ts_recent = ticks;
  286                 syncache_drop(sc2, sch);
  287                 tcpstat.tcps_sc_bucketoverflow++;
  288         } else if (tcp_syncache.cache_count >= tcp_syncache.cache_limit) {
  289                 /*
  290                  * The cache is full.  Toss the oldest entry in the
  291                  * entire cache.  This is the front entry in the
  292                  * first non-empty timer queue with the largest
  293                  * timeout value.
  294                  */
  295                 for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
  296                         sc2 = TAILQ_FIRST(&tcp_syncache.timerq[i]);
  297                         if (sc2 != NULL)
  298                                 break;
  299                 }
  300                 sc2->sc_tp->ts_recent = ticks;
  301                 syncache_drop(sc2, NULL);
  302                 tcpstat.tcps_sc_cacheoverflow++;
  303         }
  304 
  305         /* Initialize the entry's timer. */
  306         SYNCACHE_TIMEOUT(sc, 0);
  307 
  308         /* Put it into the bucket. */
  309         TAILQ_INSERT_TAIL(&sch->sch_bucket, sc, sc_hash);
  310         sch->sch_length++;
  311         tcp_syncache.cache_count++;
  312         tcpstat.tcps_sc_added++;
  313 }
  314 
  315 static void
  316 syncache_drop(sc, sch)
  317         struct syncache *sc;
  318         struct syncache_head *sch;
  319 {
  320         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  321 
  322         if (sch == NULL) {
  323 #ifdef INET6
  324                 if (sc->sc_inc.inc_isipv6) {
  325                         sch = &tcp_syncache.hashbase[
  326                             SYNCACHE_HASH6(&sc->sc_inc, tcp_syncache.hashmask)];
  327                 } else
  328 #endif
  329                 {
  330                         sch = &tcp_syncache.hashbase[
  331                             SYNCACHE_HASH(&sc->sc_inc, tcp_syncache.hashmask)];
  332                 }
  333         }
  334 
  335         TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
  336         sch->sch_length--;
  337         tcp_syncache.cache_count--;
  338 
  339         TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot], sc, sc_timerq);
  340         if (TAILQ_EMPTY(&tcp_syncache.timerq[sc->sc_rxtslot]))
  341                 callout_stop(&tcp_syncache.tt_timerq[sc->sc_rxtslot]);
  342 
  343         syncache_free(sc);
  344 }
  345 
  346 /*
  347  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
  348  * If we have retransmitted an entry the maximum number of times, expire it.
  349  */
  350 static void
  351 syncache_timer(xslot)
  352         void *xslot;
  353 {
  354         intptr_t slot = (intptr_t)xslot;
  355         struct syncache *sc, *nsc;
  356         struct inpcb *inp;
  357 
  358         INP_INFO_WLOCK(&tcbinfo);
  359         if (callout_pending(&tcp_syncache.tt_timerq[slot]) ||
  360             !callout_active(&tcp_syncache.tt_timerq[slot])) {
  361                 /* XXX can this happen? */
  362                 INP_INFO_WUNLOCK(&tcbinfo);
  363                 return;
  364         }
  365         callout_deactivate(&tcp_syncache.tt_timerq[slot]);
  366 
  367         nsc = TAILQ_FIRST(&tcp_syncache.timerq[slot]);
  368         while (nsc != NULL) {
  369                 if (ticks < nsc->sc_rxttime)
  370                         break;
  371                 sc = nsc;
  372                 inp = sc->sc_tp->t_inpcb;
  373                 if (slot == SYNCACHE_MAXREXMTS ||
  374                     slot >= tcp_syncache.rexmt_limit ||
  375                     inp == NULL || inp->inp_gencnt != sc->sc_inp_gencnt) {
  376                         nsc = TAILQ_NEXT(sc, sc_timerq);
  377                         syncache_drop(sc, NULL);
  378                         tcpstat.tcps_sc_stale++;
  379                         continue;
  380                 }
  381                 /*
  382                  * syncache_respond() may call back into the syncache to
  383                  * to modify another entry, so do not obtain the next
  384                  * entry on the timer chain until it has completed.
  385                  */
  386 #ifdef TCPDEBUG
  387                 (void) syncache_respond(sc, NULL, NULL);
  388 #else
  389                 (void) syncache_respond(sc, NULL);
  390 #endif
  391                 nsc = TAILQ_NEXT(sc, sc_timerq);
  392                 tcpstat.tcps_sc_retransmitted++;
  393                 TAILQ_REMOVE(&tcp_syncache.timerq[slot], sc, sc_timerq);
  394                 SYNCACHE_TIMEOUT(sc, slot + 1);
  395         }
  396         if (nsc != NULL)
  397                 callout_reset(&tcp_syncache.tt_timerq[slot],
  398                     nsc->sc_rxttime - ticks, syncache_timer, (void *)(slot));
  399         INP_INFO_WUNLOCK(&tcbinfo);
  400 }
  401 
  402 /*
  403  * Find an entry in the syncache.
  404  */
  405 struct syncache *
  406 syncache_lookup(inc, schp)
  407         struct in_conninfo *inc;
  408         struct syncache_head **schp;
  409 {
  410         struct syncache *sc;
  411         struct syncache_head *sch;
  412 
  413         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  414 
  415 #ifdef INET6
  416         if (inc->inc_isipv6) {
  417                 sch = &tcp_syncache.hashbase[
  418                     SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
  419                 *schp = sch;
  420                 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
  421                         if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
  422                                 return (sc);
  423                 }
  424         } else
  425 #endif
  426         {
  427                 sch = &tcp_syncache.hashbase[
  428                     SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
  429                 *schp = sch;
  430                 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
  431 #ifdef INET6
  432                         if (sc->sc_inc.inc_isipv6)
  433                                 continue;
  434 #endif
  435                         if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
  436                                 return (sc);
  437                 }
  438         }
  439         return (NULL);
  440 }
  441 
  442 /*
  443  * This function is called when we get a RST for a
  444  * non-existent connection, so that we can see if the
  445  * connection is in the syn cache.  If it is, zap it.
  446  */
  447 void
  448 syncache_chkrst(inc, th)
  449         struct in_conninfo *inc;
  450         struct tcphdr *th;
  451 {
  452         struct syncache *sc;
  453         struct syncache_head *sch;
  454 
  455         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  456 
  457         sc = syncache_lookup(inc, &sch);
  458         if (sc == NULL)
  459                 return;
  460         /*
  461          * If the RST bit is set, check the sequence number to see
  462          * if this is a valid reset segment.
  463          * RFC 793 page 37:
  464          *   In all states except SYN-SENT, all reset (RST) segments
  465          *   are validated by checking their SEQ-fields.  A reset is
  466          *   valid if its sequence number is in the window.
  467          *
  468          *   The sequence number in the reset segment is normally an
  469          *   echo of our outgoing acknowlegement numbers, but some hosts
  470          *   send a reset with the sequence number at the rightmost edge
  471          *   of our receive window, and we have to handle this case.
  472          */
  473         if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
  474             SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
  475                 syncache_drop(sc, sch);
  476                 tcpstat.tcps_sc_reset++;
  477         }
  478 }
  479 
  480 void
  481 syncache_badack(inc)
  482         struct in_conninfo *inc;
  483 {
  484         struct syncache *sc;
  485         struct syncache_head *sch;
  486 
  487         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  488 
  489         sc = syncache_lookup(inc, &sch);
  490         if (sc != NULL) {
  491                 syncache_drop(sc, sch);
  492                 tcpstat.tcps_sc_badack++;
  493         }
  494 }
  495 
  496 void
  497 syncache_unreach(inc, th)
  498         struct in_conninfo *inc;
  499         struct tcphdr *th;
  500 {
  501         struct syncache *sc;
  502         struct syncache_head *sch;
  503 
  504         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  505 
  506         /* we are called at splnet() here */
  507         sc = syncache_lookup(inc, &sch);
  508         if (sc == NULL)
  509                 return;
  510 
  511         /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
  512         if (ntohl(th->th_seq) != sc->sc_iss)
  513                 return;
  514 
  515         /*
  516          * If we've rertransmitted 3 times and this is our second error,
  517          * we remove the entry.  Otherwise, we allow it to continue on.
  518          * This prevents us from incorrectly nuking an entry during a
  519          * spurious network outage.
  520          *
  521          * See tcp_notify().
  522          */
  523         if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtslot < 3) {
  524                 sc->sc_flags |= SCF_UNREACH;
  525                 return;
  526         }
  527         syncache_drop(sc, sch);
  528         tcpstat.tcps_sc_unreach++;
  529 }
  530 
  531 /*
  532  * Build a new TCP socket structure from a syncache entry.
  533  */
  534 static struct socket *
  535 syncache_socket(sc, lso, m)
  536         struct syncache *sc;
  537         struct socket *lso;
  538         struct mbuf *m;
  539 {
  540         struct inpcb *inp = NULL;
  541         struct socket *so;
  542         struct tcpcb *tp;
  543 
  544         NET_ASSERT_GIANT();
  545         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  546 
  547         /*
  548          * Ok, create the full blown connection, and set things up
  549          * as they would have been set up if we had created the
  550          * connection when the SYN arrived.  If we can't create
  551          * the connection, abort it.
  552          */
  553         so = sonewconn(lso, SS_ISCONNECTED);
  554         if (so == NULL) {
  555                 /*
  556                  * Drop the connection; we will send a RST if the peer
  557                  * retransmits the ACK,
  558                  */
  559                 tcpstat.tcps_listendrop++;
  560                 goto abort2;
  561         }
  562 #ifdef MAC
  563         SOCK_LOCK(so);
  564         mac_set_socket_peer_from_mbuf(m, so);
  565         SOCK_UNLOCK(so);
  566 #endif
  567 
  568         inp = sotoinpcb(so);
  569         INP_LOCK(inp);
  570 
  571         /*
  572          * Insert new socket into hash list.
  573          */
  574         inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
  575 #ifdef INET6
  576         if (sc->sc_inc.inc_isipv6) {
  577                 inp->in6p_laddr = sc->sc_inc.inc6_laddr;
  578         } else {
  579                 inp->inp_vflag &= ~INP_IPV6;
  580                 inp->inp_vflag |= INP_IPV4;
  581 #endif
  582                 inp->inp_laddr = sc->sc_inc.inc_laddr;
  583 #ifdef INET6
  584         }
  585 #endif
  586         inp->inp_lport = sc->sc_inc.inc_lport;
  587         if (in_pcbinshash(inp) != 0) {
  588                 /*
  589                  * Undo the assignments above if we failed to
  590                  * put the PCB on the hash lists.
  591                  */
  592 #ifdef INET6
  593                 if (sc->sc_inc.inc_isipv6)
  594                         inp->in6p_laddr = in6addr_any;
  595                 else
  596 #endif
  597                         inp->inp_laddr.s_addr = INADDR_ANY;
  598                 inp->inp_lport = 0;
  599                 goto abort;
  600         }
  601 #ifdef IPSEC
  602         /* copy old policy into new socket's */
  603         if (ipsec_copy_pcbpolicy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
  604                 printf("syncache_expand: could not copy policy\n");
  605 #endif
  606 #ifdef FAST_IPSEC
  607         /* copy old policy into new socket's */
  608         if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
  609                 printf("syncache_expand: could not copy policy\n");
  610 #endif
  611 #ifdef INET6
  612         if (sc->sc_inc.inc_isipv6) {
  613                 struct inpcb *oinp = sotoinpcb(lso);
  614                 struct in6_addr laddr6;
  615                 struct sockaddr_in6 sin6;
  616                 /*
  617                  * Inherit socket options from the listening socket.
  618                  * Note that in6p_inputopts are not (and should not be)
  619                  * copied, since it stores previously received options and is
  620                  * used to detect if each new option is different than the
  621                  * previous one and hence should be passed to a user.
  622                  * If we copied in6p_inputopts, a user would not be able to
  623                  * receive options just after calling the accept system call.
  624                  */
  625                 inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
  626                 if (oinp->in6p_outputopts)
  627                         inp->in6p_outputopts =
  628                             ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
  629 
  630                 sin6.sin6_family = AF_INET6;
  631                 sin6.sin6_len = sizeof(sin6);
  632                 sin6.sin6_addr = sc->sc_inc.inc6_faddr;
  633                 sin6.sin6_port = sc->sc_inc.inc_fport;
  634                 sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
  635                 laddr6 = inp->in6p_laddr;
  636                 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
  637                         inp->in6p_laddr = sc->sc_inc.inc6_laddr;
  638                 if (in6_pcbconnect(inp, (struct sockaddr *)&sin6,
  639                     thread0.td_ucred)) {
  640                         inp->in6p_laddr = laddr6;
  641                         goto abort;
  642                 }
  643                 /* Override flowlabel from in6_pcbconnect. */
  644                 inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
  645                 inp->in6p_flowinfo |= sc->sc_flowlabel;
  646         } else
  647 #endif
  648         {
  649                 struct in_addr laddr;
  650                 struct sockaddr_in sin;
  651 
  652                 inp->inp_options = ip_srcroute(m);
  653                 if (inp->inp_options == NULL) {
  654                         inp->inp_options = sc->sc_ipopts;
  655                         sc->sc_ipopts = NULL;
  656                 }
  657 
  658                 sin.sin_family = AF_INET;
  659                 sin.sin_len = sizeof(sin);
  660                 sin.sin_addr = sc->sc_inc.inc_faddr;
  661                 sin.sin_port = sc->sc_inc.inc_fport;
  662                 bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
  663                 laddr = inp->inp_laddr;
  664                 if (inp->inp_laddr.s_addr == INADDR_ANY)
  665                         inp->inp_laddr = sc->sc_inc.inc_laddr;
  666                 if (in_pcbconnect(inp, (struct sockaddr *)&sin,
  667                     thread0.td_ucred)) {
  668                         inp->inp_laddr = laddr;
  669                         goto abort;
  670                 }
  671         }
  672 
  673         tp = intotcpcb(inp);
  674         tp->t_state = TCPS_SYN_RECEIVED;
  675         tp->iss = sc->sc_iss;
  676         tp->irs = sc->sc_irs;
  677         tcp_rcvseqinit(tp);
  678         tcp_sendseqinit(tp);
  679         tp->snd_wl1 = sc->sc_irs;
  680         tp->rcv_up = sc->sc_irs + 1;
  681         tp->rcv_wnd = sc->sc_wnd;
  682         tp->rcv_adv += tp->rcv_wnd;
  683 
  684         tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
  685         if (sc->sc_flags & SCF_NOOPT)
  686                 tp->t_flags |= TF_NOOPT;
  687         if (sc->sc_flags & SCF_WINSCALE) {
  688                 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
  689                 tp->requested_s_scale = sc->sc_requested_s_scale;
  690                 tp->request_r_scale = sc->sc_request_r_scale;
  691         }
  692         if (sc->sc_flags & SCF_TIMESTAMP) {
  693                 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
  694                 tp->ts_recent = sc->sc_tsrecent;
  695                 tp->ts_recent_age = ticks;
  696         }
  697         if (sc->sc_flags & SCF_CC) {
  698                 /*
  699                  * Initialization of the tcpcb for transaction;
  700                  *   set SND.WND = SEG.WND,
  701                  *   initialize CCsend and CCrecv.
  702                  */
  703                 tp->t_flags |= TF_REQ_CC|TF_RCVD_CC;
  704                 tp->cc_send = sc->sc_cc_send;
  705                 tp->cc_recv = sc->sc_cc_recv;
  706         }
  707 #ifdef TCP_SIGNATURE
  708         if (sc->sc_flags & SCF_SIGNATURE)
  709                 tp->t_flags |= TF_SIGNATURE;
  710 #endif
  711         if (sc->sc_flags & SCF_SACK) {
  712                 tp->sack_enable = 1;
  713                 tp->t_flags |= TF_SACK_PERMIT;
  714         }
  715         /*
  716          * Set up MSS and get cached values from tcp_hostcache.
  717          * This might overwrite some of the defaults we just set.
  718          */
  719         tcp_mss(tp, sc->sc_peer_mss);
  720 
  721         /*
  722          * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
  723          */
  724         if (sc->sc_rxtslot != 0)
  725                 tp->snd_cwnd = tp->t_maxseg;
  726         callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
  727 
  728         INP_UNLOCK(inp);
  729 
  730         tcpstat.tcps_accepts++;
  731         return (so);
  732 
  733 abort:
  734         INP_UNLOCK(inp);
  735 abort2:
  736         if (so != NULL)
  737                 (void) soabort(so);
  738         return (NULL);
  739 }
  740 
  741 /*
  742  * This function gets called when we receive an ACK for a
  743  * socket in the LISTEN state.  We look up the connection
  744  * in the syncache, and if its there, we pull it out of
  745  * the cache and turn it into a full-blown connection in
  746  * the SYN-RECEIVED state.
  747  */
  748 int
  749 syncache_expand(inc, th, sop, m)
  750         struct in_conninfo *inc;
  751         struct tcphdr *th;
  752         struct socket **sop;
  753         struct mbuf *m;
  754 {
  755         struct syncache *sc;
  756         struct syncache_head *sch;
  757         struct socket *so;
  758 
  759         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  760 
  761         sc = syncache_lookup(inc, &sch);
  762         if (sc == NULL) {
  763                 /*
  764                  * There is no syncache entry, so see if this ACK is
  765                  * a returning syncookie.  To do this, first:
  766                  *  A. See if this socket has had a syncache entry dropped in
  767                  *     the past.  We don't want to accept a bogus syncookie
  768                  *     if we've never received a SYN.
  769                  *  B. check that the syncookie is valid.  If it is, then
  770                  *     cobble up a fake syncache entry, and return.
  771                  */
  772                 if (!tcp_syncookies)
  773                         return (0);
  774                 sc = syncookie_lookup(inc, th, *sop);
  775                 if (sc == NULL)
  776                         return (0);
  777                 sch = NULL;
  778                 tcpstat.tcps_sc_recvcookie++;
  779         }
  780 
  781         /*
  782          * If seg contains an ACK, but not for our SYN/ACK, send a RST.
  783          */
  784         if (th->th_ack != sc->sc_iss + 1)
  785                 return (0);
  786 
  787         so = syncache_socket(sc, *sop, m);
  788         if (so == NULL) {
  789 #if 0
  790 resetandabort:
  791                 /* XXXjlemon check this - is this correct? */
  792                 (void) tcp_respond(NULL, m, m, th,
  793                     th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
  794 #endif
  795                 m_freem(m);                     /* XXX only needed for above */
  796                 tcpstat.tcps_sc_aborted++;
  797         } else
  798                 tcpstat.tcps_sc_completed++;
  799 
  800         if (sch == NULL)
  801                 syncache_free(sc);
  802         else
  803                 syncache_drop(sc, sch);
  804         *sop = so;
  805         return (1);
  806 }
  807 
  808 /*
  809  * Given a LISTEN socket and an inbound SYN request, add
  810  * this to the syn cache, and send back a segment:
  811  *      <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
  812  * to the source.
  813  *
  814  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
  815  * Doing so would require that we hold onto the data and deliver it
  816  * to the application.  However, if we are the target of a SYN-flood
  817  * DoS attack, an attacker could send data which would eventually
  818  * consume all available buffer space if it were ACKed.  By not ACKing
  819  * the data, we avoid this DoS scenario.
  820  */
  821 int
  822 syncache_add(inc, to, th, sop, m)
  823         struct in_conninfo *inc;
  824         struct tcpopt *to;
  825         struct tcphdr *th;
  826         struct socket **sop;
  827         struct mbuf *m;
  828 {
  829         struct tcpcb *tp;
  830         struct socket *so;
  831         struct syncache *sc = NULL;
  832         struct syncache_head *sch;
  833         struct mbuf *ipopts = NULL;
  834         struct rmxp_tao tao;
  835         u_int32_t flowtmp;
  836         int i, win;
  837 
  838         INP_INFO_WLOCK_ASSERT(&tcbinfo);
  839 
  840         so = *sop;
  841         tp = sototcpcb(so);
  842         bzero(&tao, sizeof(tao));
  843 
  844         /*
  845          * Remember the IP options, if any.
  846          */
  847 #ifdef INET6
  848         if (!inc->inc_isipv6)
  849 #endif
  850                 ipopts = ip_srcroute(m);
  851 
  852         /*
  853          * See if we already have an entry for this connection.
  854          * If we do, resend the SYN,ACK, and reset the retransmit timer.
  855          *
  856          * XXX
  857          * should the syncache be re-initialized with the contents
  858          * of the new SYN here (which may have different options?)
  859          */
  860         sc = syncache_lookup(inc, &sch);
  861         if (sc != NULL) {
  862                 tcpstat.tcps_sc_dupsyn++;
  863                 if (ipopts) {
  864                         /*
  865                          * If we were remembering a previous source route,
  866                          * forget it and use the new one we've been given.
  867                          */
  868                         if (sc->sc_ipopts)
  869                                 (void) m_free(sc->sc_ipopts);
  870                         sc->sc_ipopts = ipopts;
  871                 }
  872                 /*
  873                  * Update timestamp if present.
  874                  */
  875                 if (sc->sc_flags & SCF_TIMESTAMP)
  876                         sc->sc_tsrecent = to->to_tsval;
  877                 /*
  878                  * PCB may have changed, pick up new values.
  879                  */
  880                 sc->sc_tp = tp;
  881                 sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
  882 #ifdef TCPDEBUG
  883                 if (syncache_respond(sc, m, so) == 0) {
  884 #else
  885                 if (syncache_respond(sc, m) == 0) {
  886 #endif
  887                         /* NB: guarded by INP_INFO_WLOCK(&tcbinfo) */
  888                         TAILQ_REMOVE(&tcp_syncache.timerq[sc->sc_rxtslot],
  889                             sc, sc_timerq);
  890                         SYNCACHE_TIMEOUT(sc, sc->sc_rxtslot);
  891                         tcpstat.tcps_sndacks++;
  892                         tcpstat.tcps_sndtotal++;
  893                 }
  894                 *sop = NULL;
  895                 return (1);
  896         }
  897 
  898         sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
  899         if (sc == NULL) {
  900                 /*
  901                  * The zone allocator couldn't provide more entries.
  902                  * Treat this as if the cache was full; drop the oldest
  903                  * entry and insert the new one.
  904                  */
  905                 /* NB: guarded by INP_INFO_WLOCK(&tcbinfo) */
  906                 for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
  907                         sc = TAILQ_FIRST(&tcp_syncache.timerq[i]);
  908                         if (sc != NULL)
  909                                 break;
  910                 }
  911                 sc->sc_tp->ts_recent = ticks;
  912                 syncache_drop(sc, NULL);
  913                 tcpstat.tcps_sc_zonefail++;
  914                 sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
  915                 if (sc == NULL) {
  916                         if (ipopts)
  917                                 (void) m_free(ipopts);
  918                         return (0);
  919                 }
  920         }
  921 
  922         /*
  923          * Fill in the syncache values.
  924          */
  925         bzero(sc, sizeof(*sc));
  926         sc->sc_tp = tp;
  927         sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
  928         sc->sc_ipopts = ipopts;
  929         sc->sc_inc.inc_fport = inc->inc_fport;
  930         sc->sc_inc.inc_lport = inc->inc_lport;
  931 #ifdef INET6
  932         sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
  933         if (inc->inc_isipv6) {
  934                 sc->sc_inc.inc6_faddr = inc->inc6_faddr;
  935                 sc->sc_inc.inc6_laddr = inc->inc6_laddr;
  936         } else
  937 #endif
  938         {
  939                 sc->sc_inc.inc_faddr = inc->inc_faddr;
  940                 sc->sc_inc.inc_laddr = inc->inc_laddr;
  941         }
  942         sc->sc_irs = th->th_seq;
  943         sc->sc_flags = 0;
  944         sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
  945         sc->sc_flowlabel = 0;
  946         if (tcp_syncookies) {
  947                 sc->sc_iss = syncookie_generate(sc, &flowtmp);
  948 #ifdef INET6
  949                 if (inc->inc_isipv6 &&
  950                     (sc->sc_tp->t_inpcb->in6p_flags & IN6P_AUTOFLOWLABEL)) {
  951                         sc->sc_flowlabel = flowtmp & IPV6_FLOWLABEL_MASK;
  952                 }
  953 #endif
  954         } else {
  955                 sc->sc_iss = arc4random();
  956 #ifdef INET6
  957                 if (inc->inc_isipv6 &&
  958                     (sc->sc_tp->t_inpcb->in6p_flags & IN6P_AUTOFLOWLABEL)) {
  959                         sc->sc_flowlabel =
  960                             (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
  961                 }
  962 #endif
  963         }
  964 
  965         /* Initial receive window: clip sbspace to [0 .. TCP_MAXWIN] */
  966         win = sbspace(&so->so_rcv);
  967         win = imax(win, 0);
  968         win = imin(win, TCP_MAXWIN);
  969         sc->sc_wnd = win;
  970 
  971         if (tcp_do_rfc1323) {
  972                 /*
  973                  * A timestamp received in a SYN makes
  974                  * it ok to send timestamp requests and replies.
  975                  */
  976                 if (to->to_flags & TOF_TS) {
  977                         sc->sc_tsrecent = to->to_tsval;
  978                         sc->sc_flags |= SCF_TIMESTAMP;
  979                 }
  980                 if (to->to_flags & TOF_SCALE) {
  981                         int wscale = 0;
  982 
  983                         /* Compute proper scaling value from buffer space */
  984                         while (wscale < TCP_MAX_WINSHIFT &&
  985                             (TCP_MAXWIN << wscale) < so->so_rcv.sb_hiwat)
  986                                 wscale++;
  987                         sc->sc_request_r_scale = wscale;
  988                         sc->sc_requested_s_scale = to->to_requested_s_scale;
  989                         sc->sc_flags |= SCF_WINSCALE;
  990                 }
  991         }
  992         if (tcp_do_rfc1644) {
  993                 /*
  994                  * A CC or CC.new option received in a SYN makes
  995                  * it ok to send CC in subsequent segments.
  996                  */
  997                 if (to->to_flags & (TOF_CC|TOF_CCNEW)) {
  998                         sc->sc_cc_recv = to->to_cc;
  999                         sc->sc_cc_send = CC_INC(tcp_ccgen);
 1000                         sc->sc_flags |= SCF_CC;
 1001                 }
 1002         }
 1003         if (tp->t_flags & TF_NOOPT)
 1004                 sc->sc_flags = SCF_NOOPT;
 1005 #ifdef TCP_SIGNATURE
 1006         /*
 1007          * If listening socket requested TCP digests, and received SYN
 1008          * contains the option, flag this in the syncache so that
 1009          * syncache_respond() will do the right thing with the SYN+ACK.
 1010          * XXX Currently we always record the option by default and will
 1011          * attempt to use it in syncache_respond().
 1012          */
 1013         if (to->to_flags & TOF_SIGNATURE)
 1014                 sc->sc_flags = SCF_SIGNATURE;
 1015 #endif
 1016 
 1017         if (to->to_flags & TOF_SACK)
 1018                 sc->sc_flags |= SCF_SACK;
 1019 
 1020         /*
 1021          * XXX
 1022          * We have the option here of not doing TAO (even if the segment
 1023          * qualifies) and instead fall back to a normal 3WHS via the syncache.
 1024          * This allows us to apply synflood protection to TAO-qualifying SYNs
 1025          * also. However, there should be a hueristic to determine when to
 1026          * do this, and is not present at the moment.
 1027          */
 1028 
 1029         /*
 1030          * Perform TAO test on incoming CC (SEG.CC) option, if any.
 1031          * - compare SEG.CC against cached CC from the same host, if any.
 1032          * - if SEG.CC > chached value, SYN must be new and is accepted
 1033          *      immediately: save new CC in the cache, mark the socket
 1034          *      connected, enter ESTABLISHED state, turn on flag to
 1035          *      send a SYN in the next segment.
 1036          *      A virtual advertised window is set in rcv_adv to
 1037          *      initialize SWS prevention.  Then enter normal segment
 1038          *      processing: drop SYN, process data and FIN.
 1039          * - otherwise do a normal 3-way handshake.
 1040          */
 1041         if (tcp_do_rfc1644)
 1042                 tcp_hc_gettao(&sc->sc_inc, &tao);
 1043 
 1044         if ((to->to_flags & TOF_CC) != 0) {
 1045                 if (((tp->t_flags & TF_NOPUSH) != 0) &&
 1046                     sc->sc_flags & SCF_CC && tao.tao_cc != 0 &&
 1047                     CC_GT(to->to_cc, tao.tao_cc)) {
 1048                         sc->sc_rxtslot = 0;
 1049                         so = syncache_socket(sc, *sop, m);
 1050                         if (so != NULL) {
 1051                                 tao.tao_cc = to->to_cc;
 1052                                 tcp_hc_updatetao(&sc->sc_inc, TCP_HC_TAO_CC,
 1053                                                  tao.tao_cc, 0);
 1054                                 *sop = so;
 1055                         }
 1056                         syncache_free(sc);
 1057                         return (so != NULL);
 1058                 }
 1059         } else {
 1060                 /*
 1061                  * No CC option, but maybe CC.NEW: invalidate cached value.
 1062                  */
 1063                 if (tcp_do_rfc1644) {
 1064                         tao.tao_cc = 0;
 1065                         tcp_hc_updatetao(&sc->sc_inc, TCP_HC_TAO_CC,
 1066                                          tao.tao_cc, 0);
 1067                 }
 1068         }
 1069 
 1070         /*
 1071          * TAO test failed or there was no CC option,
 1072          *    do a standard 3-way handshake.
 1073          */
 1074 #ifdef TCPDEBUG
 1075         if (syncache_respond(sc, m, so) == 0) {
 1076 #else
 1077         if (syncache_respond(sc, m) == 0) {
 1078 #endif
 1079                 syncache_insert(sc, sch);
 1080                 tcpstat.tcps_sndacks++;
 1081                 tcpstat.tcps_sndtotal++;
 1082         } else {
 1083                 syncache_free(sc);
 1084                 tcpstat.tcps_sc_dropped++;
 1085         }
 1086         *sop = NULL;
 1087         return (1);
 1088 }
 1089 
 1090 #ifdef TCPDEBUG
 1091 static int
 1092 syncache_respond(sc, m, so)
 1093         struct syncache *sc;
 1094         struct mbuf *m;
 1095         struct socket *so;
 1096 #else
 1097 static int
 1098 syncache_respond(sc, m)
 1099         struct syncache *sc;
 1100         struct mbuf *m;
 1101 #endif
 1102 {
 1103         u_int8_t *optp;
 1104         int optlen, error;
 1105         u_int16_t tlen, hlen, mssopt;
 1106         struct ip *ip = NULL;
 1107         struct tcphdr *th;
 1108         struct inpcb *inp;
 1109 #ifdef INET6
 1110         struct ip6_hdr *ip6 = NULL;
 1111 #endif
 1112 
 1113         hlen =
 1114 #ifdef INET6
 1115                (sc->sc_inc.inc_isipv6) ? sizeof(struct ip6_hdr) :
 1116 #endif
 1117                 sizeof(struct ip);
 1118 
 1119         KASSERT((&sc->sc_inc) != NULL, ("syncache_respond with NULL in_conninfo pointer"));
 1120 
 1121         /* Determine MSS we advertize to other end of connection */
 1122         mssopt = tcp_mssopt(&sc->sc_inc);
 1123 
 1124         /* Compute the size of the TCP options. */
 1125         if (sc->sc_flags & SCF_NOOPT) {
 1126                 optlen = 0;
 1127         } else {
 1128                 optlen = TCPOLEN_MAXSEG +
 1129                     ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
 1130                     ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0) +
 1131                     ((sc->sc_flags & SCF_CC) ? TCPOLEN_CC_APPA * 2 : 0);
 1132 #ifdef TCP_SIGNATURE
 1133                 optlen += (sc->sc_flags & SCF_SIGNATURE) ?
 1134                     TCPOLEN_SIGNATURE + 2 : 0;
 1135 #endif
 1136                 optlen += ((sc->sc_flags & SCF_SACK) ? 4 : 0);
 1137         }
 1138         tlen = hlen + sizeof(struct tcphdr) + optlen;
 1139 
 1140         /*
 1141          * XXX
 1142          * assume that the entire packet will fit in a header mbuf
 1143          */
 1144         KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
 1145 
 1146         /*
 1147          * XXX shouldn't this reuse the mbuf if possible ?
 1148          * Create the IP+TCP header from scratch.
 1149          */
 1150         if (m)
 1151                 m_freem(m);
 1152 
 1153         m = m_gethdr(M_DONTWAIT, MT_HEADER);
 1154         if (m == NULL)
 1155                 return (ENOBUFS);
 1156         m->m_data += max_linkhdr;
 1157         m->m_len = tlen;
 1158         m->m_pkthdr.len = tlen;
 1159         m->m_pkthdr.rcvif = NULL;
 1160         inp = sc->sc_tp->t_inpcb;
 1161         INP_LOCK(inp);
 1162 #ifdef MAC
 1163         mac_create_mbuf_from_inpcb(inp, m);
 1164 #endif
 1165 
 1166 #ifdef INET6
 1167         if (sc->sc_inc.inc_isipv6) {
 1168                 ip6 = mtod(m, struct ip6_hdr *);
 1169                 ip6->ip6_vfc = IPV6_VERSION;
 1170                 ip6->ip6_nxt = IPPROTO_TCP;
 1171                 ip6->ip6_src = sc->sc_inc.inc6_laddr;
 1172                 ip6->ip6_dst = sc->sc_inc.inc6_faddr;
 1173                 ip6->ip6_plen = htons(tlen - hlen);
 1174                 /* ip6_hlim is set after checksum */
 1175                 ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
 1176                 ip6->ip6_flow |= sc->sc_flowlabel;
 1177 
 1178                 th = (struct tcphdr *)(ip6 + 1);
 1179         } else
 1180 #endif
 1181         {
 1182                 ip = mtod(m, struct ip *);
 1183                 ip->ip_v = IPVERSION;
 1184                 ip->ip_hl = sizeof(struct ip) >> 2;
 1185                 ip->ip_len = tlen;
 1186                 ip->ip_id = 0;
 1187                 ip->ip_off = 0;
 1188                 ip->ip_sum = 0;
 1189                 ip->ip_p = IPPROTO_TCP;
 1190                 ip->ip_src = sc->sc_inc.inc_laddr;
 1191                 ip->ip_dst = sc->sc_inc.inc_faddr;
 1192                 ip->ip_ttl = inp->inp_ip_ttl;   /* XXX */
 1193                 ip->ip_tos = inp->inp_ip_tos;   /* XXX */
 1194 
 1195                 /*
 1196                  * See if we should do MTU discovery.  Route lookups are
 1197                  * expensive, so we will only unset the DF bit if:
 1198                  *
 1199                  *      1) path_mtu_discovery is disabled
 1200                  *      2) the SCF_UNREACH flag has been set
 1201                  */
 1202                 if (path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
 1203                        ip->ip_off |= IP_DF;
 1204 
 1205                 th = (struct tcphdr *)(ip + 1);
 1206         }
 1207         th->th_sport = sc->sc_inc.inc_lport;
 1208         th->th_dport = sc->sc_inc.inc_fport;
 1209 
 1210         th->th_seq = htonl(sc->sc_iss);
 1211         th->th_ack = htonl(sc->sc_irs + 1);
 1212         th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
 1213         th->th_x2 = 0;
 1214         th->th_flags = TH_SYN|TH_ACK;
 1215         th->th_win = htons(sc->sc_wnd);
 1216         th->th_urp = 0;
 1217 
 1218         /* Tack on the TCP options. */
 1219         if (optlen != 0) {
 1220                 optp = (u_int8_t *)(th + 1);
 1221                 *optp++ = TCPOPT_MAXSEG;
 1222                 *optp++ = TCPOLEN_MAXSEG;
 1223                 *optp++ = (mssopt >> 8) & 0xff;
 1224                 *optp++ = mssopt & 0xff;
 1225 
 1226                 if (sc->sc_flags & SCF_WINSCALE) {
 1227                         *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
 1228                             TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
 1229                             sc->sc_request_r_scale);
 1230                         optp += 4;
 1231                 }
 1232 
 1233                 if (sc->sc_flags & SCF_TIMESTAMP) {
 1234                         u_int32_t *lp = (u_int32_t *)(optp);
 1235 
 1236                         /* Form timestamp option per appendix A of RFC 1323. */
 1237                         *lp++ = htonl(TCPOPT_TSTAMP_HDR);
 1238                         *lp++ = htonl(ticks);
 1239                         *lp   = htonl(sc->sc_tsrecent);
 1240                         optp += TCPOLEN_TSTAMP_APPA;
 1241                 }
 1242 
 1243                 /*
 1244                  * Send CC and CC.echo if we received CC from our peer.
 1245                  */
 1246                 if (sc->sc_flags & SCF_CC) {
 1247                         u_int32_t *lp = (u_int32_t *)(optp);
 1248 
 1249                         *lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
 1250                         *lp++ = htonl(sc->sc_cc_send);
 1251                         *lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CCECHO));
 1252                         *lp   = htonl(sc->sc_cc_recv);
 1253                         optp += TCPOLEN_CC_APPA * 2;
 1254                 }
 1255 
 1256 #ifdef TCP_SIGNATURE
 1257                 /*
 1258                  * Handle TCP-MD5 passive opener response.
 1259                  */
 1260                 if (sc->sc_flags & SCF_SIGNATURE) {
 1261                         u_int8_t *bp = optp;
 1262                         int i;
 1263 
 1264                         *bp++ = TCPOPT_SIGNATURE;
 1265                         *bp++ = TCPOLEN_SIGNATURE;
 1266                         for (i = 0; i < TCP_SIGLEN; i++)
 1267                                 *bp++ = 0;
 1268                         tcp_signature_compute(m, sizeof(struct ip), 0, optlen,
 1269                             optp + 2, IPSEC_DIR_OUTBOUND);
 1270                         *bp++ = TCPOPT_NOP;
 1271                         *bp++ = TCPOPT_EOL;
 1272                         optp += TCPOLEN_SIGNATURE + 2;
 1273                 }
 1274 #endif /* TCP_SIGNATURE */
 1275 
 1276         if (sc->sc_flags & SCF_SACK) {
 1277                 *(u_int32_t *)optp = htonl(TCPOPT_SACK_PERMIT_HDR);
 1278                 optp += 4;
 1279         }
 1280         }
 1281 
 1282 #ifdef INET6
 1283         if (sc->sc_inc.inc_isipv6) {
 1284                 th->th_sum = 0;
 1285                 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
 1286                 ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
 1287                 error = ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
 1288         } else
 1289 #endif
 1290         {
 1291                 th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
 1292                     htons(tlen - hlen + IPPROTO_TCP));
 1293                 m->m_pkthdr.csum_flags = CSUM_TCP;
 1294                 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
 1295 #ifdef TCPDEBUG
 1296                 /*
 1297                  * Trace.
 1298                  */
 1299                 if (so != NULL && so->so_options & SO_DEBUG) {
 1300                         struct tcpcb *tp = sototcpcb(so);
 1301                         tcp_trace(TA_OUTPUT, tp->t_state, tp,
 1302                             mtod(m, void *), th, 0);
 1303                 }
 1304 #endif
 1305                 error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, inp);
 1306         }
 1307         INP_UNLOCK(inp);
 1308         return (error);
 1309 }
 1310 
 1311 /*
 1312  * cookie layers:
 1313  *
 1314  *      |. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
 1315  *      | peer iss                                                      |
 1316  *      | MD5(laddr,faddr,secret,lport,fport)             |. . . . . . .|
 1317  *      |                     0                       |(A)|             |
 1318  * (A): peer mss index
 1319  */
 1320 
 1321 /*
 1322  * The values below are chosen to minimize the size of the tcp_secret
 1323  * table, as well as providing roughly a 16 second lifetime for the cookie.
 1324  */
 1325 
 1326 #define SYNCOOKIE_WNDBITS       5       /* exposed bits for window indexing */
 1327 #define SYNCOOKIE_TIMESHIFT     1       /* scale ticks to window time units */
 1328 
 1329 #define SYNCOOKIE_WNDMASK       ((1 << SYNCOOKIE_WNDBITS) - 1)
 1330 #define SYNCOOKIE_NSECRETS      (1 << SYNCOOKIE_WNDBITS)
 1331 #define SYNCOOKIE_TIMEOUT \
 1332     (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
 1333 #define SYNCOOKIE_DATAMASK      ((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
 1334 
 1335 static struct {
 1336         u_int32_t       ts_secbits[4];
 1337         u_int           ts_expire;
 1338 } tcp_secret[SYNCOOKIE_NSECRETS];
 1339 
 1340 static int tcp_msstab[] = { 0, 536, 1460, 8960 };
 1341 
 1342 static MD5_CTX syn_ctx;
 1343 
 1344 #define MD5Add(v)       MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
 1345 
 1346 struct md5_add {
 1347         u_int32_t laddr, faddr;
 1348         u_int32_t secbits[4];
 1349         u_int16_t lport, fport;
 1350 };
 1351 
 1352 #ifdef CTASSERT
 1353 CTASSERT(sizeof(struct md5_add) == 28);
 1354 #endif
 1355 
 1356 /*
 1357  * Consider the problem of a recreated (and retransmitted) cookie.  If the
 1358  * original SYN was accepted, the connection is established.  The second
 1359  * SYN is inflight, and if it arrives with an ISN that falls within the
 1360  * receive window, the connection is killed.
 1361  *
 1362  * However, since cookies have other problems, this may not be worth
 1363  * worrying about.
 1364  */
 1365 
 1366 static u_int32_t
 1367 syncookie_generate(struct syncache *sc, u_int32_t *flowid)
 1368 {
 1369         u_int32_t md5_buffer[4];
 1370         u_int32_t data;
 1371         int idx, i;
 1372         struct md5_add add;
 1373 
 1374         /* NB: single threaded; could add INP_INFO_WLOCK_ASSERT(&tcbinfo) */
 1375 
 1376         idx = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
 1377         if (tcp_secret[idx].ts_expire < ticks) {
 1378                 for (i = 0; i < 4; i++)
 1379                         tcp_secret[idx].ts_secbits[i] = arc4random();
 1380                 tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
 1381         }
 1382         for (data = sizeof(tcp_msstab) / sizeof(int) - 1; data > 0; data--)
 1383                 if (tcp_msstab[data] <= sc->sc_peer_mss)
 1384                         break;
 1385         data = (data << SYNCOOKIE_WNDBITS) | idx;
 1386         data ^= sc->sc_irs;                             /* peer's iss */
 1387         MD5Init(&syn_ctx);
 1388 #ifdef INET6
 1389         if (sc->sc_inc.inc_isipv6) {
 1390                 MD5Add(sc->sc_inc.inc6_laddr);
 1391                 MD5Add(sc->sc_inc.inc6_faddr);
 1392                 add.laddr = 0;
 1393                 add.faddr = 0;
 1394         } else
 1395 #endif
 1396         {
 1397                 add.laddr = sc->sc_inc.inc_laddr.s_addr;
 1398                 add.faddr = sc->sc_inc.inc_faddr.s_addr;
 1399         }
 1400         add.lport = sc->sc_inc.inc_lport;
 1401         add.fport = sc->sc_inc.inc_fport;
 1402         add.secbits[0] = tcp_secret[idx].ts_secbits[0];
 1403         add.secbits[1] = tcp_secret[idx].ts_secbits[1];
 1404         add.secbits[2] = tcp_secret[idx].ts_secbits[2];
 1405         add.secbits[3] = tcp_secret[idx].ts_secbits[3];
 1406         MD5Add(add);
 1407         MD5Final((u_char *)&md5_buffer, &syn_ctx);
 1408         data ^= (md5_buffer[0] & ~SYNCOOKIE_WNDMASK);
 1409         *flowid = md5_buffer[1];
 1410         return (data);
 1411 }
 1412 
 1413 static struct syncache *
 1414 syncookie_lookup(inc, th, so)
 1415         struct in_conninfo *inc;
 1416         struct tcphdr *th;
 1417         struct socket *so;
 1418 {
 1419         u_int32_t md5_buffer[4];
 1420         struct syncache *sc;
 1421         u_int32_t data;
 1422         int wnd, idx;
 1423         struct md5_add add;
 1424 
 1425         /* NB: single threaded; could add INP_INFO_WLOCK_ASSERT(&tcbinfo) */
 1426 
 1427         data = (th->th_ack - 1) ^ (th->th_seq - 1);     /* remove ISS */
 1428         idx = data & SYNCOOKIE_WNDMASK;
 1429         if (tcp_secret[idx].ts_expire < ticks ||
 1430             sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
 1431                 return (NULL);
 1432         MD5Init(&syn_ctx);
 1433 #ifdef INET6
 1434         if (inc->inc_isipv6) {
 1435                 MD5Add(inc->inc6_laddr);
 1436                 MD5Add(inc->inc6_faddr);
 1437                 add.laddr = 0;
 1438                 add.faddr = 0;
 1439         } else
 1440 #endif
 1441         {
 1442                 add.laddr = inc->inc_laddr.s_addr;
 1443                 add.faddr = inc->inc_faddr.s_addr;
 1444         }
 1445         add.lport = inc->inc_lport;
 1446         add.fport = inc->inc_fport;
 1447         add.secbits[0] = tcp_secret[idx].ts_secbits[0];
 1448         add.secbits[1] = tcp_secret[idx].ts_secbits[1];
 1449         add.secbits[2] = tcp_secret[idx].ts_secbits[2];
 1450         add.secbits[3] = tcp_secret[idx].ts_secbits[3];
 1451         MD5Add(add);
 1452         MD5Final((u_char *)&md5_buffer, &syn_ctx);
 1453         data ^= md5_buffer[0];
 1454         if ((data & ~SYNCOOKIE_DATAMASK) != 0)
 1455                 return (NULL);
 1456         data = data >> SYNCOOKIE_WNDBITS;
 1457 
 1458         sc = uma_zalloc(tcp_syncache.zone, M_NOWAIT);
 1459         if (sc == NULL)
 1460                 return (NULL);
 1461         /*
 1462          * Fill in the syncache values.
 1463          * XXX duplicate code from syncache_add
 1464          */
 1465         sc->sc_ipopts = NULL;
 1466         sc->sc_inc.inc_fport = inc->inc_fport;
 1467         sc->sc_inc.inc_lport = inc->inc_lport;
 1468         sc->sc_tp = sototcpcb(so);
 1469 #ifdef INET6
 1470         sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
 1471         if (inc->inc_isipv6) {
 1472                 sc->sc_inc.inc6_faddr = inc->inc6_faddr;
 1473                 sc->sc_inc.inc6_laddr = inc->inc6_laddr;
 1474                 if (sc->sc_tp->t_inpcb->in6p_flags & IN6P_AUTOFLOWLABEL)
 1475                         sc->sc_flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
 1476         } else
 1477 #endif
 1478         {
 1479                 sc->sc_inc.inc_faddr = inc->inc_faddr;
 1480                 sc->sc_inc.inc_laddr = inc->inc_laddr;
 1481         }
 1482         sc->sc_irs = th->th_seq - 1;
 1483         sc->sc_iss = th->th_ack - 1;
 1484         wnd = sbspace(&so->so_rcv);
 1485         wnd = imax(wnd, 0);
 1486         wnd = imin(wnd, TCP_MAXWIN);
 1487         sc->sc_wnd = wnd;
 1488         sc->sc_flags = 0;
 1489         sc->sc_rxtslot = 0;
 1490         sc->sc_peer_mss = tcp_msstab[data];
 1491         return (sc);
 1492 }

Cache object: d08f96fbb1e99b9fe263b4039480eea2


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.