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

Cache object: 5e63d1cb49c611fe4c4ec9429a5ff88b


[ 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.