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

Cache object: c39e74f232c96d22efaead190208f304


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