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

Cache object: 20c9742372b77635f8adb2589441fe99


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