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/netipsec/key.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*      $FreeBSD: releng/8.3/sys/netipsec/key.c 226392 2011-10-15 13:03:25Z brueffer $  */
    2 /*      $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
    3 
    4 /*-
    5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following conditions
   10  * are met:
   11  * 1. Redistributions of source code must retain the above copyright
   12  *    notice, this list of conditions and the following disclaimer.
   13  * 2. Redistributions in binary form must reproduce the above copyright
   14  *    notice, this list of conditions and the following disclaimer in the
   15  *    documentation and/or other materials provided with the distribution.
   16  * 3. Neither the name of the project nor the names of its contributors
   17  *    may be used to endorse or promote products derived from this software
   18  *    without specific prior written permission.
   19  *
   20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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 /*
   34  * This code is referd to RFC 2367
   35  */
   36 
   37 #include "opt_inet.h"
   38 #include "opt_inet6.h"
   39 #include "opt_ipsec.h"
   40 
   41 #include <sys/types.h>
   42 #include <sys/param.h>
   43 #include <sys/systm.h>
   44 #include <sys/kernel.h>
   45 #include <sys/lock.h>
   46 #include <sys/mutex.h>
   47 #include <sys/mbuf.h>
   48 #include <sys/domain.h>
   49 #include <sys/protosw.h>
   50 #include <sys/malloc.h>
   51 #include <sys/socket.h>
   52 #include <sys/socketvar.h>
   53 #include <sys/sysctl.h>
   54 #include <sys/errno.h>
   55 #include <sys/proc.h>
   56 #include <sys/queue.h>
   57 #include <sys/refcount.h>
   58 #include <sys/syslog.h>
   59 
   60 #include <net/if.h>
   61 #include <net/route.h>
   62 #include <net/raw_cb.h>
   63 #include <net/vnet.h>
   64 
   65 #include <netinet/in.h>
   66 #include <netinet/in_systm.h>
   67 #include <netinet/ip.h>
   68 #include <netinet/in_var.h>
   69 
   70 #ifdef INET6
   71 #include <netinet/ip6.h>
   72 #include <netinet6/in6_var.h>
   73 #include <netinet6/ip6_var.h>
   74 #endif /* INET6 */
   75 
   76 #ifdef INET
   77 #include <netinet/in_pcb.h>
   78 #endif
   79 #ifdef INET6
   80 #include <netinet6/in6_pcb.h>
   81 #endif /* INET6 */
   82 
   83 #include <net/pfkeyv2.h>
   84 #include <netipsec/keydb.h>
   85 #include <netipsec/key.h>
   86 #include <netipsec/keysock.h>
   87 #include <netipsec/key_debug.h>
   88 
   89 #include <netipsec/ipsec.h>
   90 #ifdef INET6
   91 #include <netipsec/ipsec6.h>
   92 #endif
   93 
   94 #include <netipsec/xform.h>
   95 
   96 #include <machine/stdarg.h>
   97 
   98 /* randomness */
   99 #include <sys/random.h>
  100 
  101 #define FULLMASK        0xff
  102 #define _BITS(bytes)    ((bytes) << 3)
  103 
  104 /*
  105  * Note on SA reference counting:
  106  * - SAs that are not in DEAD state will have (total external reference + 1)
  107  *   following value in reference count field.  they cannot be freed and are
  108  *   referenced from SA header.
  109  * - SAs that are in DEAD state will have (total external reference)
  110  *   in reference count field.  they are ready to be freed.  reference from
  111  *   SA header will be removed in key_delsav(), when the reference count
  112  *   field hits 0 (= no external reference other than from SA header.
  113  */
  114 
  115 VNET_DEFINE(u_int32_t, key_debug_level) = 0;
  116 static VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
  117 static VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
  118 static VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff;     /* XXX */
  119 static VNET_DEFINE(u_int32_t, policy_id) = 0;
  120 /*interval to initialize randseed,1(m)*/
  121 static VNET_DEFINE(u_int, key_int_random) = 60;
  122 /* interval to expire acquiring, 30(s)*/
  123 static VNET_DEFINE(u_int, key_larval_lifetime) = 30;
  124 /* counter for blocking SADB_ACQUIRE.*/
  125 static VNET_DEFINE(int, key_blockacq_count) = 10;
  126 /* lifetime for blocking SADB_ACQUIRE.*/
  127 static VNET_DEFINE(int, key_blockacq_lifetime) = 20;
  128 /* preferred old sa rather than new sa.*/
  129 static VNET_DEFINE(int, key_preferred_oldsa) = 1;
  130 #define V_key_spi_trycnt        VNET(key_spi_trycnt)
  131 #define V_key_spi_minval        VNET(key_spi_minval)
  132 #define V_key_spi_maxval        VNET(key_spi_maxval)
  133 #define V_policy_id             VNET(policy_id)
  134 #define V_key_int_random        VNET(key_int_random)
  135 #define V_key_larval_lifetime   VNET(key_larval_lifetime)
  136 #define V_key_blockacq_count    VNET(key_blockacq_count)
  137 #define V_key_blockacq_lifetime VNET(key_blockacq_lifetime)
  138 #define V_key_preferred_oldsa   VNET(key_preferred_oldsa)
  139 
  140 static VNET_DEFINE(u_int32_t, acq_seq) = 0;
  141 #define V_acq_seq               VNET(acq_seq)
  142 
  143                                                                 /* SPD */
  144 static VNET_DEFINE(LIST_HEAD(_sptree, secpolicy), sptree[IPSEC_DIR_MAX]);
  145 #define V_sptree                VNET(sptree)
  146 static struct mtx sptree_lock;
  147 #define SPTREE_LOCK_INIT() \
  148         mtx_init(&sptree_lock, "sptree", \
  149                 "fast ipsec security policy database", MTX_DEF)
  150 #define SPTREE_LOCK_DESTROY()   mtx_destroy(&sptree_lock)
  151 #define SPTREE_LOCK()           mtx_lock(&sptree_lock)
  152 #define SPTREE_UNLOCK() mtx_unlock(&sptree_lock)
  153 #define SPTREE_LOCK_ASSERT()    mtx_assert(&sptree_lock, MA_OWNED)
  154 
  155 static VNET_DEFINE(LIST_HEAD(_sahtree, secashead), sahtree);    /* SAD */
  156 #define V_sahtree               VNET(sahtree)
  157 static struct mtx sahtree_lock;
  158 #define SAHTREE_LOCK_INIT() \
  159         mtx_init(&sahtree_lock, "sahtree", \
  160                 "fast ipsec security association database", MTX_DEF)
  161 #define SAHTREE_LOCK_DESTROY()  mtx_destroy(&sahtree_lock)
  162 #define SAHTREE_LOCK()          mtx_lock(&sahtree_lock)
  163 #define SAHTREE_UNLOCK()        mtx_unlock(&sahtree_lock)
  164 #define SAHTREE_LOCK_ASSERT()   mtx_assert(&sahtree_lock, MA_OWNED)
  165 
  166                                                         /* registed list */
  167 static VNET_DEFINE(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
  168 #define V_regtree               VNET(regtree)
  169 static struct mtx regtree_lock;
  170 #define REGTREE_LOCK_INIT() \
  171         mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
  172 #define REGTREE_LOCK_DESTROY()  mtx_destroy(&regtree_lock)
  173 #define REGTREE_LOCK()          mtx_lock(&regtree_lock)
  174 #define REGTREE_UNLOCK()        mtx_unlock(&regtree_lock)
  175 #define REGTREE_LOCK_ASSERT()   mtx_assert(&regtree_lock, MA_OWNED)
  176 
  177 static VNET_DEFINE(LIST_HEAD(_acqtree, secacq), acqtree); /* acquiring list */
  178 #define V_acqtree               VNET(acqtree)
  179 static struct mtx acq_lock;
  180 #define ACQ_LOCK_INIT() \
  181         mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
  182 #define ACQ_LOCK_DESTROY()      mtx_destroy(&acq_lock)
  183 #define ACQ_LOCK()              mtx_lock(&acq_lock)
  184 #define ACQ_UNLOCK()            mtx_unlock(&acq_lock)
  185 #define ACQ_LOCK_ASSERT()       mtx_assert(&acq_lock, MA_OWNED)
  186 
  187                                                         /* SP acquiring list */
  188 static VNET_DEFINE(LIST_HEAD(_spacqtree, secspacq), spacqtree);
  189 #define V_spacqtree             VNET(spacqtree)
  190 static struct mtx spacq_lock;
  191 #define SPACQ_LOCK_INIT() \
  192         mtx_init(&spacq_lock, "spacqtree", \
  193                 "fast ipsec security policy acquire list", MTX_DEF)
  194 #define SPACQ_LOCK_DESTROY()    mtx_destroy(&spacq_lock)
  195 #define SPACQ_LOCK()            mtx_lock(&spacq_lock)
  196 #define SPACQ_UNLOCK()          mtx_unlock(&spacq_lock)
  197 #define SPACQ_LOCK_ASSERT()     mtx_assert(&spacq_lock, MA_OWNED)
  198 
  199 /* search order for SAs */
  200 static const u_int saorder_state_valid_prefer_old[] = {
  201         SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
  202 };
  203 static const u_int saorder_state_valid_prefer_new[] = {
  204         SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
  205 };
  206 static const u_int saorder_state_alive[] = {
  207         /* except DEAD */
  208         SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
  209 };
  210 static const u_int saorder_state_any[] = {
  211         SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
  212         SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
  213 };
  214 
  215 static const int minsize[] = {
  216         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
  217         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
  218         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
  219         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
  220         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
  221         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_SRC */
  222         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_DST */
  223         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_PROXY */
  224         sizeof(struct sadb_key),        /* SADB_EXT_KEY_AUTH */
  225         sizeof(struct sadb_key),        /* SADB_EXT_KEY_ENCRYPT */
  226         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_SRC */
  227         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_DST */
  228         sizeof(struct sadb_sens),       /* SADB_EXT_SENSITIVITY */
  229         sizeof(struct sadb_prop),       /* SADB_EXT_PROPOSAL */
  230         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_AUTH */
  231         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_ENCRYPT */
  232         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
  233         0,                              /* SADB_X_EXT_KMPRIVATE */
  234         sizeof(struct sadb_x_policy),   /* SADB_X_EXT_POLICY */
  235         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
  236         sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
  237         sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
  238         sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
  239         sizeof(struct sadb_address),    /* SADB_X_EXT_NAT_T_OAI */
  240         sizeof(struct sadb_address),    /* SADB_X_EXT_NAT_T_OAR */
  241         sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
  242 };
  243 static const int maxsize[] = {
  244         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
  245         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
  246         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
  247         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
  248         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
  249         0,                              /* SADB_EXT_ADDRESS_SRC */
  250         0,                              /* SADB_EXT_ADDRESS_DST */
  251         0,                              /* SADB_EXT_ADDRESS_PROXY */
  252         0,                              /* SADB_EXT_KEY_AUTH */
  253         0,                              /* SADB_EXT_KEY_ENCRYPT */
  254         0,                              /* SADB_EXT_IDENTITY_SRC */
  255         0,                              /* SADB_EXT_IDENTITY_DST */
  256         0,                              /* SADB_EXT_SENSITIVITY */
  257         0,                              /* SADB_EXT_PROPOSAL */
  258         0,                              /* SADB_EXT_SUPPORTED_AUTH */
  259         0,                              /* SADB_EXT_SUPPORTED_ENCRYPT */
  260         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
  261         0,                              /* SADB_X_EXT_KMPRIVATE */
  262         0,                              /* SADB_X_EXT_POLICY */
  263         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
  264         sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
  265         sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
  266         sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
  267         0,                              /* SADB_X_EXT_NAT_T_OAI */
  268         0,                              /* SADB_X_EXT_NAT_T_OAR */
  269         sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
  270 };
  271 
  272 static VNET_DEFINE(int, ipsec_esp_keymin) = 256;
  273 static VNET_DEFINE(int, ipsec_esp_auth) = 0;
  274 static VNET_DEFINE(int, ipsec_ah_keymin) = 128;
  275 
  276 #define V_ipsec_esp_keymin      VNET(ipsec_esp_keymin)
  277 #define V_ipsec_esp_auth        VNET(ipsec_esp_auth)
  278 #define V_ipsec_ah_keymin       VNET(ipsec_ah_keymin)
  279 
  280 #ifdef SYSCTL_DECL
  281 SYSCTL_DECL(_net_key);
  282 #endif
  283 
  284 SYSCTL_VNET_INT(_net_key, KEYCTL_DEBUG_LEVEL,   debug,
  285         CTLFLAG_RW, &VNET_NAME(key_debug_level),        0,      "");
  286 
  287 /* max count of trial for the decision of spi value */
  288 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
  289         CTLFLAG_RW, &VNET_NAME(key_spi_trycnt), 0,      "");
  290 
  291 /* minimum spi value to allocate automatically. */
  292 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MIN_VALUE,
  293         spi_minval,     CTLFLAG_RW, &VNET_NAME(key_spi_minval), 0,      "");
  294 
  295 /* maximun spi value to allocate automatically. */
  296 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MAX_VALUE,
  297         spi_maxval,     CTLFLAG_RW, &VNET_NAME(key_spi_maxval), 0,      "");
  298 
  299 /* interval to initialize randseed */
  300 SYSCTL_VNET_INT(_net_key, KEYCTL_RANDOM_INT,
  301         int_random,     CTLFLAG_RW, &VNET_NAME(key_int_random), 0,      "");
  302 
  303 /* lifetime for larval SA */
  304 SYSCTL_VNET_INT(_net_key, KEYCTL_LARVAL_LIFETIME,
  305         larval_lifetime, CTLFLAG_RW, &VNET_NAME(key_larval_lifetime),   0, "");
  306 
  307 /* counter for blocking to send SADB_ACQUIRE to IKEd */
  308 SYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,
  309         blockacq_count, CTLFLAG_RW, &VNET_NAME(key_blockacq_count),     0, "");
  310 
  311 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
  312 SYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,
  313         blockacq_lifetime, CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
  314 
  315 /* ESP auth */
  316 SYSCTL_VNET_INT(_net_key, KEYCTL_ESP_AUTH,      esp_auth,
  317         CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth), 0,      "");
  318 
  319 /* minimum ESP key length */
  320 SYSCTL_VNET_INT(_net_key, KEYCTL_ESP_KEYMIN,
  321         esp_keymin, CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin),   0,      "");
  322 
  323 /* minimum AH key length */
  324 SYSCTL_VNET_INT(_net_key, KEYCTL_AH_KEYMIN,     ah_keymin,
  325         CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin),        0,      "");
  326 
  327 /* perfered old SA rather than new SA */
  328 SYSCTL_VNET_INT(_net_key, KEYCTL_PREFERED_OLDSA,
  329         preferred_oldsa, CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa),   0, "");
  330 
  331 #define __LIST_CHAINED(elm) \
  332         (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
  333 #define LIST_INSERT_TAIL(head, elm, type, field) \
  334 do {\
  335         struct type *curelm = LIST_FIRST(head); \
  336         if (curelm == NULL) {\
  337                 LIST_INSERT_HEAD(head, elm, field); \
  338         } else { \
  339                 while (LIST_NEXT(curelm, field)) \
  340                         curelm = LIST_NEXT(curelm, field);\
  341                 LIST_INSERT_AFTER(curelm, elm, field);\
  342         }\
  343 } while (0)
  344 
  345 #define KEY_CHKSASTATE(head, sav, name) \
  346 do { \
  347         if ((head) != (sav)) {                                          \
  348                 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
  349                         (name), (head), (sav)));                        \
  350                 continue;                                               \
  351         }                                                               \
  352 } while (0)
  353 
  354 #define KEY_CHKSPDIR(head, sp, name) \
  355 do { \
  356         if ((head) != (sp)) {                                           \
  357                 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
  358                         "anyway continue.\n",                           \
  359                         (name), (head), (sp)));                         \
  360         }                                                               \
  361 } while (0)
  362 
  363 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
  364 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
  365 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
  366 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
  367 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
  368 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
  369 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
  370 
  371 /*
  372  * set parameters into secpolicyindex buffer.
  373  * Must allocate secpolicyindex buffer passed to this function.
  374  */
  375 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
  376 do { \
  377         bzero((idx), sizeof(struct secpolicyindex));                         \
  378         (idx)->dir = (_dir);                                                 \
  379         (idx)->prefs = (ps);                                                 \
  380         (idx)->prefd = (pd);                                                 \
  381         (idx)->ul_proto = (ulp);                                             \
  382         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
  383         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
  384 } while (0)
  385 
  386 /*
  387  * set parameters into secasindex buffer.
  388  * Must allocate secasindex buffer before calling this function.
  389  */
  390 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
  391 do { \
  392         bzero((idx), sizeof(struct secasindex));                             \
  393         (idx)->proto = (p);                                                  \
  394         (idx)->mode = (m);                                                   \
  395         (idx)->reqid = (r);                                                  \
  396         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
  397         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
  398 } while (0)
  399 
  400 /* key statistics */
  401 struct _keystat {
  402         u_long getspi_count; /* the avarage of count to try to get new SPI */
  403 } keystat;
  404 
  405 struct sadb_msghdr {
  406         struct sadb_msg *msg;
  407         struct sadb_ext *ext[SADB_EXT_MAX + 1];
  408         int extoff[SADB_EXT_MAX + 1];
  409         int extlen[SADB_EXT_MAX + 1];
  410 };
  411 
  412 static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
  413 static void key_freesp_so __P((struct secpolicy **));
  414 static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
  415 static void key_delsp __P((struct secpolicy *));
  416 static struct secpolicy *key_getsp __P((struct secpolicyindex *));
  417 static void _key_delsp(struct secpolicy *sp);
  418 static struct secpolicy *key_getspbyid __P((u_int32_t));
  419 static u_int32_t key_newreqid __P((void));
  420 static struct mbuf *key_gather_mbuf __P((struct mbuf *,
  421         const struct sadb_msghdr *, int, int, ...));
  422 static int key_spdadd __P((struct socket *, struct mbuf *,
  423         const struct sadb_msghdr *));
  424 static u_int32_t key_getnewspid __P((void));
  425 static int key_spddelete __P((struct socket *, struct mbuf *,
  426         const struct sadb_msghdr *));
  427 static int key_spddelete2 __P((struct socket *, struct mbuf *,
  428         const struct sadb_msghdr *));
  429 static int key_spdget __P((struct socket *, struct mbuf *,
  430         const struct sadb_msghdr *));
  431 static int key_spdflush __P((struct socket *, struct mbuf *,
  432         const struct sadb_msghdr *));
  433 static int key_spddump __P((struct socket *, struct mbuf *,
  434         const struct sadb_msghdr *));
  435 static struct mbuf *key_setdumpsp __P((struct secpolicy *,
  436         u_int8_t, u_int32_t, u_int32_t));
  437 static u_int key_getspreqmsglen __P((struct secpolicy *));
  438 static int key_spdexpire __P((struct secpolicy *));
  439 static struct secashead *key_newsah __P((struct secasindex *));
  440 static void key_delsah __P((struct secashead *));
  441 static struct secasvar *key_newsav __P((struct mbuf *,
  442         const struct sadb_msghdr *, struct secashead *, int *,
  443         const char*, int));
  444 #define KEY_NEWSAV(m, sadb, sah, e)                             \
  445         key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
  446 static void key_delsav __P((struct secasvar *));
  447 static struct secashead *key_getsah __P((struct secasindex *));
  448 static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
  449 static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
  450 static int key_setsaval __P((struct secasvar *, struct mbuf *,
  451         const struct sadb_msghdr *));
  452 static int key_mature __P((struct secasvar *));
  453 static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
  454         u_int8_t, u_int32_t, u_int32_t));
  455 static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
  456         u_int32_t, pid_t, u_int16_t));
  457 static struct mbuf *key_setsadbsa __P((struct secasvar *));
  458 static struct mbuf *key_setsadbaddr __P((u_int16_t,
  459         const struct sockaddr *, u_int8_t, u_int16_t));
  460 #ifdef IPSEC_NAT_T
  461 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
  462 static struct mbuf *key_setsadbxtype(u_int16_t);
  463 #endif
  464 static void key_porttosaddr(struct sockaddr *, u_int16_t);
  465 #define KEY_PORTTOSADDR(saddr, port)                            \
  466         key_porttosaddr((struct sockaddr *)(saddr), (port))
  467 static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
  468 static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
  469         u_int32_t));
  470 static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int, 
  471                                      struct malloc_type *);
  472 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
  473                                             struct malloc_type *type);
  474 #ifdef INET6
  475 static int key_ismyaddr6 __P((struct sockaddr_in6 *));
  476 #endif
  477 
  478 /* flags for key_cmpsaidx() */
  479 #define CMP_HEAD        1       /* protocol, addresses. */
  480 #define CMP_MODE_REQID  2       /* additionally HEAD, reqid, mode. */
  481 #define CMP_REQID       3       /* additionally HEAD, reaid. */
  482 #define CMP_EXACTLY     4       /* all elements. */
  483 static int key_cmpsaidx
  484         __P((const struct secasindex *, const struct secasindex *, int));
  485 
  486 static int key_cmpspidx_exactly
  487         __P((struct secpolicyindex *, struct secpolicyindex *));
  488 static int key_cmpspidx_withmask
  489         __P((struct secpolicyindex *, struct secpolicyindex *));
  490 static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
  491 static int key_bbcmp __P((const void *, const void *, u_int));
  492 static u_int16_t key_satype2proto __P((u_int8_t));
  493 static u_int8_t key_proto2satype __P((u_int16_t));
  494 
  495 static int key_getspi __P((struct socket *, struct mbuf *,
  496         const struct sadb_msghdr *));
  497 static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
  498                                         struct secasindex *));
  499 static int key_update __P((struct socket *, struct mbuf *,
  500         const struct sadb_msghdr *));
  501 #ifdef IPSEC_DOSEQCHECK
  502 static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
  503 #endif
  504 static int key_add __P((struct socket *, struct mbuf *,
  505         const struct sadb_msghdr *));
  506 static int key_setident __P((struct secashead *, struct mbuf *,
  507         const struct sadb_msghdr *));
  508 static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
  509         const struct sadb_msghdr *));
  510 static int key_delete __P((struct socket *, struct mbuf *,
  511         const struct sadb_msghdr *));
  512 static int key_get __P((struct socket *, struct mbuf *,
  513         const struct sadb_msghdr *));
  514 
  515 static void key_getcomb_setlifetime __P((struct sadb_comb *));
  516 static struct mbuf *key_getcomb_esp __P((void));
  517 static struct mbuf *key_getcomb_ah __P((void));
  518 static struct mbuf *key_getcomb_ipcomp __P((void));
  519 static struct mbuf *key_getprop __P((const struct secasindex *));
  520 
  521 static int key_acquire __P((const struct secasindex *, struct secpolicy *));
  522 static struct secacq *key_newacq __P((const struct secasindex *));
  523 static struct secacq *key_getacq __P((const struct secasindex *));
  524 static struct secacq *key_getacqbyseq __P((u_int32_t));
  525 static struct secspacq *key_newspacq __P((struct secpolicyindex *));
  526 static struct secspacq *key_getspacq __P((struct secpolicyindex *));
  527 static int key_acquire2 __P((struct socket *, struct mbuf *,
  528         const struct sadb_msghdr *));
  529 static int key_register __P((struct socket *, struct mbuf *,
  530         const struct sadb_msghdr *));
  531 static int key_expire __P((struct secasvar *));
  532 static int key_flush __P((struct socket *, struct mbuf *,
  533         const struct sadb_msghdr *));
  534 static int key_dump __P((struct socket *, struct mbuf *,
  535         const struct sadb_msghdr *));
  536 static int key_promisc __P((struct socket *, struct mbuf *,
  537         const struct sadb_msghdr *));
  538 static int key_senderror __P((struct socket *, struct mbuf *, int));
  539 static int key_validate_ext __P((const struct sadb_ext *, int));
  540 static int key_align __P((struct mbuf *, struct sadb_msghdr *));
  541 static struct mbuf *key_setlifetime(struct seclifetime *src, 
  542                                      u_int16_t exttype);
  543 static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
  544 
  545 #if 0
  546 static const char *key_getfqdn __P((void));
  547 static const char *key_getuserfqdn __P((void));
  548 #endif
  549 static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
  550 static struct mbuf *key_alloc_mbuf __P((int));
  551 
  552 static __inline void
  553 sa_initref(struct secasvar *sav)
  554 {
  555 
  556         refcount_init(&sav->refcnt, 1);
  557 }
  558 static __inline void
  559 sa_addref(struct secasvar *sav)
  560 {
  561 
  562         refcount_acquire(&sav->refcnt);
  563         IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
  564 }
  565 static __inline int
  566 sa_delref(struct secasvar *sav)
  567 {
  568 
  569         IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
  570         return (refcount_release(&sav->refcnt));
  571 }
  572 
  573 #define SP_ADDREF(p) do {                                               \
  574         (p)->refcnt++;                                                  \
  575         IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));         \
  576 } while (0)
  577 #define SP_DELREF(p) do {                                               \
  578         IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));         \
  579         (p)->refcnt--;                                                  \
  580 } while (0)
  581  
  582 
  583 /*
  584  * Update the refcnt while holding the SPTREE lock.
  585  */
  586 void
  587 key_addref(struct secpolicy *sp)
  588 {
  589         SPTREE_LOCK();
  590         SP_ADDREF(sp);
  591         SPTREE_UNLOCK();
  592 }
  593 
  594 /*
  595  * Return 0 when there are known to be no SP's for the specified
  596  * direction.  Otherwise return 1.  This is used by IPsec code
  597  * to optimize performance.
  598  */
  599 int
  600 key_havesp(u_int dir)
  601 {
  602 
  603         return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
  604                 LIST_FIRST(&V_sptree[dir]) != NULL : 1);
  605 }
  606 
  607 /* %%% IPsec policy management */
  608 /*
  609  * allocating a SP for OUTBOUND or INBOUND packet.
  610  * Must call key_freesp() later.
  611  * OUT: NULL:   not found
  612  *      others: found and return the pointer.
  613  */
  614 struct secpolicy *
  615 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
  616 {
  617         struct secpolicy *sp;
  618 
  619         IPSEC_ASSERT(spidx != NULL, ("null spidx"));
  620         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  621                 ("invalid direction %u", dir));
  622 
  623         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  624                 printf("DP %s from %s:%u\n", __func__, where, tag));
  625 
  626         /* get a SP entry */
  627         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  628                 printf("*** objects\n");
  629                 kdebug_secpolicyindex(spidx));
  630 
  631         SPTREE_LOCK();
  632         LIST_FOREACH(sp, &V_sptree[dir], chain) {
  633                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  634                         printf("*** in SPD\n");
  635                         kdebug_secpolicyindex(&sp->spidx));
  636 
  637                 if (sp->state == IPSEC_SPSTATE_DEAD)
  638                         continue;
  639                 if (key_cmpspidx_withmask(&sp->spidx, spidx))
  640                         goto found;
  641         }
  642         sp = NULL;
  643 found:
  644         if (sp) {
  645                 /* sanity check */
  646                 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
  647 
  648                 /* found a SPD entry */
  649                 sp->lastused = time_second;
  650                 SP_ADDREF(sp);
  651         }
  652         SPTREE_UNLOCK();
  653 
  654         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  655                 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
  656                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  657         return sp;
  658 }
  659 
  660 /*
  661  * allocating a SP for OUTBOUND or INBOUND packet.
  662  * Must call key_freesp() later.
  663  * OUT: NULL:   not found
  664  *      others: found and return the pointer.
  665  */
  666 struct secpolicy *
  667 key_allocsp2(u_int32_t spi,
  668              union sockaddr_union *dst,
  669              u_int8_t proto,
  670              u_int dir,
  671              const char* where, int tag)
  672 {
  673         struct secpolicy *sp;
  674 
  675         IPSEC_ASSERT(dst != NULL, ("null dst"));
  676         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  677                 ("invalid direction %u", dir));
  678 
  679         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  680                 printf("DP %s from %s:%u\n", __func__, where, tag));
  681 
  682         /* get a SP entry */
  683         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  684                 printf("*** objects\n");
  685                 printf("spi %u proto %u dir %u\n", spi, proto, dir);
  686                 kdebug_sockaddr(&dst->sa));
  687 
  688         SPTREE_LOCK();
  689         LIST_FOREACH(sp, &V_sptree[dir], chain) {
  690                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  691                         printf("*** in SPD\n");
  692                         kdebug_secpolicyindex(&sp->spidx));
  693 
  694                 if (sp->state == IPSEC_SPSTATE_DEAD)
  695                         continue;
  696                 /* compare simple values, then dst address */
  697                 if (sp->spidx.ul_proto != proto)
  698                         continue;
  699                 /* NB: spi's must exist and match */
  700                 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
  701                         continue;
  702                 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
  703                         goto found;
  704         }
  705         sp = NULL;
  706 found:
  707         if (sp) {
  708                 /* sanity check */
  709                 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
  710 
  711                 /* found a SPD entry */
  712                 sp->lastused = time_second;
  713                 SP_ADDREF(sp);
  714         }
  715         SPTREE_UNLOCK();
  716 
  717         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  718                 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
  719                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  720         return sp;
  721 }
  722 
  723 #if 0
  724 /*
  725  * return a policy that matches this particular inbound packet.
  726  * XXX slow
  727  */
  728 struct secpolicy *
  729 key_gettunnel(const struct sockaddr *osrc,
  730               const struct sockaddr *odst,
  731               const struct sockaddr *isrc,
  732               const struct sockaddr *idst,
  733               const char* where, int tag)
  734 {
  735         struct secpolicy *sp;
  736         const int dir = IPSEC_DIR_INBOUND;
  737         struct ipsecrequest *r1, *r2, *p;
  738         struct secpolicyindex spidx;
  739 
  740         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  741                 printf("DP %s from %s:%u\n", __func__, where, tag));
  742 
  743         if (isrc->sa_family != idst->sa_family) {
  744                 ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
  745                         __func__, isrc->sa_family, idst->sa_family));
  746                 sp = NULL;
  747                 goto done;
  748         }
  749 
  750         SPTREE_LOCK();
  751         LIST_FOREACH(sp, &V_sptree[dir], chain) {
  752                 if (sp->state == IPSEC_SPSTATE_DEAD)
  753                         continue;
  754 
  755                 r1 = r2 = NULL;
  756                 for (p = sp->req; p; p = p->next) {
  757                         if (p->saidx.mode != IPSEC_MODE_TUNNEL)
  758                                 continue;
  759 
  760                         r1 = r2;
  761                         r2 = p;
  762 
  763                         if (!r1) {
  764                                 /* here we look at address matches only */
  765                                 spidx = sp->spidx;
  766                                 if (isrc->sa_len > sizeof(spidx.src) ||
  767                                     idst->sa_len > sizeof(spidx.dst))
  768                                         continue;
  769                                 bcopy(isrc, &spidx.src, isrc->sa_len);
  770                                 bcopy(idst, &spidx.dst, idst->sa_len);
  771                                 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
  772                                         continue;
  773                         } else {
  774                                 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
  775                                     key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
  776                                         continue;
  777                         }
  778 
  779                         if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
  780                             key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
  781                                 continue;
  782 
  783                         goto found;
  784                 }
  785         }
  786         sp = NULL;
  787 found:
  788         if (sp) {
  789                 sp->lastused = time_second;
  790                 SP_ADDREF(sp);
  791         }
  792         SPTREE_UNLOCK();
  793 done:
  794         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  795                 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
  796                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  797         return sp;
  798 }
  799 #endif
  800 
  801 /*
  802  * allocating an SA entry for an *OUTBOUND* packet.
  803  * checking each request entries in SP, and acquire an SA if need.
  804  * OUT: 0: there are valid requests.
  805  *      ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
  806  */
  807 int
  808 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
  809 {
  810         u_int level;
  811         int error;
  812         struct secasvar *sav;
  813 
  814         IPSEC_ASSERT(isr != NULL, ("null isr"));
  815         IPSEC_ASSERT(saidx != NULL, ("null saidx"));
  816         IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
  817                 saidx->mode == IPSEC_MODE_TUNNEL,
  818                 ("unexpected policy %u", saidx->mode));
  819 
  820         /*
  821          * XXX guard against protocol callbacks from the crypto
  822          * thread as they reference ipsecrequest.sav which we
  823          * temporarily null out below.  Need to rethink how we
  824          * handle bundled SA's in the callback thread.
  825          */
  826         IPSECREQUEST_LOCK_ASSERT(isr);
  827 
  828         /* get current level */
  829         level = ipsec_get_reqlevel(isr);
  830 
  831         /*
  832          * We check new SA in the IPsec request because a different
  833          * SA may be involved each time this request is checked, either
  834          * because new SAs are being configured, or this request is
  835          * associated with an unconnected datagram socket, or this request
  836          * is associated with a system default policy.
  837          *
  838          * key_allocsa_policy should allocate the oldest SA available.
  839          * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
  840          */
  841         sav = key_allocsa_policy(saidx);
  842         if (sav != isr->sav) {
  843                 /* SA need to be updated. */
  844                 if (!IPSECREQUEST_UPGRADE(isr)) {
  845                         /* Kick everyone off. */
  846                         IPSECREQUEST_UNLOCK(isr);
  847                         IPSECREQUEST_WLOCK(isr);
  848                 }
  849                 if (isr->sav != NULL)
  850                         KEY_FREESAV(&isr->sav);
  851                 isr->sav = sav;
  852                 IPSECREQUEST_DOWNGRADE(isr);
  853         } else if (sav != NULL)
  854                 KEY_FREESAV(&sav);
  855 
  856         /* When there is SA. */
  857         if (isr->sav != NULL) {
  858                 if (isr->sav->state != SADB_SASTATE_MATURE &&
  859                     isr->sav->state != SADB_SASTATE_DYING)
  860                         return EINVAL;
  861                 return 0;
  862         }
  863 
  864         /* there is no SA */
  865         error = key_acquire(saidx, isr->sp);
  866         if (error != 0) {
  867                 /* XXX What should I do ? */
  868                 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
  869                         __func__, error));
  870                 return error;
  871         }
  872 
  873         if (level != IPSEC_LEVEL_REQUIRE) {
  874                 /* XXX sigh, the interface to this routine is botched */
  875                 IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
  876                 return 0;
  877         } else {
  878                 return ENOENT;
  879         }
  880 }
  881 
  882 /*
  883  * allocating a SA for policy entry from SAD.
  884  * NOTE: searching SAD of aliving state.
  885  * OUT: NULL:   not found.
  886  *      others: found and return the pointer.
  887  */
  888 static struct secasvar *
  889 key_allocsa_policy(const struct secasindex *saidx)
  890 {
  891 #define N(a)    _ARRAYLEN(a)
  892         struct secashead *sah;
  893         struct secasvar *sav;
  894         u_int stateidx, arraysize;
  895         const u_int *state_valid;
  896 
  897         SAHTREE_LOCK();
  898         LIST_FOREACH(sah, &V_sahtree, chain) {
  899                 if (sah->state == SADB_SASTATE_DEAD)
  900                         continue;
  901                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
  902                         if (V_key_preferred_oldsa) {
  903                                 state_valid = saorder_state_valid_prefer_old;
  904                                 arraysize = N(saorder_state_valid_prefer_old);
  905                         } else {
  906                                 state_valid = saorder_state_valid_prefer_new;
  907                                 arraysize = N(saorder_state_valid_prefer_new);
  908                         }
  909                         SAHTREE_UNLOCK();
  910                         goto found;
  911                 }
  912         }
  913         SAHTREE_UNLOCK();
  914 
  915         return NULL;
  916 
  917     found:
  918         /* search valid state */
  919         for (stateidx = 0; stateidx < arraysize; stateidx++) {
  920                 sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
  921                 if (sav != NULL)
  922                         return sav;
  923         }
  924 
  925         return NULL;
  926 #undef N
  927 }
  928 
  929 /*
  930  * searching SAD with direction, protocol, mode and state.
  931  * called by key_allocsa_policy().
  932  * OUT:
  933  *      NULL    : not found
  934  *      others  : found, pointer to a SA.
  935  */
  936 static struct secasvar *
  937 key_do_allocsa_policy(struct secashead *sah, u_int state)
  938 {
  939         struct secasvar *sav, *nextsav, *candidate, *d;
  940 
  941         /* initilize */
  942         candidate = NULL;
  943 
  944         SAHTREE_LOCK();
  945         for (sav = LIST_FIRST(&sah->savtree[state]);
  946              sav != NULL;
  947              sav = nextsav) {
  948 
  949                 nextsav = LIST_NEXT(sav, chain);
  950 
  951                 /* sanity check */
  952                 KEY_CHKSASTATE(sav->state, state, __func__);
  953 
  954                 /* initialize */
  955                 if (candidate == NULL) {
  956                         candidate = sav;
  957                         continue;
  958                 }
  959 
  960                 /* Which SA is the better ? */
  961 
  962                 IPSEC_ASSERT(candidate->lft_c != NULL,
  963                         ("null candidate lifetime"));
  964                 IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
  965 
  966                 /* What the best method is to compare ? */
  967                 if (V_key_preferred_oldsa) {
  968                         if (candidate->lft_c->addtime >
  969                                         sav->lft_c->addtime) {
  970                                 candidate = sav;
  971                         }
  972                         continue;
  973                         /*NOTREACHED*/
  974                 }
  975 
  976                 /* preferred new sa rather than old sa */
  977                 if (candidate->lft_c->addtime <
  978                                 sav->lft_c->addtime) {
  979                         d = candidate;
  980                         candidate = sav;
  981                 } else
  982                         d = sav;
  983 
  984                 /*
  985                  * prepared to delete the SA when there is more
  986                  * suitable candidate and the lifetime of the SA is not
  987                  * permanent.
  988                  */
  989                 if (d->lft_h->addtime != 0) {
  990                         struct mbuf *m, *result;
  991                         u_int8_t satype;
  992 
  993                         key_sa_chgstate(d, SADB_SASTATE_DEAD);
  994 
  995                         IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
  996 
  997                         satype = key_proto2satype(d->sah->saidx.proto);
  998                         if (satype == 0)
  999                                 goto msgfail;
 1000 
 1001                         m = key_setsadbmsg(SADB_DELETE, 0,
 1002                             satype, 0, 0, d->refcnt - 1);
 1003                         if (!m)
 1004                                 goto msgfail;
 1005                         result = m;
 1006 
 1007                         /* set sadb_address for saidx's. */
 1008                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 1009                                 &d->sah->saidx.src.sa,
 1010                                 d->sah->saidx.src.sa.sa_len << 3,
 1011                                 IPSEC_ULPROTO_ANY);
 1012                         if (!m)
 1013                                 goto msgfail;
 1014                         m_cat(result, m);
 1015 
 1016                         /* set sadb_address for saidx's. */
 1017                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 1018                                 &d->sah->saidx.dst.sa,
 1019                                 d->sah->saidx.dst.sa.sa_len << 3,
 1020                                 IPSEC_ULPROTO_ANY);
 1021                         if (!m)
 1022                                 goto msgfail;
 1023                         m_cat(result, m);
 1024 
 1025                         /* create SA extension */
 1026                         m = key_setsadbsa(d);
 1027                         if (!m)
 1028                                 goto msgfail;
 1029                         m_cat(result, m);
 1030 
 1031                         if (result->m_len < sizeof(struct sadb_msg)) {
 1032                                 result = m_pullup(result,
 1033                                                 sizeof(struct sadb_msg));
 1034                                 if (result == NULL)
 1035                                         goto msgfail;
 1036                         }
 1037 
 1038                         result->m_pkthdr.len = 0;
 1039                         for (m = result; m; m = m->m_next)
 1040                                 result->m_pkthdr.len += m->m_len;
 1041                         mtod(result, struct sadb_msg *)->sadb_msg_len =
 1042                                 PFKEY_UNIT64(result->m_pkthdr.len);
 1043 
 1044                         if (key_sendup_mbuf(NULL, result,
 1045                                         KEY_SENDUP_REGISTERED))
 1046                                 goto msgfail;
 1047                  msgfail:
 1048                         KEY_FREESAV(&d);
 1049                 }
 1050         }
 1051         if (candidate) {
 1052                 sa_addref(candidate);
 1053                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1054                         printf("DP %s cause refcnt++:%d SA:%p\n",
 1055                                 __func__, candidate->refcnt, candidate));
 1056         }
 1057         SAHTREE_UNLOCK();
 1058 
 1059         return candidate;
 1060 }
 1061 
 1062 /*
 1063  * allocating a usable SA entry for a *INBOUND* packet.
 1064  * Must call key_freesav() later.
 1065  * OUT: positive:       pointer to a usable sav (i.e. MATURE or DYING state).
 1066  *      NULL:           not found, or error occured.
 1067  *
 1068  * In the comparison, no source address is used--for RFC2401 conformance.
 1069  * To quote, from section 4.1:
 1070  *      A security association is uniquely identified by a triple consisting
 1071  *      of a Security Parameter Index (SPI), an IP Destination Address, and a
 1072  *      security protocol (AH or ESP) identifier.
 1073  * Note that, however, we do need to keep source address in IPsec SA.
 1074  * IKE specification and PF_KEY specification do assume that we
 1075  * keep source address in IPsec SA.  We see a tricky situation here.
 1076  */
 1077 struct secasvar *
 1078 key_allocsa(
 1079         union sockaddr_union *dst,
 1080         u_int proto,
 1081         u_int32_t spi,
 1082         const char* where, int tag)
 1083 {
 1084         struct secashead *sah;
 1085         struct secasvar *sav;
 1086         u_int stateidx, arraysize, state;
 1087         const u_int *saorder_state_valid;
 1088         int chkport;
 1089 
 1090         IPSEC_ASSERT(dst != NULL, ("null dst address"));
 1091 
 1092         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1093                 printf("DP %s from %s:%u\n", __func__, where, tag));
 1094 
 1095 #ifdef IPSEC_NAT_T
 1096         chkport = (dst->sa.sa_family == AF_INET &&
 1097             dst->sa.sa_len == sizeof(struct sockaddr_in) &&
 1098             dst->sin.sin_port != 0);
 1099 #else
 1100         chkport = 0;
 1101 #endif
 1102 
 1103         /*
 1104          * searching SAD.
 1105          * XXX: to be checked internal IP header somewhere.  Also when
 1106          * IPsec tunnel packet is received.  But ESP tunnel mode is
 1107          * encrypted so we can't check internal IP header.
 1108          */
 1109         SAHTREE_LOCK();
 1110         if (V_key_preferred_oldsa) {
 1111                 saorder_state_valid = saorder_state_valid_prefer_old;
 1112                 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
 1113         } else {
 1114                 saorder_state_valid = saorder_state_valid_prefer_new;
 1115                 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
 1116         }
 1117         LIST_FOREACH(sah, &V_sahtree, chain) {
 1118                 /* search valid state */
 1119                 for (stateidx = 0; stateidx < arraysize; stateidx++) {
 1120                         state = saorder_state_valid[stateidx];
 1121                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 1122                                 /* sanity check */
 1123                                 KEY_CHKSASTATE(sav->state, state, __func__);
 1124                                 /* do not return entries w/ unusable state */
 1125                                 if (sav->state != SADB_SASTATE_MATURE &&
 1126                                     sav->state != SADB_SASTATE_DYING)
 1127                                         continue;
 1128                                 if (proto != sav->sah->saidx.proto)
 1129                                         continue;
 1130                                 if (spi != sav->spi)
 1131                                         continue;
 1132 #if 0   /* don't check src */
 1133                                 /* check src address */
 1134                                 if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, chkport) != 0)
 1135                                         continue;
 1136 #endif
 1137                                 /* check dst address */
 1138                                 if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
 1139                                         continue;
 1140                                 sa_addref(sav);
 1141                                 goto done;
 1142                         }
 1143                 }
 1144         }
 1145         sav = NULL;
 1146 done:
 1147         SAHTREE_UNLOCK();
 1148 
 1149         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1150                 printf("DP %s return SA:%p; refcnt %u\n", __func__,
 1151                         sav, sav ? sav->refcnt : 0));
 1152         return sav;
 1153 }
 1154 
 1155 /*
 1156  * Must be called after calling key_allocsp().
 1157  * For both the packet without socket and key_freeso().
 1158  */
 1159 void
 1160 _key_freesp(struct secpolicy **spp, const char* where, int tag)
 1161 {
 1162         struct secpolicy *sp = *spp;
 1163 
 1164         IPSEC_ASSERT(sp != NULL, ("null sp"));
 1165 
 1166         SPTREE_LOCK();
 1167         SP_DELREF(sp);
 1168 
 1169         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1170                 printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
 1171                         __func__, sp, sp->id, where, tag, sp->refcnt));
 1172 
 1173         if (sp->refcnt == 0) {
 1174                 *spp = NULL;
 1175                 key_delsp(sp);
 1176         }
 1177         SPTREE_UNLOCK();
 1178 }
 1179 
 1180 /*
 1181  * Must be called after calling key_allocsp().
 1182  * For the packet with socket.
 1183  */
 1184 void
 1185 key_freeso(struct socket *so)
 1186 {
 1187         IPSEC_ASSERT(so != NULL, ("null so"));
 1188 
 1189         switch (so->so_proto->pr_domain->dom_family) {
 1190 #if defined(INET) || defined(INET6)
 1191 #ifdef INET
 1192         case PF_INET:
 1193 #endif
 1194 #ifdef INET6
 1195         case PF_INET6:
 1196 #endif
 1197             {
 1198                 struct inpcb *pcb = sotoinpcb(so);
 1199 
 1200                 /* Does it have a PCB ? */
 1201                 if (pcb == NULL)
 1202                         return;
 1203                 key_freesp_so(&pcb->inp_sp->sp_in);
 1204                 key_freesp_so(&pcb->inp_sp->sp_out);
 1205             }
 1206                 break;
 1207 #endif /* INET || INET6 */
 1208         default:
 1209                 ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
 1210                     __func__, so->so_proto->pr_domain->dom_family));
 1211                 return;
 1212         }
 1213 }
 1214 
 1215 static void
 1216 key_freesp_so(struct secpolicy **sp)
 1217 {
 1218         IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
 1219 
 1220         if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
 1221             (*sp)->policy == IPSEC_POLICY_BYPASS)
 1222                 return;
 1223 
 1224         IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
 1225                 ("invalid policy %u", (*sp)->policy));
 1226         KEY_FREESP(sp);
 1227 }
 1228 
 1229 void
 1230 key_addrefsa(struct secasvar *sav, const char* where, int tag)
 1231 {
 1232 
 1233         IPSEC_ASSERT(sav != NULL, ("null sav"));
 1234         IPSEC_ASSERT(sav->refcnt > 0, ("refcount must exist"));
 1235 
 1236         sa_addref(sav);
 1237 }
 1238 
 1239 /*
 1240  * Must be called after calling key_allocsa().
 1241  * This function is called by key_freesp() to free some SA allocated
 1242  * for a policy.
 1243  */
 1244 void
 1245 key_freesav(struct secasvar **psav, const char* where, int tag)
 1246 {
 1247         struct secasvar *sav = *psav;
 1248 
 1249         IPSEC_ASSERT(sav != NULL, ("null sav"));
 1250 
 1251         if (sa_delref(sav)) {
 1252                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1253                         printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
 1254                                 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
 1255                 *psav = NULL;
 1256                 key_delsav(sav);
 1257         } else {
 1258                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1259                         printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
 1260                                 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
 1261         }
 1262 }
 1263 
 1264 /* %%% SPD management */
 1265 /*
 1266  * free security policy entry.
 1267  */
 1268 static void
 1269 key_delsp(struct secpolicy *sp)
 1270 {
 1271         struct ipsecrequest *isr, *nextisr;
 1272 
 1273         IPSEC_ASSERT(sp != NULL, ("null sp"));
 1274         SPTREE_LOCK_ASSERT();
 1275 
 1276         sp->state = IPSEC_SPSTATE_DEAD;
 1277 
 1278         IPSEC_ASSERT(sp->refcnt == 0,
 1279                 ("SP with references deleted (refcnt %u)", sp->refcnt));
 1280 
 1281         /* remove from SP index */
 1282         if (__LIST_CHAINED(sp))
 1283                 LIST_REMOVE(sp, chain);
 1284 
 1285         for (isr = sp->req; isr != NULL; isr = nextisr) {
 1286                 if (isr->sav != NULL) {
 1287                         KEY_FREESAV(&isr->sav);
 1288                         isr->sav = NULL;
 1289                 }
 1290 
 1291                 nextisr = isr->next;
 1292                 ipsec_delisr(isr);
 1293         }
 1294         _key_delsp(sp);
 1295 }
 1296 
 1297 /*
 1298  * search SPD
 1299  * OUT: NULL    : not found
 1300  *      others  : found, pointer to a SP.
 1301  */
 1302 static struct secpolicy *
 1303 key_getsp(struct secpolicyindex *spidx)
 1304 {
 1305         struct secpolicy *sp;
 1306 
 1307         IPSEC_ASSERT(spidx != NULL, ("null spidx"));
 1308 
 1309         SPTREE_LOCK();
 1310         LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
 1311                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1312                         continue;
 1313                 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
 1314                         SP_ADDREF(sp);
 1315                         break;
 1316                 }
 1317         }
 1318         SPTREE_UNLOCK();
 1319 
 1320         return sp;
 1321 }
 1322 
 1323 /*
 1324  * get SP by index.
 1325  * OUT: NULL    : not found
 1326  *      others  : found, pointer to a SP.
 1327  */
 1328 static struct secpolicy *
 1329 key_getspbyid(u_int32_t id)
 1330 {
 1331         struct secpolicy *sp;
 1332 
 1333         SPTREE_LOCK();
 1334         LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
 1335                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1336                         continue;
 1337                 if (sp->id == id) {
 1338                         SP_ADDREF(sp);
 1339                         goto done;
 1340                 }
 1341         }
 1342 
 1343         LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
 1344                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1345                         continue;
 1346                 if (sp->id == id) {
 1347                         SP_ADDREF(sp);
 1348                         goto done;
 1349                 }
 1350         }
 1351 done:
 1352         SPTREE_UNLOCK();
 1353 
 1354         return sp;
 1355 }
 1356 
 1357 struct secpolicy *
 1358 key_newsp(const char* where, int tag)
 1359 {
 1360         struct secpolicy *newsp = NULL;
 1361 
 1362         newsp = (struct secpolicy *)
 1363                 malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
 1364         if (newsp) {
 1365                 SECPOLICY_LOCK_INIT(newsp);
 1366                 newsp->refcnt = 1;
 1367                 newsp->req = NULL;
 1368         }
 1369 
 1370         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1371                 printf("DP %s from %s:%u return SP:%p\n", __func__,
 1372                         where, tag, newsp));
 1373         return newsp;
 1374 }
 1375 
 1376 static void
 1377 _key_delsp(struct secpolicy *sp)
 1378 {
 1379         SECPOLICY_LOCK_DESTROY(sp);
 1380         free(sp, M_IPSEC_SP);
 1381 }
 1382 
 1383 /*
 1384  * create secpolicy structure from sadb_x_policy structure.
 1385  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
 1386  * so must be set properly later.
 1387  */
 1388 struct secpolicy *
 1389 key_msg2sp(xpl0, len, error)
 1390         struct sadb_x_policy *xpl0;
 1391         size_t len;
 1392         int *error;
 1393 {
 1394         struct secpolicy *newsp;
 1395 
 1396         IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
 1397         IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
 1398 
 1399         if (len != PFKEY_EXTLEN(xpl0)) {
 1400                 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
 1401                 *error = EINVAL;
 1402                 return NULL;
 1403         }
 1404 
 1405         if ((newsp = KEY_NEWSP()) == NULL) {
 1406                 *error = ENOBUFS;
 1407                 return NULL;
 1408         }
 1409 
 1410         newsp->spidx.dir = xpl0->sadb_x_policy_dir;
 1411         newsp->policy = xpl0->sadb_x_policy_type;
 1412 
 1413         /* check policy */
 1414         switch (xpl0->sadb_x_policy_type) {
 1415         case IPSEC_POLICY_DISCARD:
 1416         case IPSEC_POLICY_NONE:
 1417         case IPSEC_POLICY_ENTRUST:
 1418         case IPSEC_POLICY_BYPASS:
 1419                 newsp->req = NULL;
 1420                 break;
 1421 
 1422         case IPSEC_POLICY_IPSEC:
 1423             {
 1424                 int tlen;
 1425                 struct sadb_x_ipsecrequest *xisr;
 1426                 struct ipsecrequest **p_isr = &newsp->req;
 1427 
 1428                 /* validity check */
 1429                 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
 1430                         ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
 1431                                 __func__));
 1432                         KEY_FREESP(&newsp);
 1433                         *error = EINVAL;
 1434                         return NULL;
 1435                 }
 1436 
 1437                 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
 1438                 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
 1439 
 1440                 while (tlen > 0) {
 1441                         /* length check */
 1442                         if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
 1443                                 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
 1444                                         "length.\n", __func__));
 1445                                 KEY_FREESP(&newsp);
 1446                                 *error = EINVAL;
 1447                                 return NULL;
 1448                         }
 1449 
 1450                         /* allocate request buffer */
 1451                         /* NB: data structure is zero'd */
 1452                         *p_isr = ipsec_newisr();
 1453                         if ((*p_isr) == NULL) {
 1454                                 ipseclog((LOG_DEBUG,
 1455                                     "%s: No more memory.\n", __func__));
 1456                                 KEY_FREESP(&newsp);
 1457                                 *error = ENOBUFS;
 1458                                 return NULL;
 1459                         }
 1460 
 1461                         /* set values */
 1462                         switch (xisr->sadb_x_ipsecrequest_proto) {
 1463                         case IPPROTO_ESP:
 1464                         case IPPROTO_AH:
 1465                         case IPPROTO_IPCOMP:
 1466                                 break;
 1467                         default:
 1468                                 ipseclog((LOG_DEBUG,
 1469                                     "%s: invalid proto type=%u\n", __func__,
 1470                                     xisr->sadb_x_ipsecrequest_proto));
 1471                                 KEY_FREESP(&newsp);
 1472                                 *error = EPROTONOSUPPORT;
 1473                                 return NULL;
 1474                         }
 1475                         (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
 1476 
 1477                         switch (xisr->sadb_x_ipsecrequest_mode) {
 1478                         case IPSEC_MODE_TRANSPORT:
 1479                         case IPSEC_MODE_TUNNEL:
 1480                                 break;
 1481                         case IPSEC_MODE_ANY:
 1482                         default:
 1483                                 ipseclog((LOG_DEBUG,
 1484                                     "%s: invalid mode=%u\n", __func__,
 1485                                     xisr->sadb_x_ipsecrequest_mode));
 1486                                 KEY_FREESP(&newsp);
 1487                                 *error = EINVAL;
 1488                                 return NULL;
 1489                         }
 1490                         (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
 1491 
 1492                         switch (xisr->sadb_x_ipsecrequest_level) {
 1493                         case IPSEC_LEVEL_DEFAULT:
 1494                         case IPSEC_LEVEL_USE:
 1495                         case IPSEC_LEVEL_REQUIRE:
 1496                                 break;
 1497                         case IPSEC_LEVEL_UNIQUE:
 1498                                 /* validity check */
 1499                                 /*
 1500                                  * If range violation of reqid, kernel will
 1501                                  * update it, don't refuse it.
 1502                                  */
 1503                                 if (xisr->sadb_x_ipsecrequest_reqid
 1504                                                 > IPSEC_MANUAL_REQID_MAX) {
 1505                                         ipseclog((LOG_DEBUG,
 1506                                             "%s: reqid=%d range "
 1507                                             "violation, updated by kernel.\n",
 1508                                             __func__,
 1509                                             xisr->sadb_x_ipsecrequest_reqid));
 1510                                         xisr->sadb_x_ipsecrequest_reqid = 0;
 1511                                 }
 1512 
 1513                                 /* allocate new reqid id if reqid is zero. */
 1514                                 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
 1515                                         u_int32_t reqid;
 1516                                         if ((reqid = key_newreqid()) == 0) {
 1517                                                 KEY_FREESP(&newsp);
 1518                                                 *error = ENOBUFS;
 1519                                                 return NULL;
 1520                                         }
 1521                                         (*p_isr)->saidx.reqid = reqid;
 1522                                         xisr->sadb_x_ipsecrequest_reqid = reqid;
 1523                                 } else {
 1524                                 /* set it for manual keying. */
 1525                                         (*p_isr)->saidx.reqid =
 1526                                                 xisr->sadb_x_ipsecrequest_reqid;
 1527                                 }
 1528                                 break;
 1529 
 1530                         default:
 1531                                 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
 1532                                         __func__,
 1533                                         xisr->sadb_x_ipsecrequest_level));
 1534                                 KEY_FREESP(&newsp);
 1535                                 *error = EINVAL;
 1536                                 return NULL;
 1537                         }
 1538                         (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
 1539 
 1540                         /* set IP addresses if there */
 1541                         if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
 1542                                 struct sockaddr *paddr;
 1543 
 1544                                 paddr = (struct sockaddr *)(xisr + 1);
 1545 
 1546                                 /* validity check */
 1547                                 if (paddr->sa_len
 1548                                     > sizeof((*p_isr)->saidx.src)) {
 1549                                         ipseclog((LOG_DEBUG, "%s: invalid "
 1550                                                 "request address length.\n",
 1551                                                 __func__));
 1552                                         KEY_FREESP(&newsp);
 1553                                         *error = EINVAL;
 1554                                         return NULL;
 1555                                 }
 1556                                 bcopy(paddr, &(*p_isr)->saidx.src,
 1557                                         paddr->sa_len);
 1558 
 1559                                 paddr = (struct sockaddr *)((caddr_t)paddr
 1560                                                         + paddr->sa_len);
 1561 
 1562                                 /* validity check */
 1563                                 if (paddr->sa_len
 1564                                     > sizeof((*p_isr)->saidx.dst)) {
 1565                                         ipseclog((LOG_DEBUG, "%s: invalid "
 1566                                                 "request address length.\n",
 1567                                                 __func__));
 1568                                         KEY_FREESP(&newsp);
 1569                                         *error = EINVAL;
 1570                                         return NULL;
 1571                                 }
 1572                                 bcopy(paddr, &(*p_isr)->saidx.dst,
 1573                                         paddr->sa_len);
 1574                         }
 1575 
 1576                         (*p_isr)->sp = newsp;
 1577 
 1578                         /* initialization for the next. */
 1579                         p_isr = &(*p_isr)->next;
 1580                         tlen -= xisr->sadb_x_ipsecrequest_len;
 1581 
 1582                         /* validity check */
 1583                         if (tlen < 0) {
 1584                                 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
 1585                                         __func__));
 1586                                 KEY_FREESP(&newsp);
 1587                                 *error = EINVAL;
 1588                                 return NULL;
 1589                         }
 1590 
 1591                         xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
 1592                                          + xisr->sadb_x_ipsecrequest_len);
 1593                 }
 1594             }
 1595                 break;
 1596         default:
 1597                 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
 1598                 KEY_FREESP(&newsp);
 1599                 *error = EINVAL;
 1600                 return NULL;
 1601         }
 1602 
 1603         *error = 0;
 1604         return newsp;
 1605 }
 1606 
 1607 static u_int32_t
 1608 key_newreqid()
 1609 {
 1610         static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
 1611 
 1612         auto_reqid = (auto_reqid == ~0
 1613                         ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
 1614 
 1615         /* XXX should be unique check */
 1616 
 1617         return auto_reqid;
 1618 }
 1619 
 1620 /*
 1621  * copy secpolicy struct to sadb_x_policy structure indicated.
 1622  */
 1623 struct mbuf *
 1624 key_sp2msg(sp)
 1625         struct secpolicy *sp;
 1626 {
 1627         struct sadb_x_policy *xpl;
 1628         int tlen;
 1629         caddr_t p;
 1630         struct mbuf *m;
 1631 
 1632         IPSEC_ASSERT(sp != NULL, ("null policy"));
 1633 
 1634         tlen = key_getspreqmsglen(sp);
 1635 
 1636         m = key_alloc_mbuf(tlen);
 1637         if (!m || m->m_next) {  /*XXX*/
 1638                 if (m)
 1639                         m_freem(m);
 1640                 return NULL;
 1641         }
 1642 
 1643         m->m_len = tlen;
 1644         m->m_next = NULL;
 1645         xpl = mtod(m, struct sadb_x_policy *);
 1646         bzero(xpl, tlen);
 1647 
 1648         xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
 1649         xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
 1650         xpl->sadb_x_policy_type = sp->policy;
 1651         xpl->sadb_x_policy_dir = sp->spidx.dir;
 1652         xpl->sadb_x_policy_id = sp->id;
 1653         p = (caddr_t)xpl + sizeof(*xpl);
 1654 
 1655         /* if is the policy for ipsec ? */
 1656         if (sp->policy == IPSEC_POLICY_IPSEC) {
 1657                 struct sadb_x_ipsecrequest *xisr;
 1658                 struct ipsecrequest *isr;
 1659 
 1660                 for (isr = sp->req; isr != NULL; isr = isr->next) {
 1661 
 1662                         xisr = (struct sadb_x_ipsecrequest *)p;
 1663 
 1664                         xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
 1665                         xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
 1666                         xisr->sadb_x_ipsecrequest_level = isr->level;
 1667                         xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
 1668 
 1669                         p += sizeof(*xisr);
 1670                         bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
 1671                         p += isr->saidx.src.sa.sa_len;
 1672                         bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
 1673                         p += isr->saidx.src.sa.sa_len;
 1674 
 1675                         xisr->sadb_x_ipsecrequest_len =
 1676                                 PFKEY_ALIGN8(sizeof(*xisr)
 1677                                         + isr->saidx.src.sa.sa_len
 1678                                         + isr->saidx.dst.sa.sa_len);
 1679                 }
 1680         }
 1681 
 1682         return m;
 1683 }
 1684 
 1685 /* m will not be freed nor modified */
 1686 static struct mbuf *
 1687 #ifdef __STDC__
 1688 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
 1689         int ndeep, int nitem, ...)
 1690 #else
 1691 key_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
 1692         struct mbuf *m;
 1693         const struct sadb_msghdr *mhp;
 1694         int ndeep;
 1695         int nitem;
 1696         va_dcl
 1697 #endif
 1698 {
 1699         va_list ap;
 1700         int idx;
 1701         int i;
 1702         struct mbuf *result = NULL, *n;
 1703         int len;
 1704 
 1705         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 1706         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 1707 
 1708         va_start(ap, nitem);
 1709         for (i = 0; i < nitem; i++) {
 1710                 idx = va_arg(ap, int);
 1711                 if (idx < 0 || idx > SADB_EXT_MAX)
 1712                         goto fail;
 1713                 /* don't attempt to pull empty extension */
 1714                 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
 1715                         continue;
 1716                 if (idx != SADB_EXT_RESERVED  &&
 1717                     (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
 1718                         continue;
 1719 
 1720                 if (idx == SADB_EXT_RESERVED) {
 1721                         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 1722 
 1723                         IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
 1724 
 1725                         MGETHDR(n, M_DONTWAIT, MT_DATA);
 1726                         if (!n)
 1727                                 goto fail;
 1728                         n->m_len = len;
 1729                         n->m_next = NULL;
 1730                         m_copydata(m, 0, sizeof(struct sadb_msg),
 1731                             mtod(n, caddr_t));
 1732                 } else if (i < ndeep) {
 1733                         len = mhp->extlen[idx];
 1734                         n = key_alloc_mbuf(len);
 1735                         if (!n || n->m_next) {  /*XXX*/
 1736                                 if (n)
 1737                                         m_freem(n);
 1738                                 goto fail;
 1739                         }
 1740                         m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
 1741                             mtod(n, caddr_t));
 1742                 } else {
 1743                         n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
 1744                             M_DONTWAIT);
 1745                 }
 1746                 if (n == NULL)
 1747                         goto fail;
 1748 
 1749                 if (result)
 1750                         m_cat(result, n);
 1751                 else
 1752                         result = n;
 1753         }
 1754         va_end(ap);
 1755 
 1756         if ((result->m_flags & M_PKTHDR) != 0) {
 1757                 result->m_pkthdr.len = 0;
 1758                 for (n = result; n; n = n->m_next)
 1759                         result->m_pkthdr.len += n->m_len;
 1760         }
 1761 
 1762         return result;
 1763 
 1764 fail:
 1765         m_freem(result);
 1766         va_end(ap);
 1767         return NULL;
 1768 }
 1769 
 1770 /*
 1771  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
 1772  * add an entry to SP database, when received
 1773  *   <base, address(SD), (lifetime(H),) policy>
 1774  * from the user(?).
 1775  * Adding to SP database,
 1776  * and send
 1777  *   <base, address(SD), (lifetime(H),) policy>
 1778  * to the socket which was send.
 1779  *
 1780  * SPDADD set a unique policy entry.
 1781  * SPDSETIDX like SPDADD without a part of policy requests.
 1782  * SPDUPDATE replace a unique policy entry.
 1783  *
 1784  * m will always be freed.
 1785  */
 1786 static int
 1787 key_spdadd(so, m, mhp)
 1788         struct socket *so;
 1789         struct mbuf *m;
 1790         const struct sadb_msghdr *mhp;
 1791 {
 1792         struct sadb_address *src0, *dst0;
 1793         struct sadb_x_policy *xpl0, *xpl;
 1794         struct sadb_lifetime *lft = NULL;
 1795         struct secpolicyindex spidx;
 1796         struct secpolicy *newsp;
 1797         int error;
 1798 
 1799         IPSEC_ASSERT(so != NULL, ("null socket"));
 1800         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 1801         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 1802         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 1803 
 1804         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 1805             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 1806             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
 1807                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
 1808                 return key_senderror(so, m, EINVAL);
 1809         }
 1810         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 1811             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
 1812             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 1813                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 1814                         __func__));
 1815                 return key_senderror(so, m, EINVAL);
 1816         }
 1817         if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
 1818                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
 1819                         < sizeof(struct sadb_lifetime)) {
 1820                         ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 1821                                 __func__));
 1822                         return key_senderror(so, m, EINVAL);
 1823                 }
 1824                 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
 1825         }
 1826 
 1827         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 1828         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 1829         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
 1830 
 1831         /* 
 1832          * Note: do not parse SADB_X_EXT_NAT_T_* here:
 1833          * we are processing traffic endpoints.
 1834          */
 1835 
 1836         /* make secindex */
 1837         /* XXX boundary check against sa_len */
 1838         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 1839                         src0 + 1,
 1840                         dst0 + 1,
 1841                         src0->sadb_address_prefixlen,
 1842                         dst0->sadb_address_prefixlen,
 1843                         src0->sadb_address_proto,
 1844                         &spidx);
 1845 
 1846         /* checking the direciton. */
 1847         switch (xpl0->sadb_x_policy_dir) {
 1848         case IPSEC_DIR_INBOUND:
 1849         case IPSEC_DIR_OUTBOUND:
 1850                 break;
 1851         default:
 1852                 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
 1853                 mhp->msg->sadb_msg_errno = EINVAL;
 1854                 return 0;
 1855         }
 1856 
 1857         /* check policy */
 1858         /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
 1859         if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
 1860          || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
 1861                 ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
 1862                 return key_senderror(so, m, EINVAL);
 1863         }
 1864 
 1865         /* policy requests are mandatory when action is ipsec. */
 1866         if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
 1867          && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
 1868          && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
 1869                 ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
 1870                         __func__));
 1871                 return key_senderror(so, m, EINVAL);
 1872         }
 1873 
 1874         /*
 1875          * checking there is SP already or not.
 1876          * SPDUPDATE doesn't depend on whether there is a SP or not.
 1877          * If the type is either SPDADD or SPDSETIDX AND a SP is found,
 1878          * then error.
 1879          */
 1880         newsp = key_getsp(&spidx);
 1881         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
 1882                 if (newsp) {
 1883                         SPTREE_LOCK();
 1884                         newsp->state = IPSEC_SPSTATE_DEAD;
 1885                         SPTREE_UNLOCK();
 1886                         KEY_FREESP(&newsp);
 1887                 }
 1888         } else {
 1889                 if (newsp != NULL) {
 1890                         KEY_FREESP(&newsp);
 1891                         ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
 1892                                 __func__));
 1893                         return key_senderror(so, m, EEXIST);
 1894                 }
 1895         }
 1896 
 1897         /* allocation new SP entry */
 1898         if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
 1899                 return key_senderror(so, m, error);
 1900         }
 1901 
 1902         if ((newsp->id = key_getnewspid()) == 0) {
 1903                 _key_delsp(newsp);
 1904                 return key_senderror(so, m, ENOBUFS);
 1905         }
 1906 
 1907         /* XXX boundary check against sa_len */
 1908         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 1909                         src0 + 1,
 1910                         dst0 + 1,
 1911                         src0->sadb_address_prefixlen,
 1912                         dst0->sadb_address_prefixlen,
 1913                         src0->sadb_address_proto,
 1914                         &newsp->spidx);
 1915 
 1916         /* sanity check on addr pair */
 1917         if (((struct sockaddr *)(src0 + 1))->sa_family !=
 1918                         ((struct sockaddr *)(dst0+ 1))->sa_family) {
 1919                 _key_delsp(newsp);
 1920                 return key_senderror(so, m, EINVAL);
 1921         }
 1922         if (((struct sockaddr *)(src0 + 1))->sa_len !=
 1923                         ((struct sockaddr *)(dst0+ 1))->sa_len) {
 1924                 _key_delsp(newsp);
 1925                 return key_senderror(so, m, EINVAL);
 1926         }
 1927 #if 1
 1928         if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
 1929                 struct sockaddr *sa;
 1930                 sa = (struct sockaddr *)(src0 + 1);
 1931                 if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
 1932                         _key_delsp(newsp);
 1933                         return key_senderror(so, m, EINVAL);
 1934                 }
 1935         }
 1936         if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
 1937                 struct sockaddr *sa;
 1938                 sa = (struct sockaddr *)(dst0 + 1);
 1939                 if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
 1940                         _key_delsp(newsp);
 1941                         return key_senderror(so, m, EINVAL);
 1942                 }
 1943         }
 1944 #endif
 1945 
 1946         newsp->created = time_second;
 1947         newsp->lastused = newsp->created;
 1948         newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
 1949         newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
 1950 
 1951         newsp->refcnt = 1;      /* do not reclaim until I say I do */
 1952         newsp->state = IPSEC_SPSTATE_ALIVE;
 1953         LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
 1954 
 1955         /* delete the entry in spacqtree */
 1956         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
 1957                 struct secspacq *spacq = key_getspacq(&spidx);
 1958                 if (spacq != NULL) {
 1959                         /* reset counter in order to deletion by timehandler. */
 1960                         spacq->created = time_second;
 1961                         spacq->count = 0;
 1962                         SPACQ_UNLOCK();
 1963                 }
 1964         }
 1965 
 1966     {
 1967         struct mbuf *n, *mpolicy;
 1968         struct sadb_msg *newmsg;
 1969         int off;
 1970 
 1971         /*
 1972          * Note: do not send SADB_X_EXT_NAT_T_* here:
 1973          * we are sending traffic endpoints.
 1974          */
 1975 
 1976         /* create new sadb_msg to reply. */
 1977         if (lft) {
 1978                 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
 1979                     SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
 1980                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 1981         } else {
 1982                 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
 1983                     SADB_X_EXT_POLICY,
 1984                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 1985         }
 1986         if (!n)
 1987                 return key_senderror(so, m, ENOBUFS);
 1988 
 1989         if (n->m_len < sizeof(*newmsg)) {
 1990                 n = m_pullup(n, sizeof(*newmsg));
 1991                 if (!n)
 1992                         return key_senderror(so, m, ENOBUFS);
 1993         }
 1994         newmsg = mtod(n, struct sadb_msg *);
 1995         newmsg->sadb_msg_errno = 0;
 1996         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 1997 
 1998         off = 0;
 1999         mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
 2000             sizeof(*xpl), &off);
 2001         if (mpolicy == NULL) {
 2002                 /* n is already freed */
 2003                 return key_senderror(so, m, ENOBUFS);
 2004         }
 2005         xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
 2006         if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
 2007                 m_freem(n);
 2008                 return key_senderror(so, m, EINVAL);
 2009         }
 2010         xpl->sadb_x_policy_id = newsp->id;
 2011 
 2012         m_freem(m);
 2013         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 2014     }
 2015 }
 2016 
 2017 /*
 2018  * get new policy id.
 2019  * OUT:
 2020  *      0:      failure.
 2021  *      others: success.
 2022  */
 2023 static u_int32_t
 2024 key_getnewspid()
 2025 {
 2026         u_int32_t newid = 0;
 2027         int count = V_key_spi_trycnt;   /* XXX */
 2028         struct secpolicy *sp;
 2029 
 2030         /* when requesting to allocate spi ranged */
 2031         while (count--) {
 2032                 newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
 2033 
 2034                 if ((sp = key_getspbyid(newid)) == NULL)
 2035                         break;
 2036 
 2037                 KEY_FREESP(&sp);
 2038         }
 2039 
 2040         if (count == 0 || newid == 0) {
 2041                 ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
 2042                         __func__));
 2043                 return 0;
 2044         }
 2045 
 2046         return newid;
 2047 }
 2048 
 2049 /*
 2050  * SADB_SPDDELETE processing
 2051  * receive
 2052  *   <base, address(SD), policy(*)>
 2053  * from the user(?), and set SADB_SASTATE_DEAD,
 2054  * and send,
 2055  *   <base, address(SD), policy(*)>
 2056  * to the ikmpd.
 2057  * policy(*) including direction of policy.
 2058  *
 2059  * m will always be freed.
 2060  */
 2061 static int
 2062 key_spddelete(so, m, mhp)
 2063         struct socket *so;
 2064         struct mbuf *m;
 2065         const struct sadb_msghdr *mhp;
 2066 {
 2067         struct sadb_address *src0, *dst0;
 2068         struct sadb_x_policy *xpl0;
 2069         struct secpolicyindex spidx;
 2070         struct secpolicy *sp;
 2071 
 2072         IPSEC_ASSERT(so != NULL, ("null so"));
 2073         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 2074         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 2075         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 2076 
 2077         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 2078             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 2079             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
 2080                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 2081                         __func__));
 2082                 return key_senderror(so, m, EINVAL);
 2083         }
 2084         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 2085             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
 2086             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 2087                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 2088                         __func__));
 2089                 return key_senderror(so, m, EINVAL);
 2090         }
 2091 
 2092         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 2093         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 2094         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
 2095 
 2096         /*
 2097          * Note: do not parse SADB_X_EXT_NAT_T_* here:
 2098          * we are processing traffic endpoints.
 2099          */
 2100 
 2101         /* make secindex */
 2102         /* XXX boundary check against sa_len */
 2103         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 2104                         src0 + 1,
 2105                         dst0 + 1,
 2106                         src0->sadb_address_prefixlen,
 2107                         dst0->sadb_address_prefixlen,
 2108                         src0->sadb_address_proto,
 2109                         &spidx);
 2110 
 2111         /* checking the direciton. */
 2112         switch (xpl0->sadb_x_policy_dir) {
 2113         case IPSEC_DIR_INBOUND:
 2114         case IPSEC_DIR_OUTBOUND:
 2115                 break;
 2116         default:
 2117                 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
 2118                 return key_senderror(so, m, EINVAL);
 2119         }
 2120 
 2121         /* Is there SP in SPD ? */
 2122         if ((sp = key_getsp(&spidx)) == NULL) {
 2123                 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
 2124                 return key_senderror(so, m, EINVAL);
 2125         }
 2126 
 2127         /* save policy id to buffer to be returned. */
 2128         xpl0->sadb_x_policy_id = sp->id;
 2129 
 2130         SPTREE_LOCK();
 2131         sp->state = IPSEC_SPSTATE_DEAD;
 2132         SPTREE_UNLOCK();
 2133         KEY_FREESP(&sp);
 2134 
 2135     {
 2136         struct mbuf *n;
 2137         struct sadb_msg *newmsg;
 2138 
 2139         /*
 2140          * Note: do not send SADB_X_EXT_NAT_T_* here:
 2141          * we are sending traffic endpoints.
 2142          */
 2143 
 2144         /* create new sadb_msg to reply. */
 2145         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
 2146             SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 2147         if (!n)
 2148                 return key_senderror(so, m, ENOBUFS);
 2149 
 2150         newmsg = mtod(n, struct sadb_msg *);
 2151         newmsg->sadb_msg_errno = 0;
 2152         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 2153 
 2154         m_freem(m);
 2155         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 2156     }
 2157 }
 2158 
 2159 /*
 2160  * SADB_SPDDELETE2 processing
 2161  * receive
 2162  *   <base, policy(*)>
 2163  * from the user(?), and set SADB_SASTATE_DEAD,
 2164  * and send,
 2165  *   <base, policy(*)>
 2166  * to the ikmpd.
 2167  * policy(*) including direction of policy.
 2168  *
 2169  * m will always be freed.
 2170  */
 2171 static int
 2172 key_spddelete2(so, m, mhp)
 2173         struct socket *so;
 2174         struct mbuf *m;
 2175         const struct sadb_msghdr *mhp;
 2176 {
 2177         u_int32_t id;
 2178         struct secpolicy *sp;
 2179 
 2180         IPSEC_ASSERT(so != NULL, ("null socket"));
 2181         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 2182         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 2183         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 2184 
 2185         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
 2186             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 2187                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
 2188                 return key_senderror(so, m, EINVAL);
 2189         }
 2190 
 2191         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
 2192 
 2193         /* Is there SP in SPD ? */
 2194         if ((sp = key_getspbyid(id)) == NULL) {
 2195                 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
 2196                 return key_senderror(so, m, EINVAL);
 2197         }
 2198 
 2199         SPTREE_LOCK();
 2200         sp->state = IPSEC_SPSTATE_DEAD;
 2201         SPTREE_UNLOCK();
 2202         KEY_FREESP(&sp);
 2203 
 2204     {
 2205         struct mbuf *n, *nn;
 2206         struct sadb_msg *newmsg;
 2207         int off, len;
 2208 
 2209         /* create new sadb_msg to reply. */
 2210         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2211 
 2212         MGETHDR(n, M_DONTWAIT, MT_DATA);
 2213         if (n && len > MHLEN) {
 2214                 MCLGET(n, M_DONTWAIT);
 2215                 if ((n->m_flags & M_EXT) == 0) {
 2216                         m_freem(n);
 2217                         n = NULL;
 2218                 }
 2219         }
 2220         if (!n)
 2221                 return key_senderror(so, m, ENOBUFS);
 2222 
 2223         n->m_len = len;
 2224         n->m_next = NULL;
 2225         off = 0;
 2226 
 2227         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
 2228         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2229 
 2230         IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
 2231                 off, len));
 2232 
 2233         n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
 2234             mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
 2235         if (!n->m_next) {
 2236                 m_freem(n);
 2237                 return key_senderror(so, m, ENOBUFS);
 2238         }
 2239 
 2240         n->m_pkthdr.len = 0;
 2241         for (nn = n; nn; nn = nn->m_next)
 2242                 n->m_pkthdr.len += nn->m_len;
 2243 
 2244         newmsg = mtod(n, struct sadb_msg *);
 2245         newmsg->sadb_msg_errno = 0;
 2246         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 2247 
 2248         m_freem(m);
 2249         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 2250     }
 2251 }
 2252 
 2253 /*
 2254  * SADB_X_GET processing
 2255  * receive
 2256  *   <base, policy(*)>
 2257  * from the user(?),
 2258  * and send,
 2259  *   <base, address(SD), policy>
 2260  * to the ikmpd.
 2261  * policy(*) including direction of policy.
 2262  *
 2263  * m will always be freed.
 2264  */
 2265 static int
 2266 key_spdget(so, m, mhp)
 2267         struct socket *so;
 2268         struct mbuf *m;
 2269         const struct sadb_msghdr *mhp;
 2270 {
 2271         u_int32_t id;
 2272         struct secpolicy *sp;
 2273         struct mbuf *n;
 2274 
 2275         IPSEC_ASSERT(so != NULL, ("null socket"));
 2276         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 2277         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 2278         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 2279 
 2280         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
 2281             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 2282                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 2283                         __func__));
 2284                 return key_senderror(so, m, EINVAL);
 2285         }
 2286 
 2287         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
 2288 
 2289         /* Is there SP in SPD ? */
 2290         if ((sp = key_getspbyid(id)) == NULL) {
 2291                 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
 2292                 return key_senderror(so, m, ENOENT);
 2293         }
 2294 
 2295         n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
 2296         KEY_FREESP(&sp);
 2297         if (n != NULL) {
 2298                 m_freem(m);
 2299                 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 2300         } else
 2301                 return key_senderror(so, m, ENOBUFS);
 2302 }
 2303 
 2304 /*
 2305  * SADB_X_SPDACQUIRE processing.
 2306  * Acquire policy and SA(s) for a *OUTBOUND* packet.
 2307  * send
 2308  *   <base, policy(*)>
 2309  * to KMD, and expect to receive
 2310  *   <base> with SADB_X_SPDACQUIRE if error occured,
 2311  * or
 2312  *   <base, policy>
 2313  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
 2314  * policy(*) is without policy requests.
 2315  *
 2316  *    0     : succeed
 2317  *    others: error number
 2318  */
 2319 int
 2320 key_spdacquire(sp)
 2321         struct secpolicy *sp;
 2322 {
 2323         struct mbuf *result = NULL, *m;
 2324         struct secspacq *newspacq;
 2325 
 2326         IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
 2327         IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
 2328         IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
 2329                 ("policy not IPSEC %u", sp->policy));
 2330 
 2331         /* Get an entry to check whether sent message or not. */
 2332         newspacq = key_getspacq(&sp->spidx);
 2333         if (newspacq != NULL) {
 2334                 if (V_key_blockacq_count < newspacq->count) {
 2335                         /* reset counter and do send message. */
 2336                         newspacq->count = 0;
 2337                 } else {
 2338                         /* increment counter and do nothing. */
 2339                         newspacq->count++;
 2340                         return 0;
 2341                 }
 2342                 SPACQ_UNLOCK();
 2343         } else {
 2344                 /* make new entry for blocking to send SADB_ACQUIRE. */
 2345                 newspacq = key_newspacq(&sp->spidx);
 2346                 if (newspacq == NULL)
 2347                         return ENOBUFS;
 2348         }
 2349 
 2350         /* create new sadb_msg to reply. */
 2351         m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
 2352         if (!m)
 2353                 return ENOBUFS;
 2354 
 2355         result = m;
 2356 
 2357         result->m_pkthdr.len = 0;
 2358         for (m = result; m; m = m->m_next)
 2359                 result->m_pkthdr.len += m->m_len;
 2360 
 2361         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2362             PFKEY_UNIT64(result->m_pkthdr.len);
 2363 
 2364         return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
 2365 }
 2366 
 2367 /*
 2368  * SADB_SPDFLUSH processing
 2369  * receive
 2370  *   <base>
 2371  * from the user, and free all entries in secpctree.
 2372  * and send,
 2373  *   <base>
 2374  * to the user.
 2375  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
 2376  *
 2377  * m will always be freed.
 2378  */
 2379 static int
 2380 key_spdflush(so, m, mhp)
 2381         struct socket *so;
 2382         struct mbuf *m;
 2383         const struct sadb_msghdr *mhp;
 2384 {
 2385         struct sadb_msg *newmsg;
 2386         struct secpolicy *sp;
 2387         u_int dir;
 2388 
 2389         IPSEC_ASSERT(so != NULL, ("null socket"));
 2390         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 2391         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 2392         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 2393 
 2394         if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
 2395                 return key_senderror(so, m, EINVAL);
 2396 
 2397         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2398                 SPTREE_LOCK();
 2399                 LIST_FOREACH(sp, &V_sptree[dir], chain)
 2400                         sp->state = IPSEC_SPSTATE_DEAD;
 2401                 SPTREE_UNLOCK();
 2402         }
 2403 
 2404         if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
 2405                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 2406                 return key_senderror(so, m, ENOBUFS);
 2407         }
 2408 
 2409         if (m->m_next)
 2410                 m_freem(m->m_next);
 2411         m->m_next = NULL;
 2412         m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2413         newmsg = mtod(m, struct sadb_msg *);
 2414         newmsg->sadb_msg_errno = 0;
 2415         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
 2416 
 2417         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 2418 }
 2419 
 2420 /*
 2421  * SADB_SPDDUMP processing
 2422  * receive
 2423  *   <base>
 2424  * from the user, and dump all SP leaves
 2425  * and send,
 2426  *   <base> .....
 2427  * to the ikmpd.
 2428  *
 2429  * m will always be freed.
 2430  */
 2431 static int
 2432 key_spddump(so, m, mhp)
 2433         struct socket *so;
 2434         struct mbuf *m;
 2435         const struct sadb_msghdr *mhp;
 2436 {
 2437         struct secpolicy *sp;
 2438         int cnt;
 2439         u_int dir;
 2440         struct mbuf *n;
 2441 
 2442         IPSEC_ASSERT(so != NULL, ("null socket"));
 2443         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 2444         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 2445         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 2446 
 2447         /* search SPD entry and get buffer size. */
 2448         cnt = 0;
 2449         SPTREE_LOCK();
 2450         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2451                 LIST_FOREACH(sp, &V_sptree[dir], chain) {
 2452                         cnt++;
 2453                 }
 2454         }
 2455 
 2456         if (cnt == 0) {
 2457                 SPTREE_UNLOCK();
 2458                 return key_senderror(so, m, ENOENT);
 2459         }
 2460 
 2461         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2462                 LIST_FOREACH(sp, &V_sptree[dir], chain) {
 2463                         --cnt;
 2464                         n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
 2465                             mhp->msg->sadb_msg_pid);
 2466 
 2467                         if (n)
 2468                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 2469                 }
 2470         }
 2471 
 2472         SPTREE_UNLOCK();
 2473         m_freem(m);
 2474         return 0;
 2475 }
 2476 
 2477 static struct mbuf *
 2478 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
 2479 {
 2480         struct mbuf *result = NULL, *m;
 2481         struct seclifetime lt;
 2482 
 2483         m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
 2484         if (!m)
 2485                 goto fail;
 2486         result = m;
 2487 
 2488         /*
 2489          * Note: do not send SADB_X_EXT_NAT_T_* here:
 2490          * we are sending traffic endpoints.
 2491          */
 2492         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 2493             &sp->spidx.src.sa, sp->spidx.prefs,
 2494             sp->spidx.ul_proto);
 2495         if (!m)
 2496                 goto fail;
 2497         m_cat(result, m);
 2498 
 2499         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 2500             &sp->spidx.dst.sa, sp->spidx.prefd,
 2501             sp->spidx.ul_proto);
 2502         if (!m)
 2503                 goto fail;
 2504         m_cat(result, m);
 2505 
 2506         m = key_sp2msg(sp);
 2507         if (!m)
 2508                 goto fail;
 2509         m_cat(result, m);
 2510 
 2511         if(sp->lifetime){
 2512                 lt.addtime=sp->created;
 2513                 lt.usetime= sp->lastused;
 2514                 m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
 2515                 if (!m)
 2516                         goto fail;
 2517                 m_cat(result, m);
 2518                 
 2519                 lt.addtime=sp->lifetime;
 2520                 lt.usetime= sp->validtime;
 2521                 m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
 2522                 if (!m)
 2523                         goto fail;
 2524                 m_cat(result, m);
 2525         }
 2526 
 2527         if ((result->m_flags & M_PKTHDR) == 0)
 2528                 goto fail;
 2529 
 2530         if (result->m_len < sizeof(struct sadb_msg)) {
 2531                 result = m_pullup(result, sizeof(struct sadb_msg));
 2532                 if (result == NULL)
 2533                         goto fail;
 2534         }
 2535 
 2536         result->m_pkthdr.len = 0;
 2537         for (m = result; m; m = m->m_next)
 2538                 result->m_pkthdr.len += m->m_len;
 2539 
 2540         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2541             PFKEY_UNIT64(result->m_pkthdr.len);
 2542 
 2543         return result;
 2544 
 2545 fail:
 2546         m_freem(result);
 2547         return NULL;
 2548 }
 2549 
 2550 /*
 2551  * get PFKEY message length for security policy and request.
 2552  */
 2553 static u_int
 2554 key_getspreqmsglen(sp)
 2555         struct secpolicy *sp;
 2556 {
 2557         u_int tlen;
 2558 
 2559         tlen = sizeof(struct sadb_x_policy);
 2560 
 2561         /* if is the policy for ipsec ? */
 2562         if (sp->policy != IPSEC_POLICY_IPSEC)
 2563                 return tlen;
 2564 
 2565         /* get length of ipsec requests */
 2566     {
 2567         struct ipsecrequest *isr;
 2568         int len;
 2569 
 2570         for (isr = sp->req; isr != NULL; isr = isr->next) {
 2571                 len = sizeof(struct sadb_x_ipsecrequest)
 2572                         + isr->saidx.src.sa.sa_len
 2573                         + isr->saidx.dst.sa.sa_len;
 2574 
 2575                 tlen += PFKEY_ALIGN8(len);
 2576         }
 2577     }
 2578 
 2579         return tlen;
 2580 }
 2581 
 2582 /*
 2583  * SADB_SPDEXPIRE processing
 2584  * send
 2585  *   <base, address(SD), lifetime(CH), policy>
 2586  * to KMD by PF_KEY.
 2587  *
 2588  * OUT: 0       : succeed
 2589  *      others  : error number
 2590  */
 2591 static int
 2592 key_spdexpire(sp)
 2593         struct secpolicy *sp;
 2594 {
 2595         struct mbuf *result = NULL, *m;
 2596         int len;
 2597         int error = -1;
 2598         struct sadb_lifetime *lt;
 2599 
 2600         /* XXX: Why do we lock ? */
 2601 
 2602         IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
 2603 
 2604         /* set msg header */
 2605         m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
 2606         if (!m) {
 2607                 error = ENOBUFS;
 2608                 goto fail;
 2609         }
 2610         result = m;
 2611 
 2612         /* create lifetime extension (current and hard) */
 2613         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
 2614         m = key_alloc_mbuf(len);
 2615         if (!m || m->m_next) {  /*XXX*/
 2616                 if (m)
 2617                         m_freem(m);
 2618                 error = ENOBUFS;
 2619                 goto fail;
 2620         }
 2621         bzero(mtod(m, caddr_t), len);
 2622         lt = mtod(m, struct sadb_lifetime *);
 2623         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 2624         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
 2625         lt->sadb_lifetime_allocations = 0;
 2626         lt->sadb_lifetime_bytes = 0;
 2627         lt->sadb_lifetime_addtime = sp->created;
 2628         lt->sadb_lifetime_usetime = sp->lastused;
 2629         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
 2630         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 2631         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
 2632         lt->sadb_lifetime_allocations = 0;
 2633         lt->sadb_lifetime_bytes = 0;
 2634         lt->sadb_lifetime_addtime = sp->lifetime;
 2635         lt->sadb_lifetime_usetime = sp->validtime;
 2636         m_cat(result, m);
 2637 
 2638         /*
 2639          * Note: do not send SADB_X_EXT_NAT_T_* here:
 2640          * we are sending traffic endpoints.
 2641          */
 2642 
 2643         /* set sadb_address for source */
 2644         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 2645             &sp->spidx.src.sa,
 2646             sp->spidx.prefs, sp->spidx.ul_proto);
 2647         if (!m) {
 2648                 error = ENOBUFS;
 2649                 goto fail;
 2650         }
 2651         m_cat(result, m);
 2652 
 2653         /* set sadb_address for destination */
 2654         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 2655             &sp->spidx.dst.sa,
 2656             sp->spidx.prefd, sp->spidx.ul_proto);
 2657         if (!m) {
 2658                 error = ENOBUFS;
 2659                 goto fail;
 2660         }
 2661         m_cat(result, m);
 2662 
 2663         /* set secpolicy */
 2664         m = key_sp2msg(sp);
 2665         if (!m) {
 2666                 error = ENOBUFS;
 2667                 goto fail;
 2668         }
 2669         m_cat(result, m);
 2670 
 2671         if ((result->m_flags & M_PKTHDR) == 0) {
 2672                 error = EINVAL;
 2673                 goto fail;
 2674         }
 2675 
 2676         if (result->m_len < sizeof(struct sadb_msg)) {
 2677                 result = m_pullup(result, sizeof(struct sadb_msg));
 2678                 if (result == NULL) {
 2679                         error = ENOBUFS;
 2680                         goto fail;
 2681                 }
 2682         }
 2683 
 2684         result->m_pkthdr.len = 0;
 2685         for (m = result; m; m = m->m_next)
 2686                 result->m_pkthdr.len += m->m_len;
 2687 
 2688         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2689             PFKEY_UNIT64(result->m_pkthdr.len);
 2690 
 2691         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
 2692 
 2693  fail:
 2694         if (result)
 2695                 m_freem(result);
 2696         return error;
 2697 }
 2698 
 2699 /* %%% SAD management */
 2700 /*
 2701  * allocating a memory for new SA head, and copy from the values of mhp.
 2702  * OUT: NULL    : failure due to the lack of memory.
 2703  *      others  : pointer to new SA head.
 2704  */
 2705 static struct secashead *
 2706 key_newsah(saidx)
 2707         struct secasindex *saidx;
 2708 {
 2709         struct secashead *newsah;
 2710 
 2711         IPSEC_ASSERT(saidx != NULL, ("null saidx"));
 2712 
 2713         newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
 2714         if (newsah != NULL) {
 2715                 int i;
 2716                 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
 2717                         LIST_INIT(&newsah->savtree[i]);
 2718                 newsah->saidx = *saidx;
 2719 
 2720                 /* add to saidxtree */
 2721                 newsah->state = SADB_SASTATE_MATURE;
 2722 
 2723                 SAHTREE_LOCK();
 2724                 LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
 2725                 SAHTREE_UNLOCK();
 2726         }
 2727         return(newsah);
 2728 }
 2729 
 2730 /*
 2731  * delete SA index and all SA registerd.
 2732  */
 2733 static void
 2734 key_delsah(sah)
 2735         struct secashead *sah;
 2736 {
 2737         struct secasvar *sav, *nextsav;
 2738         u_int stateidx;
 2739         int zombie = 0;
 2740 
 2741         IPSEC_ASSERT(sah != NULL, ("NULL sah"));
 2742         SAHTREE_LOCK_ASSERT();
 2743 
 2744         /* searching all SA registerd in the secindex. */
 2745         for (stateidx = 0;
 2746              stateidx < _ARRAYLEN(saorder_state_any);
 2747              stateidx++) {
 2748                 u_int state = saorder_state_any[stateidx];
 2749                 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
 2750                         if (sav->refcnt == 0) {
 2751                                 /* sanity check */
 2752                                 KEY_CHKSASTATE(state, sav->state, __func__);
 2753                                 /* 
 2754                                  * do NOT call KEY_FREESAV here:
 2755                                  * it will only delete the sav if refcnt == 1,
 2756                                  * where we already know that refcnt == 0
 2757                                  */
 2758                                 key_delsav(sav);
 2759                         } else {
 2760                                 /* give up to delete this sa */
 2761                                 zombie++;
 2762                         }
 2763                 }
 2764         }
 2765         if (!zombie) {          /* delete only if there are savs */
 2766                 /* remove from tree of SA index */
 2767                 if (__LIST_CHAINED(sah))
 2768                         LIST_REMOVE(sah, chain);
 2769                 if (sah->route_cache.sa_route.ro_rt) {
 2770                         RTFREE(sah->route_cache.sa_route.ro_rt);
 2771                         sah->route_cache.sa_route.ro_rt = (struct rtentry *)NULL;
 2772                 }
 2773                 free(sah, M_IPSEC_SAH);
 2774         }
 2775 }
 2776 
 2777 /*
 2778  * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
 2779  * and copy the values of mhp into new buffer.
 2780  * When SAD message type is GETSPI:
 2781  *      to set sequence number from acq_seq++,
 2782  *      to set zero to SPI.
 2783  *      not to call key_setsava().
 2784  * OUT: NULL    : fail
 2785  *      others  : pointer to new secasvar.
 2786  *
 2787  * does not modify mbuf.  does not free mbuf on error.
 2788  */
 2789 static struct secasvar *
 2790 key_newsav(m, mhp, sah, errp, where, tag)
 2791         struct mbuf *m;
 2792         const struct sadb_msghdr *mhp;
 2793         struct secashead *sah;
 2794         int *errp;
 2795         const char* where;
 2796         int tag;
 2797 {
 2798         struct secasvar *newsav;
 2799         const struct sadb_sa *xsa;
 2800 
 2801         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 2802         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 2803         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 2804         IPSEC_ASSERT(sah != NULL, ("null secashead"));
 2805 
 2806         newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
 2807         if (newsav == NULL) {
 2808                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 2809                 *errp = ENOBUFS;
 2810                 goto done;
 2811         }
 2812 
 2813         switch (mhp->msg->sadb_msg_type) {
 2814         case SADB_GETSPI:
 2815                 newsav->spi = 0;
 2816 
 2817 #ifdef IPSEC_DOSEQCHECK
 2818                 /* sync sequence number */
 2819                 if (mhp->msg->sadb_msg_seq == 0)
 2820                         newsav->seq =
 2821                                 (V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
 2822                 else
 2823 #endif
 2824                         newsav->seq = mhp->msg->sadb_msg_seq;
 2825                 break;
 2826 
 2827         case SADB_ADD:
 2828                 /* sanity check */
 2829                 if (mhp->ext[SADB_EXT_SA] == NULL) {
 2830                         free(newsav, M_IPSEC_SA);
 2831                         newsav = NULL;
 2832                         ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 2833                                 __func__));
 2834                         *errp = EINVAL;
 2835                         goto done;
 2836                 }
 2837                 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 2838                 newsav->spi = xsa->sadb_sa_spi;
 2839                 newsav->seq = mhp->msg->sadb_msg_seq;
 2840                 break;
 2841         default:
 2842                 free(newsav, M_IPSEC_SA);
 2843                 newsav = NULL;
 2844                 *errp = EINVAL;
 2845                 goto done;
 2846         }
 2847 
 2848 
 2849         /* copy sav values */
 2850         if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
 2851                 *errp = key_setsaval(newsav, m, mhp);
 2852                 if (*errp) {
 2853                         free(newsav, M_IPSEC_SA);
 2854                         newsav = NULL;
 2855                         goto done;
 2856                 }
 2857         }
 2858 
 2859         SECASVAR_LOCK_INIT(newsav);
 2860 
 2861         /* reset created */
 2862         newsav->created = time_second;
 2863         newsav->pid = mhp->msg->sadb_msg_pid;
 2864 
 2865         /* add to satree */
 2866         newsav->sah = sah;
 2867         sa_initref(newsav);
 2868         newsav->state = SADB_SASTATE_LARVAL;
 2869 
 2870         SAHTREE_LOCK();
 2871         LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
 2872                         secasvar, chain);
 2873         SAHTREE_UNLOCK();
 2874 done:
 2875         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 2876                 printf("DP %s from %s:%u return SP:%p\n", __func__,
 2877                         where, tag, newsav));
 2878 
 2879         return newsav;
 2880 }
 2881 
 2882 /*
 2883  * free() SA variable entry.
 2884  */
 2885 static void
 2886 key_cleansav(struct secasvar *sav)
 2887 {
 2888         /*
 2889          * Cleanup xform state.  Note that zeroize'ing causes the
 2890          * keys to be cleared; otherwise we must do it ourself.
 2891          */
 2892         if (sav->tdb_xform != NULL) {
 2893                 sav->tdb_xform->xf_zeroize(sav);
 2894                 sav->tdb_xform = NULL;
 2895         } else {
 2896                 KASSERT(sav->iv == NULL, ("iv but no xform"));
 2897                 if (sav->key_auth != NULL)
 2898                         bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
 2899                 if (sav->key_enc != NULL)
 2900                         bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
 2901         }
 2902         if (sav->key_auth != NULL) {
 2903                 if (sav->key_auth->key_data != NULL)
 2904                         free(sav->key_auth->key_data, M_IPSEC_MISC);
 2905                 free(sav->key_auth, M_IPSEC_MISC);
 2906                 sav->key_auth = NULL;
 2907         }
 2908         if (sav->key_enc != NULL) {
 2909                 if (sav->key_enc->key_data != NULL)
 2910                         free(sav->key_enc->key_data, M_IPSEC_MISC);
 2911                 free(sav->key_enc, M_IPSEC_MISC);
 2912                 sav->key_enc = NULL;
 2913         }
 2914         if (sav->sched) {
 2915                 bzero(sav->sched, sav->schedlen);
 2916                 free(sav->sched, M_IPSEC_MISC);
 2917                 sav->sched = NULL;
 2918         }
 2919         if (sav->replay != NULL) {
 2920                 free(sav->replay, M_IPSEC_MISC);
 2921                 sav->replay = NULL;
 2922         }
 2923         if (sav->lft_c != NULL) {
 2924                 free(sav->lft_c, M_IPSEC_MISC);
 2925                 sav->lft_c = NULL;
 2926         }
 2927         if (sav->lft_h != NULL) {
 2928                 free(sav->lft_h, M_IPSEC_MISC);
 2929                 sav->lft_h = NULL;
 2930         }
 2931         if (sav->lft_s != NULL) {
 2932                 free(sav->lft_s, M_IPSEC_MISC);
 2933                 sav->lft_s = NULL;
 2934         }
 2935 }
 2936 
 2937 /*
 2938  * free() SA variable entry.
 2939  */
 2940 static void
 2941 key_delsav(sav)
 2942         struct secasvar *sav;
 2943 {
 2944         IPSEC_ASSERT(sav != NULL, ("null sav"));
 2945         IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
 2946 
 2947         /* remove from SA header */
 2948         if (__LIST_CHAINED(sav))
 2949                 LIST_REMOVE(sav, chain);
 2950         key_cleansav(sav);
 2951         SECASVAR_LOCK_DESTROY(sav);
 2952         free(sav, M_IPSEC_SA);
 2953 }
 2954 
 2955 /*
 2956  * search SAD.
 2957  * OUT:
 2958  *      NULL    : not found
 2959  *      others  : found, pointer to a SA.
 2960  */
 2961 static struct secashead *
 2962 key_getsah(saidx)
 2963         struct secasindex *saidx;
 2964 {
 2965         struct secashead *sah;
 2966 
 2967         SAHTREE_LOCK();
 2968         LIST_FOREACH(sah, &V_sahtree, chain) {
 2969                 if (sah->state == SADB_SASTATE_DEAD)
 2970                         continue;
 2971                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
 2972                         break;
 2973         }
 2974         SAHTREE_UNLOCK();
 2975 
 2976         return sah;
 2977 }
 2978 
 2979 /*
 2980  * check not to be duplicated SPI.
 2981  * NOTE: this function is too slow due to searching all SAD.
 2982  * OUT:
 2983  *      NULL    : not found
 2984  *      others  : found, pointer to a SA.
 2985  */
 2986 static struct secasvar *
 2987 key_checkspidup(saidx, spi)
 2988         struct secasindex *saidx;
 2989         u_int32_t spi;
 2990 {
 2991         struct secashead *sah;
 2992         struct secasvar *sav;
 2993 
 2994         /* check address family */
 2995         if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
 2996                 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
 2997                         __func__));
 2998                 return NULL;
 2999         }
 3000 
 3001         sav = NULL;
 3002         /* check all SAD */
 3003         SAHTREE_LOCK();
 3004         LIST_FOREACH(sah, &V_sahtree, chain) {
 3005                 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
 3006                         continue;
 3007                 sav = key_getsavbyspi(sah, spi);
 3008                 if (sav != NULL)
 3009                         break;
 3010         }
 3011         SAHTREE_UNLOCK();
 3012 
 3013         return sav;
 3014 }
 3015 
 3016 /*
 3017  * search SAD litmited alive SA, protocol, SPI.
 3018  * OUT:
 3019  *      NULL    : not found
 3020  *      others  : found, pointer to a SA.
 3021  */
 3022 static struct secasvar *
 3023 key_getsavbyspi(sah, spi)
 3024         struct secashead *sah;
 3025         u_int32_t spi;
 3026 {
 3027         struct secasvar *sav;
 3028         u_int stateidx, state;
 3029 
 3030         sav = NULL;
 3031         SAHTREE_LOCK_ASSERT();
 3032         /* search all status */
 3033         for (stateidx = 0;
 3034              stateidx < _ARRAYLEN(saorder_state_alive);
 3035              stateidx++) {
 3036 
 3037                 state = saorder_state_alive[stateidx];
 3038                 LIST_FOREACH(sav, &sah->savtree[state], chain) {
 3039 
 3040                         /* sanity check */
 3041                         if (sav->state != state) {
 3042                                 ipseclog((LOG_DEBUG, "%s: "
 3043                                     "invalid sav->state (queue: %d SA: %d)\n",
 3044                                     __func__, state, sav->state));
 3045                                 continue;
 3046                         }
 3047 
 3048                         if (sav->spi == spi)
 3049                                 return sav;
 3050                 }
 3051         }
 3052 
 3053         return NULL;
 3054 }
 3055 
 3056 /*
 3057  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
 3058  * You must update these if need.
 3059  * OUT: 0:      success.
 3060  *      !0:     failure.
 3061  *
 3062  * does not modify mbuf.  does not free mbuf on error.
 3063  */
 3064 static int
 3065 key_setsaval(sav, m, mhp)
 3066         struct secasvar *sav;
 3067         struct mbuf *m;
 3068         const struct sadb_msghdr *mhp;
 3069 {
 3070         int error = 0;
 3071 
 3072         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 3073         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 3074         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 3075 
 3076         /* initialization */
 3077         sav->replay = NULL;
 3078         sav->key_auth = NULL;
 3079         sav->key_enc = NULL;
 3080         sav->sched = NULL;
 3081         sav->schedlen = 0;
 3082         sav->iv = NULL;
 3083         sav->lft_c = NULL;
 3084         sav->lft_h = NULL;
 3085         sav->lft_s = NULL;
 3086         sav->tdb_xform = NULL;          /* transform */
 3087         sav->tdb_encalgxform = NULL;    /* encoding algorithm */
 3088         sav->tdb_authalgxform = NULL;   /* authentication algorithm */
 3089         sav->tdb_compalgxform = NULL;   /* compression algorithm */
 3090         /*  Initialize even if NAT-T not compiled in: */
 3091         sav->natt_type = 0;
 3092         sav->natt_esp_frag_len = 0;
 3093 
 3094         /* SA */
 3095         if (mhp->ext[SADB_EXT_SA] != NULL) {
 3096                 const struct sadb_sa *sa0;
 3097 
 3098                 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 3099                 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
 3100                         error = EINVAL;
 3101                         goto fail;
 3102                 }
 3103 
 3104                 sav->alg_auth = sa0->sadb_sa_auth;
 3105                 sav->alg_enc = sa0->sadb_sa_encrypt;
 3106                 sav->flags = sa0->sadb_sa_flags;
 3107 
 3108                 /* replay window */
 3109                 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
 3110                         sav->replay = (struct secreplay *)
 3111                                 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
 3112                         if (sav->replay == NULL) {
 3113                                 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
 3114                                         __func__));
 3115                                 error = ENOBUFS;
 3116                                 goto fail;
 3117                         }
 3118                         if (sa0->sadb_sa_replay != 0)
 3119                                 sav->replay->bitmap = (caddr_t)(sav->replay+1);
 3120                         sav->replay->wsize = sa0->sadb_sa_replay;
 3121                 }
 3122         }
 3123 
 3124         /* Authentication keys */
 3125         if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
 3126                 const struct sadb_key *key0;
 3127                 int len;
 3128 
 3129                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
 3130                 len = mhp->extlen[SADB_EXT_KEY_AUTH];
 3131 
 3132                 error = 0;
 3133                 if (len < sizeof(*key0)) {
 3134                         error = EINVAL;
 3135                         goto fail;
 3136                 }
 3137                 switch (mhp->msg->sadb_msg_satype) {
 3138                 case SADB_SATYPE_AH:
 3139                 case SADB_SATYPE_ESP:
 3140                 case SADB_X_SATYPE_TCPSIGNATURE:
 3141                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
 3142                             sav->alg_auth != SADB_X_AALG_NULL)
 3143                                 error = EINVAL;
 3144                         break;
 3145                 case SADB_X_SATYPE_IPCOMP:
 3146                 default:
 3147                         error = EINVAL;
 3148                         break;
 3149                 }
 3150                 if (error) {
 3151                         ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
 3152                                 __func__));
 3153                         goto fail;
 3154                 }
 3155 
 3156                 sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
 3157                                                                 M_IPSEC_MISC);
 3158                 if (sav->key_auth == NULL ) {
 3159                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",
 3160                                   __func__));
 3161                         error = ENOBUFS;
 3162                         goto fail;
 3163                 }
 3164         }
 3165 
 3166         /* Encryption key */
 3167         if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
 3168                 const struct sadb_key *key0;
 3169                 int len;
 3170 
 3171                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
 3172                 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
 3173 
 3174                 error = 0;
 3175                 if (len < sizeof(*key0)) {
 3176                         error = EINVAL;
 3177                         goto fail;
 3178                 }
 3179                 switch (mhp->msg->sadb_msg_satype) {
 3180                 case SADB_SATYPE_ESP:
 3181                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
 3182                             sav->alg_enc != SADB_EALG_NULL) {
 3183                                 error = EINVAL;
 3184                                 break;
 3185                         }
 3186                         sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
 3187                                                                        len,
 3188                                                                        M_IPSEC_MISC);
 3189                         if (sav->key_enc == NULL) {
 3190                                 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
 3191                                         __func__));
 3192                                 error = ENOBUFS;
 3193                                 goto fail;
 3194                         }
 3195                         break;
 3196                 case SADB_X_SATYPE_IPCOMP:
 3197                         if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
 3198                                 error = EINVAL;
 3199                         sav->key_enc = NULL;    /*just in case*/
 3200                         break;
 3201                 case SADB_SATYPE_AH:
 3202                 case SADB_X_SATYPE_TCPSIGNATURE:
 3203                 default:
 3204                         error = EINVAL;
 3205                         break;
 3206                 }
 3207                 if (error) {
 3208                         ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
 3209                                 __func__));
 3210                         goto fail;
 3211                 }
 3212         }
 3213 
 3214         /* set iv */
 3215         sav->ivlen = 0;
 3216 
 3217         switch (mhp->msg->sadb_msg_satype) {
 3218         case SADB_SATYPE_AH:
 3219                 error = xform_init(sav, XF_AH);
 3220                 break;
 3221         case SADB_SATYPE_ESP:
 3222                 error = xform_init(sav, XF_ESP);
 3223                 break;
 3224         case SADB_X_SATYPE_IPCOMP:
 3225                 error = xform_init(sav, XF_IPCOMP);
 3226                 break;
 3227         case SADB_X_SATYPE_TCPSIGNATURE:
 3228                 error = xform_init(sav, XF_TCPSIGNATURE);
 3229                 break;
 3230         }
 3231         if (error) {
 3232                 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
 3233                         __func__, mhp->msg->sadb_msg_satype));
 3234                 goto fail;
 3235         }
 3236 
 3237         /* reset created */
 3238         sav->created = time_second;
 3239 
 3240         /* make lifetime for CURRENT */
 3241         sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
 3242         if (sav->lft_c == NULL) {
 3243                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 3244                 error = ENOBUFS;
 3245                 goto fail;
 3246         }
 3247 
 3248         sav->lft_c->allocations = 0;
 3249         sav->lft_c->bytes = 0;
 3250         sav->lft_c->addtime = time_second;
 3251         sav->lft_c->usetime = 0;
 3252 
 3253         /* lifetimes for HARD and SOFT */
 3254     {
 3255         const struct sadb_lifetime *lft0;
 3256 
 3257         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
 3258         if (lft0 != NULL) {
 3259                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
 3260                         error = EINVAL;
 3261                         goto fail;
 3262                 }
 3263                 sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
 3264                 if (sav->lft_h == NULL) {
 3265                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
 3266                         error = ENOBUFS;
 3267                         goto fail;
 3268                 }
 3269                 /* to be initialize ? */
 3270         }
 3271 
 3272         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
 3273         if (lft0 != NULL) {
 3274                 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
 3275                         error = EINVAL;
 3276                         goto fail;
 3277                 }
 3278                 sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
 3279                 if (sav->lft_s == NULL) {
 3280                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
 3281                         error = ENOBUFS;
 3282                         goto fail;
 3283                 }
 3284                 /* to be initialize ? */
 3285         }
 3286     }
 3287 
 3288         return 0;
 3289 
 3290  fail:
 3291         /* initialization */
 3292         key_cleansav(sav);
 3293 
 3294         return error;
 3295 }
 3296 
 3297 /*
 3298  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
 3299  * OUT: 0:      valid
 3300  *      other:  errno
 3301  */
 3302 static int
 3303 key_mature(struct secasvar *sav)
 3304 {
 3305         int error;
 3306 
 3307         /* check SPI value */
 3308         switch (sav->sah->saidx.proto) {
 3309         case IPPROTO_ESP:
 3310         case IPPROTO_AH:
 3311                 /*
 3312                  * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
 3313                  * 1-255 reserved by IANA for future use,
 3314                  * 0 for implementation specific, local use.
 3315                  */
 3316                 if (ntohl(sav->spi) <= 255) {
 3317                         ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
 3318                             __func__, (u_int32_t)ntohl(sav->spi)));
 3319                         return EINVAL;
 3320                 }
 3321                 break;
 3322         }
 3323 
 3324         /* check satype */
 3325         switch (sav->sah->saidx.proto) {
 3326         case IPPROTO_ESP:
 3327                 /* check flags */
 3328                 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
 3329                     (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
 3330                         ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
 3331                                 "given to old-esp.\n", __func__));
 3332                         return EINVAL;
 3333                 }
 3334                 error = xform_init(sav, XF_ESP);
 3335                 break;
 3336         case IPPROTO_AH:
 3337                 /* check flags */
 3338                 if (sav->flags & SADB_X_EXT_DERIV) {
 3339                         ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
 3340                                 "given to AH SA.\n", __func__));
 3341                         return EINVAL;
 3342                 }
 3343                 if (sav->alg_enc != SADB_EALG_NONE) {
 3344                         ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
 3345                                 "mismated.\n", __func__));
 3346                         return(EINVAL);
 3347                 }
 3348                 error = xform_init(sav, XF_AH);
 3349                 break;
 3350         case IPPROTO_IPCOMP:
 3351                 if (sav->alg_auth != SADB_AALG_NONE) {
 3352                         ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
 3353                                 "mismated.\n", __func__));
 3354                         return(EINVAL);
 3355                 }
 3356                 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
 3357                  && ntohl(sav->spi) >= 0x10000) {
 3358                         ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
 3359                                 __func__));
 3360                         return(EINVAL);
 3361                 }
 3362                 error = xform_init(sav, XF_IPCOMP);
 3363                 break;
 3364         case IPPROTO_TCP:
 3365                 if (sav->alg_enc != SADB_EALG_NONE) {
 3366                         ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
 3367                                 "mismated.\n", __func__));
 3368                         return(EINVAL);
 3369                 }
 3370                 error = xform_init(sav, XF_TCPSIGNATURE);
 3371                 break;
 3372         default:
 3373                 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
 3374                 error = EPROTONOSUPPORT;
 3375                 break;
 3376         }
 3377         if (error == 0) {
 3378                 SAHTREE_LOCK();
 3379                 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
 3380                 SAHTREE_UNLOCK();
 3381         }
 3382         return (error);
 3383 }
 3384 
 3385 /*
 3386  * subroutine for SADB_GET and SADB_DUMP.
 3387  */
 3388 static struct mbuf *
 3389 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
 3390     u_int32_t seq, u_int32_t pid)
 3391 {
 3392         struct mbuf *result = NULL, *tres = NULL, *m;
 3393         int i;
 3394         int dumporder[] = {
 3395                 SADB_EXT_SA, SADB_X_EXT_SA2,
 3396                 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
 3397                 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
 3398                 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
 3399                 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
 3400                 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
 3401 #ifdef IPSEC_NAT_T
 3402                 SADB_X_EXT_NAT_T_TYPE,
 3403                 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
 3404                 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
 3405                 SADB_X_EXT_NAT_T_FRAG,
 3406 #endif
 3407         };
 3408 
 3409         m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
 3410         if (m == NULL)
 3411                 goto fail;
 3412         result = m;
 3413 
 3414         for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
 3415                 m = NULL;
 3416                 switch (dumporder[i]) {
 3417                 case SADB_EXT_SA:
 3418                         m = key_setsadbsa(sav);
 3419                         if (!m)
 3420                                 goto fail;
 3421                         break;
 3422 
 3423                 case SADB_X_EXT_SA2:
 3424                         m = key_setsadbxsa2(sav->sah->saidx.mode,
 3425                                         sav->replay ? sav->replay->count : 0,
 3426                                         sav->sah->saidx.reqid);
 3427                         if (!m)
 3428                                 goto fail;
 3429                         break;
 3430 
 3431                 case SADB_EXT_ADDRESS_SRC:
 3432                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 3433                             &sav->sah->saidx.src.sa,
 3434                             FULLMASK, IPSEC_ULPROTO_ANY);
 3435                         if (!m)
 3436                                 goto fail;
 3437                         break;
 3438 
 3439                 case SADB_EXT_ADDRESS_DST:
 3440                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 3441                             &sav->sah->saidx.dst.sa,
 3442                             FULLMASK, IPSEC_ULPROTO_ANY);
 3443                         if (!m)
 3444                                 goto fail;
 3445                         break;
 3446 
 3447                 case SADB_EXT_KEY_AUTH:
 3448                         if (!sav->key_auth)
 3449                                 continue;
 3450                         m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
 3451                         if (!m)
 3452                                 goto fail;
 3453                         break;
 3454 
 3455                 case SADB_EXT_KEY_ENCRYPT:
 3456                         if (!sav->key_enc)
 3457                                 continue;
 3458                         m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
 3459                         if (!m)
 3460                                 goto fail;
 3461                         break;
 3462 
 3463                 case SADB_EXT_LIFETIME_CURRENT:
 3464                         if (!sav->lft_c)
 3465                                 continue;
 3466                         m = key_setlifetime(sav->lft_c, 
 3467                                             SADB_EXT_LIFETIME_CURRENT);
 3468                         if (!m)
 3469                                 goto fail;
 3470                         break;
 3471 
 3472                 case SADB_EXT_LIFETIME_HARD:
 3473                         if (!sav->lft_h)
 3474                                 continue;
 3475                         m = key_setlifetime(sav->lft_h, 
 3476                                             SADB_EXT_LIFETIME_HARD);
 3477                         if (!m)
 3478                                 goto fail;
 3479                         break;
 3480 
 3481                 case SADB_EXT_LIFETIME_SOFT:
 3482                         if (!sav->lft_s)
 3483                                 continue;
 3484                         m = key_setlifetime(sav->lft_s, 
 3485                                             SADB_EXT_LIFETIME_SOFT);
 3486 
 3487                         if (!m)
 3488                                 goto fail;
 3489                         break;
 3490 
 3491 #ifdef IPSEC_NAT_T
 3492                 case SADB_X_EXT_NAT_T_TYPE:
 3493                         m = key_setsadbxtype(sav->natt_type);
 3494                         if (!m)
 3495                                 goto fail;
 3496                         break;
 3497                 
 3498                 case SADB_X_EXT_NAT_T_DPORT:
 3499                         m = key_setsadbxport(
 3500                             KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
 3501                             SADB_X_EXT_NAT_T_DPORT);
 3502                         if (!m)
 3503                                 goto fail;
 3504                         break;
 3505 
 3506                 case SADB_X_EXT_NAT_T_SPORT:
 3507                         m = key_setsadbxport(
 3508                             KEY_PORTFROMSADDR(&sav->sah->saidx.src),
 3509                             SADB_X_EXT_NAT_T_SPORT);
 3510                         if (!m)
 3511                                 goto fail;
 3512                         break;
 3513 
 3514                 case SADB_X_EXT_NAT_T_OAI:
 3515                 case SADB_X_EXT_NAT_T_OAR:
 3516                 case SADB_X_EXT_NAT_T_FRAG:
 3517                         /* We do not (yet) support those. */
 3518                         continue;
 3519 #endif
 3520 
 3521                 case SADB_EXT_ADDRESS_PROXY:
 3522                 case SADB_EXT_IDENTITY_SRC:
 3523                 case SADB_EXT_IDENTITY_DST:
 3524                         /* XXX: should we brought from SPD ? */
 3525                 case SADB_EXT_SENSITIVITY:
 3526                 default:
 3527                         continue;
 3528                 }
 3529 
 3530                 if (!m)
 3531                         goto fail;
 3532                 if (tres)
 3533                         m_cat(m, tres);
 3534                 tres = m;
 3535                   
 3536         }
 3537 
 3538         m_cat(result, tres);
 3539         if (result->m_len < sizeof(struct sadb_msg)) {
 3540                 result = m_pullup(result, sizeof(struct sadb_msg));
 3541                 if (result == NULL)
 3542                         goto fail;
 3543         }
 3544 
 3545         result->m_pkthdr.len = 0;
 3546         for (m = result; m; m = m->m_next)
 3547                 result->m_pkthdr.len += m->m_len;
 3548 
 3549         mtod(result, struct sadb_msg *)->sadb_msg_len =
 3550             PFKEY_UNIT64(result->m_pkthdr.len);
 3551 
 3552         return result;
 3553 
 3554 fail:
 3555         m_freem(result);
 3556         m_freem(tres);
 3557         return NULL;
 3558 }
 3559 
 3560 /*
 3561  * set data into sadb_msg.
 3562  */
 3563 static struct mbuf *
 3564 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
 3565     pid_t pid, u_int16_t reserved)
 3566 {
 3567         struct mbuf *m;
 3568         struct sadb_msg *p;
 3569         int len;
 3570 
 3571         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 3572         if (len > MCLBYTES)
 3573                 return NULL;
 3574         MGETHDR(m, M_DONTWAIT, MT_DATA);
 3575         if (m && len > MHLEN) {
 3576                 MCLGET(m, M_DONTWAIT);
 3577                 if ((m->m_flags & M_EXT) == 0) {
 3578                         m_freem(m);
 3579                         m = NULL;
 3580                 }
 3581         }
 3582         if (!m)
 3583                 return NULL;
 3584         m->m_pkthdr.len = m->m_len = len;
 3585         m->m_next = NULL;
 3586 
 3587         p = mtod(m, struct sadb_msg *);
 3588 
 3589         bzero(p, len);
 3590         p->sadb_msg_version = PF_KEY_V2;
 3591         p->sadb_msg_type = type;
 3592         p->sadb_msg_errno = 0;
 3593         p->sadb_msg_satype = satype;
 3594         p->sadb_msg_len = PFKEY_UNIT64(tlen);
 3595         p->sadb_msg_reserved = reserved;
 3596         p->sadb_msg_seq = seq;
 3597         p->sadb_msg_pid = (u_int32_t)pid;
 3598 
 3599         return m;
 3600 }
 3601 
 3602 /*
 3603  * copy secasvar data into sadb_address.
 3604  */
 3605 static struct mbuf *
 3606 key_setsadbsa(sav)
 3607         struct secasvar *sav;
 3608 {
 3609         struct mbuf *m;
 3610         struct sadb_sa *p;
 3611         int len;
 3612 
 3613         len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
 3614         m = key_alloc_mbuf(len);
 3615         if (!m || m->m_next) {  /*XXX*/
 3616                 if (m)
 3617                         m_freem(m);
 3618                 return NULL;
 3619         }
 3620 
 3621         p = mtod(m, struct sadb_sa *);
 3622 
 3623         bzero(p, len);
 3624         p->sadb_sa_len = PFKEY_UNIT64(len);
 3625         p->sadb_sa_exttype = SADB_EXT_SA;
 3626         p->sadb_sa_spi = sav->spi;
 3627         p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
 3628         p->sadb_sa_state = sav->state;
 3629         p->sadb_sa_auth = sav->alg_auth;
 3630         p->sadb_sa_encrypt = sav->alg_enc;
 3631         p->sadb_sa_flags = sav->flags;
 3632 
 3633         return m;
 3634 }
 3635 
 3636 /*
 3637  * set data into sadb_address.
 3638  */
 3639 static struct mbuf *
 3640 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
 3641 {
 3642         struct mbuf *m;
 3643         struct sadb_address *p;
 3644         size_t len;
 3645 
 3646         len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
 3647             PFKEY_ALIGN8(saddr->sa_len);
 3648         m = key_alloc_mbuf(len);
 3649         if (!m || m->m_next) {  /*XXX*/
 3650                 if (m)
 3651                         m_freem(m);
 3652                 return NULL;
 3653         }
 3654 
 3655         p = mtod(m, struct sadb_address *);
 3656 
 3657         bzero(p, len);
 3658         p->sadb_address_len = PFKEY_UNIT64(len);
 3659         p->sadb_address_exttype = exttype;
 3660         p->sadb_address_proto = ul_proto;
 3661         if (prefixlen == FULLMASK) {
 3662                 switch (saddr->sa_family) {
 3663                 case AF_INET:
 3664                         prefixlen = sizeof(struct in_addr) << 3;
 3665                         break;
 3666                 case AF_INET6:
 3667                         prefixlen = sizeof(struct in6_addr) << 3;
 3668                         break;
 3669                 default:
 3670                         ; /*XXX*/
 3671                 }
 3672         }
 3673         p->sadb_address_prefixlen = prefixlen;
 3674         p->sadb_address_reserved = 0;
 3675 
 3676         bcopy(saddr,
 3677             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
 3678             saddr->sa_len);
 3679 
 3680         return m;
 3681 }
 3682 
 3683 /*
 3684  * set data into sadb_x_sa2.
 3685  */
 3686 static struct mbuf *
 3687 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
 3688 {
 3689         struct mbuf *m;
 3690         struct sadb_x_sa2 *p;
 3691         size_t len;
 3692 
 3693         len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
 3694         m = key_alloc_mbuf(len);
 3695         if (!m || m->m_next) {  /*XXX*/
 3696                 if (m)
 3697                         m_freem(m);
 3698                 return NULL;
 3699         }
 3700 
 3701         p = mtod(m, struct sadb_x_sa2 *);
 3702 
 3703         bzero(p, len);
 3704         p->sadb_x_sa2_len = PFKEY_UNIT64(len);
 3705         p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
 3706         p->sadb_x_sa2_mode = mode;
 3707         p->sadb_x_sa2_reserved1 = 0;
 3708         p->sadb_x_sa2_reserved2 = 0;
 3709         p->sadb_x_sa2_sequence = seq;
 3710         p->sadb_x_sa2_reqid = reqid;
 3711 
 3712         return m;
 3713 }
 3714 
 3715 #ifdef IPSEC_NAT_T
 3716 /*
 3717  * Set a type in sadb_x_nat_t_type.
 3718  */
 3719 static struct mbuf *
 3720 key_setsadbxtype(u_int16_t type)
 3721 {
 3722         struct mbuf *m;
 3723         size_t len;
 3724         struct sadb_x_nat_t_type *p;
 3725 
 3726         len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
 3727 
 3728         m = key_alloc_mbuf(len);
 3729         if (!m || m->m_next) {  /*XXX*/
 3730                 if (m)
 3731                         m_freem(m);
 3732                 return (NULL);
 3733         }
 3734 
 3735         p = mtod(m, struct sadb_x_nat_t_type *);
 3736 
 3737         bzero(p, len);
 3738         p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
 3739         p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
 3740         p->sadb_x_nat_t_type_type = type;
 3741 
 3742         return (m);
 3743 }
 3744 /*
 3745  * Set a port in sadb_x_nat_t_port.
 3746  * In contrast to default RFC 2367 behaviour, port is in network byte order.
 3747  */
 3748 static struct mbuf *
 3749 key_setsadbxport(u_int16_t port, u_int16_t type)
 3750 {
 3751         struct mbuf *m;
 3752         size_t len;
 3753         struct sadb_x_nat_t_port *p;
 3754 
 3755         len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
 3756 
 3757         m = key_alloc_mbuf(len);
 3758         if (!m || m->m_next) {  /*XXX*/
 3759                 if (m)
 3760                         m_freem(m);
 3761                 return (NULL);
 3762         }
 3763 
 3764         p = mtod(m, struct sadb_x_nat_t_port *);
 3765 
 3766         bzero(p, len);
 3767         p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
 3768         p->sadb_x_nat_t_port_exttype = type;
 3769         p->sadb_x_nat_t_port_port = port;
 3770 
 3771         return (m);
 3772 }
 3773 
 3774 /* 
 3775  * Get port from sockaddr. Port is in network byte order.
 3776  */
 3777 u_int16_t 
 3778 key_portfromsaddr(struct sockaddr *sa)
 3779 {
 3780 
 3781         switch (sa->sa_family) {
 3782 #ifdef INET
 3783         case AF_INET:
 3784                 return ((struct sockaddr_in *)sa)->sin_port;
 3785 #endif
 3786 #ifdef INET6
 3787         case AF_INET6:
 3788                 return ((struct sockaddr_in6 *)sa)->sin6_port;
 3789 #endif
 3790         }
 3791         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 3792                 printf("DP %s unexpected address family %d\n",
 3793                         __func__, sa->sa_family));
 3794         return (0);
 3795 }
 3796 #endif /* IPSEC_NAT_T */
 3797 
 3798 /*
 3799  * Set port in struct sockaddr. Port is in network byte order.
 3800  */
 3801 static void
 3802 key_porttosaddr(struct sockaddr *sa, u_int16_t port)
 3803 {
 3804 
 3805         switch (sa->sa_family) {
 3806 #ifdef INET
 3807         case AF_INET:
 3808                 ((struct sockaddr_in *)sa)->sin_port = port;
 3809                 break;
 3810 #endif
 3811 #ifdef INET6
 3812         case AF_INET6:
 3813                 ((struct sockaddr_in6 *)sa)->sin6_port = port;
 3814                 break;
 3815 #endif
 3816         default:
 3817                 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
 3818                         __func__, sa->sa_family));
 3819                 break;
 3820         }
 3821 }
 3822 
 3823 /*
 3824  * set data into sadb_x_policy
 3825  */
 3826 static struct mbuf *
 3827 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
 3828 {
 3829         struct mbuf *m;
 3830         struct sadb_x_policy *p;
 3831         size_t len;
 3832 
 3833         len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
 3834         m = key_alloc_mbuf(len);
 3835         if (!m || m->m_next) {  /*XXX*/
 3836                 if (m)
 3837                         m_freem(m);
 3838                 return NULL;
 3839         }
 3840 
 3841         p = mtod(m, struct sadb_x_policy *);
 3842 
 3843         bzero(p, len);
 3844         p->sadb_x_policy_len = PFKEY_UNIT64(len);
 3845         p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
 3846         p->sadb_x_policy_type = type;
 3847         p->sadb_x_policy_dir = dir;
 3848         p->sadb_x_policy_id = id;
 3849 
 3850         return m;
 3851 }
 3852 
 3853 /* %%% utilities */
 3854 /* Take a key message (sadb_key) from the socket and turn it into one
 3855  * of the kernel's key structures (seckey).
 3856  *
 3857  * IN: pointer to the src
 3858  * OUT: NULL no more memory
 3859  */
 3860 struct seckey *
 3861 key_dup_keymsg(const struct sadb_key *src, u_int len,
 3862                struct malloc_type *type)
 3863 {
 3864         struct seckey *dst;
 3865         dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
 3866         if (dst != NULL) {
 3867                 dst->bits = src->sadb_key_bits;
 3868                 dst->key_data = (char *)malloc(len, type, M_NOWAIT);
 3869                 if (dst->key_data != NULL) {
 3870                         bcopy((const char *)src + sizeof(struct sadb_key), 
 3871                               dst->key_data, len);
 3872                 } else {
 3873                         ipseclog((LOG_DEBUG, "%s: No more memory.\n", 
 3874                                   __func__));
 3875                         free(dst, type);
 3876                         dst = NULL;
 3877                 }
 3878         } else {
 3879                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", 
 3880                           __func__));
 3881 
 3882         }
 3883         return dst;
 3884 }
 3885 
 3886 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
 3887  * turn it into one of the kernel's lifetime structures (seclifetime).
 3888  *
 3889  * IN: pointer to the destination, source and malloc type
 3890  * OUT: NULL, no more memory
 3891  */
 3892 
 3893 static struct seclifetime *
 3894 key_dup_lifemsg(const struct sadb_lifetime *src,
 3895                  struct malloc_type *type)
 3896 {
 3897         struct seclifetime *dst = NULL;
 3898 
 3899         dst = (struct seclifetime *)malloc(sizeof(struct seclifetime), 
 3900                                            type, M_NOWAIT);
 3901         if (dst == NULL) {
 3902                 /* XXX counter */
 3903                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 3904         } else {
 3905                 dst->allocations = src->sadb_lifetime_allocations;
 3906                 dst->bytes = src->sadb_lifetime_bytes;
 3907                 dst->addtime = src->sadb_lifetime_addtime;
 3908                 dst->usetime = src->sadb_lifetime_usetime;
 3909         }
 3910         return dst;
 3911 }
 3912 
 3913 /* compare my own address
 3914  * OUT: 1: true, i.e. my address.
 3915  *      0: false
 3916  */
 3917 int
 3918 key_ismyaddr(sa)
 3919         struct sockaddr *sa;
 3920 {
 3921 #ifdef INET
 3922         struct sockaddr_in *sin;
 3923         struct in_ifaddr *ia;
 3924 #endif
 3925 
 3926         IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
 3927 
 3928         switch (sa->sa_family) {
 3929 #ifdef INET
 3930         case AF_INET:
 3931                 sin = (struct sockaddr_in *)sa;
 3932                 IN_IFADDR_RLOCK();
 3933                 for (ia = V_in_ifaddrhead.tqh_first; ia;
 3934                      ia = ia->ia_link.tqe_next)
 3935                 {
 3936                         if (sin->sin_family == ia->ia_addr.sin_family &&
 3937                             sin->sin_len == ia->ia_addr.sin_len &&
 3938                             sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
 3939                         {
 3940                                 IN_IFADDR_RUNLOCK();
 3941                                 return 1;
 3942                         }
 3943                 }
 3944                 IN_IFADDR_RUNLOCK();
 3945                 break;
 3946 #endif
 3947 #ifdef INET6
 3948         case AF_INET6:
 3949                 return key_ismyaddr6((struct sockaddr_in6 *)sa);
 3950 #endif
 3951         }
 3952 
 3953         return 0;
 3954 }
 3955 
 3956 #ifdef INET6
 3957 /*
 3958  * compare my own address for IPv6.
 3959  * 1: ours
 3960  * 0: other
 3961  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
 3962  */
 3963 #include <netinet6/in6_var.h>
 3964 
 3965 static int
 3966 key_ismyaddr6(sin6)
 3967         struct sockaddr_in6 *sin6;
 3968 {
 3969         struct in6_ifaddr *ia;
 3970 #if 0
 3971         struct in6_multi *in6m;
 3972 #endif
 3973 
 3974         IN6_IFADDR_RLOCK();
 3975         TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
 3976                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
 3977                     (struct sockaddr *)&ia->ia_addr, 0) == 0) {
 3978                         IN6_IFADDR_RUNLOCK();
 3979                         return 1;
 3980                 }
 3981 
 3982 #if 0
 3983                 /*
 3984                  * XXX Multicast
 3985                  * XXX why do we care about multlicast here while we don't care
 3986                  * about IPv4 multicast??
 3987                  * XXX scope
 3988                  */
 3989                 in6m = NULL;
 3990                 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
 3991                 if (in6m) {
 3992                         IN6_IFADDR_RUNLOCK();
 3993                         return 1;
 3994                 }
 3995 #endif
 3996         }
 3997         IN6_IFADDR_RUNLOCK();
 3998 
 3999         /* loopback, just for safety */
 4000         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
 4001                 return 1;
 4002 
 4003         return 0;
 4004 }
 4005 #endif /*INET6*/
 4006 
 4007 /*
 4008  * compare two secasindex structure.
 4009  * flag can specify to compare 2 saidxes.
 4010  * compare two secasindex structure without both mode and reqid.
 4011  * don't compare port.
 4012  * IN:  
 4013  *      saidx0: source, it can be in SAD.
 4014  *      saidx1: object.
 4015  * OUT: 
 4016  *      1 : equal
 4017  *      0 : not equal
 4018  */
 4019 static int
 4020 key_cmpsaidx(
 4021         const struct secasindex *saidx0,
 4022         const struct secasindex *saidx1,
 4023         int flag)
 4024 {
 4025         int chkport = 0;
 4026 
 4027         /* sanity */
 4028         if (saidx0 == NULL && saidx1 == NULL)
 4029                 return 1;
 4030 
 4031         if (saidx0 == NULL || saidx1 == NULL)
 4032                 return 0;
 4033 
 4034         if (saidx0->proto != saidx1->proto)
 4035                 return 0;
 4036 
 4037         if (flag == CMP_EXACTLY) {
 4038                 if (saidx0->mode != saidx1->mode)
 4039                         return 0;
 4040                 if (saidx0->reqid != saidx1->reqid)
 4041                         return 0;
 4042                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
 4043                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
 4044                         return 0;
 4045         } else {
 4046 
 4047                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
 4048                 if (flag == CMP_MODE_REQID
 4049                   ||flag == CMP_REQID) {
 4050                         /*
 4051                          * If reqid of SPD is non-zero, unique SA is required.
 4052                          * The result must be of same reqid in this case.
 4053                          */
 4054                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
 4055                                 return 0;
 4056                 }
 4057 
 4058                 if (flag == CMP_MODE_REQID) {
 4059                         if (saidx0->mode != IPSEC_MODE_ANY
 4060                          && saidx0->mode != saidx1->mode)
 4061                                 return 0;
 4062                 }
 4063 
 4064 #ifdef IPSEC_NAT_T
 4065                 /*
 4066                  * If NAT-T is enabled, check ports for tunnel mode.
 4067                  * Do not check ports if they are set to zero in the SPD.
 4068                  * Also do not do it for transport mode, as there is no
 4069                  * port information available in the SP.
 4070                  */
 4071                 if (saidx1->mode == IPSEC_MODE_TUNNEL &&
 4072                     saidx1->src.sa.sa_family == AF_INET &&
 4073                     saidx1->dst.sa.sa_family == AF_INET &&
 4074                     ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
 4075                     ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
 4076                         chkport = 1;
 4077 #endif /* IPSEC_NAT_T */
 4078 
 4079                 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
 4080                         return 0;
 4081                 }
 4082                 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
 4083                         return 0;
 4084                 }
 4085         }
 4086 
 4087         return 1;
 4088 }
 4089 
 4090 /*
 4091  * compare two secindex structure exactly.
 4092  * IN:
 4093  *      spidx0: source, it is often in SPD.
 4094  *      spidx1: object, it is often from PFKEY message.
 4095  * OUT:
 4096  *      1 : equal
 4097  *      0 : not equal
 4098  */
 4099 static int
 4100 key_cmpspidx_exactly(
 4101         struct secpolicyindex *spidx0,
 4102         struct secpolicyindex *spidx1)
 4103 {
 4104         /* sanity */
 4105         if (spidx0 == NULL && spidx1 == NULL)
 4106                 return 1;
 4107 
 4108         if (spidx0 == NULL || spidx1 == NULL)
 4109                 return 0;
 4110 
 4111         if (spidx0->prefs != spidx1->prefs
 4112          || spidx0->prefd != spidx1->prefd
 4113          || spidx0->ul_proto != spidx1->ul_proto)
 4114                 return 0;
 4115 
 4116         return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
 4117                key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
 4118 }
 4119 
 4120 /*
 4121  * compare two secindex structure with mask.
 4122  * IN:
 4123  *      spidx0: source, it is often in SPD.
 4124  *      spidx1: object, it is often from IP header.
 4125  * OUT:
 4126  *      1 : equal
 4127  *      0 : not equal
 4128  */
 4129 static int
 4130 key_cmpspidx_withmask(
 4131         struct secpolicyindex *spidx0,
 4132         struct secpolicyindex *spidx1)
 4133 {
 4134         /* sanity */
 4135         if (spidx0 == NULL && spidx1 == NULL)
 4136                 return 1;
 4137 
 4138         if (spidx0 == NULL || spidx1 == NULL)
 4139                 return 0;
 4140 
 4141         if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
 4142             spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
 4143             spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
 4144             spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
 4145                 return 0;
 4146 
 4147         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
 4148         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
 4149          && spidx0->ul_proto != spidx1->ul_proto)
 4150                 return 0;
 4151 
 4152         switch (spidx0->src.sa.sa_family) {
 4153         case AF_INET:
 4154                 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
 4155                  && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
 4156                         return 0;
 4157                 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
 4158                     &spidx1->src.sin.sin_addr, spidx0->prefs))
 4159                         return 0;
 4160                 break;
 4161         case AF_INET6:
 4162                 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
 4163                  && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
 4164                         return 0;
 4165                 /*
 4166                  * scope_id check. if sin6_scope_id is 0, we regard it
 4167                  * as a wildcard scope, which matches any scope zone ID. 
 4168                  */
 4169                 if (spidx0->src.sin6.sin6_scope_id &&
 4170                     spidx1->src.sin6.sin6_scope_id &&
 4171                     spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
 4172                         return 0;
 4173                 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
 4174                     &spidx1->src.sin6.sin6_addr, spidx0->prefs))
 4175                         return 0;
 4176                 break;
 4177         default:
 4178                 /* XXX */
 4179                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
 4180                         return 0;
 4181                 break;
 4182         }
 4183 
 4184         switch (spidx0->dst.sa.sa_family) {
 4185         case AF_INET:
 4186                 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
 4187                  && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
 4188                         return 0;
 4189                 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
 4190                     &spidx1->dst.sin.sin_addr, spidx0->prefd))
 4191                         return 0;
 4192                 break;
 4193         case AF_INET6:
 4194                 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
 4195                  && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
 4196                         return 0;
 4197                 /*
 4198                  * scope_id check. if sin6_scope_id is 0, we regard it
 4199                  * as a wildcard scope, which matches any scope zone ID. 
 4200                  */
 4201                 if (spidx0->dst.sin6.sin6_scope_id &&
 4202                     spidx1->dst.sin6.sin6_scope_id &&
 4203                     spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
 4204                         return 0;
 4205                 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
 4206                     &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
 4207                         return 0;
 4208                 break;
 4209         default:
 4210                 /* XXX */
 4211                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
 4212                         return 0;
 4213                 break;
 4214         }
 4215 
 4216         /* XXX Do we check other field ?  e.g. flowinfo */
 4217 
 4218         return 1;
 4219 }
 4220 
 4221 /* returns 0 on match */
 4222 static int
 4223 key_sockaddrcmp(
 4224         const struct sockaddr *sa1,
 4225         const struct sockaddr *sa2,
 4226         int port)
 4227 {
 4228 #ifdef satosin
 4229 #undef satosin
 4230 #endif
 4231 #define satosin(s) ((const struct sockaddr_in *)s)
 4232 #ifdef satosin6
 4233 #undef satosin6
 4234 #endif
 4235 #define satosin6(s) ((const struct sockaddr_in6 *)s)
 4236         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
 4237                 return 1;
 4238 
 4239         switch (sa1->sa_family) {
 4240         case AF_INET:
 4241                 if (sa1->sa_len != sizeof(struct sockaddr_in))
 4242                         return 1;
 4243                 if (satosin(sa1)->sin_addr.s_addr !=
 4244                     satosin(sa2)->sin_addr.s_addr) {
 4245                         return 1;
 4246                 }
 4247                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
 4248                         return 1;
 4249                 break;
 4250         case AF_INET6:
 4251                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
 4252                         return 1;       /*EINVAL*/
 4253                 if (satosin6(sa1)->sin6_scope_id !=
 4254                     satosin6(sa2)->sin6_scope_id) {
 4255                         return 1;
 4256                 }
 4257                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
 4258                     &satosin6(sa2)->sin6_addr)) {
 4259                         return 1;
 4260                 }
 4261                 if (port &&
 4262                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
 4263                         return 1;
 4264                 }
 4265                 break;
 4266         default:
 4267                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
 4268                         return 1;
 4269                 break;
 4270         }
 4271 
 4272         return 0;
 4273 #undef satosin
 4274 #undef satosin6
 4275 }
 4276 
 4277 /*
 4278  * compare two buffers with mask.
 4279  * IN:
 4280  *      addr1: source
 4281  *      addr2: object
 4282  *      bits:  Number of bits to compare
 4283  * OUT:
 4284  *      1 : equal
 4285  *      0 : not equal
 4286  */
 4287 static int
 4288 key_bbcmp(const void *a1, const void *a2, u_int bits)
 4289 {
 4290         const unsigned char *p1 = a1;
 4291         const unsigned char *p2 = a2;
 4292 
 4293         /* XXX: This could be considerably faster if we compare a word
 4294          * at a time, but it is complicated on LSB Endian machines */
 4295 
 4296         /* Handle null pointers */
 4297         if (p1 == NULL || p2 == NULL)
 4298                 return (p1 == p2);
 4299 
 4300         while (bits >= 8) {
 4301                 if (*p1++ != *p2++)
 4302                         return 0;
 4303                 bits -= 8;
 4304         }
 4305 
 4306         if (bits > 0) {
 4307                 u_int8_t mask = ~((1<<(8-bits))-1);
 4308                 if ((*p1 & mask) != (*p2 & mask))
 4309                         return 0;
 4310         }
 4311         return 1;       /* Match! */
 4312 }
 4313 
 4314 static void
 4315 key_flush_spd(time_t now)
 4316 {
 4317         static u_int16_t sptree_scangen = 0;
 4318         u_int16_t gen = sptree_scangen++;
 4319         struct secpolicy *sp;
 4320         u_int dir;
 4321 
 4322         /* SPD */
 4323         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 4324 restart:
 4325                 SPTREE_LOCK();
 4326                 LIST_FOREACH(sp, &V_sptree[dir], chain) {
 4327                         if (sp->scangen == gen)         /* previously handled */
 4328                                 continue;
 4329                         sp->scangen = gen;
 4330                         if (sp->state == IPSEC_SPSTATE_DEAD &&
 4331                             sp->refcnt == 1) {
 4332                                 /*
 4333                                  * Ensure that we only decrease refcnt once,
 4334                                  * when we're the last consumer.
 4335                                  * Directly call SP_DELREF/key_delsp instead
 4336                                  * of KEY_FREESP to avoid unlocking/relocking
 4337                                  * SPTREE_LOCK before key_delsp: may refcnt
 4338                                  * be increased again during that time ?
 4339                                  * NB: also clean entries created by
 4340                                  * key_spdflush
 4341                                  */
 4342                                 SP_DELREF(sp);
 4343                                 key_delsp(sp);
 4344                                 SPTREE_UNLOCK();
 4345                                 goto restart;
 4346                         }
 4347                         if (sp->lifetime == 0 && sp->validtime == 0)
 4348                                 continue;
 4349                         if ((sp->lifetime && now - sp->created > sp->lifetime)
 4350                          || (sp->validtime && now - sp->lastused > sp->validtime)) {
 4351                                 sp->state = IPSEC_SPSTATE_DEAD;
 4352                                 SPTREE_UNLOCK();
 4353                                 key_spdexpire(sp);
 4354                                 goto restart;
 4355                         }
 4356                 }
 4357                 SPTREE_UNLOCK();
 4358         }
 4359 }
 4360 
 4361 static void
 4362 key_flush_sad(time_t now)
 4363 {
 4364         struct secashead *sah, *nextsah;
 4365         struct secasvar *sav, *nextsav;
 4366 
 4367         /* SAD */
 4368         SAHTREE_LOCK();
 4369         LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
 4370                 /* if sah has been dead, then delete it and process next sah. */
 4371                 if (sah->state == SADB_SASTATE_DEAD) {
 4372                         key_delsah(sah);
 4373                         continue;
 4374                 }
 4375 
 4376                 /* if LARVAL entry doesn't become MATURE, delete it. */
 4377                 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
 4378                         /* Need to also check refcnt for a larval SA ??? */
 4379                         if (now - sav->created > V_key_larval_lifetime)
 4380                                 KEY_FREESAV(&sav);
 4381                 }
 4382 
 4383                 /*
 4384                  * check MATURE entry to start to send expire message
 4385                  * whether or not.
 4386                  */
 4387                 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
 4388                         /* we don't need to check. */
 4389                         if (sav->lft_s == NULL)
 4390                                 continue;
 4391 
 4392                         /* sanity check */
 4393                         if (sav->lft_c == NULL) {
 4394                                 ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
 4395                                         "time, why?\n", __func__));
 4396                                 continue;
 4397                         }
 4398 
 4399                         /* check SOFT lifetime */
 4400                         if (sav->lft_s->addtime != 0 &&
 4401                             now - sav->created > sav->lft_s->addtime) {
 4402                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
 4403                                 /* 
 4404                                  * Actually, only send expire message if
 4405                                  * SA has been used, as it was done before,
 4406                                  * but should we always send such message,
 4407                                  * and let IKE daemon decide if it should be
 4408                                  * renegotiated or not ?
 4409                                  * XXX expire message will actually NOT be
 4410                                  * sent if SA is only used after soft
 4411                                  * lifetime has been reached, see below
 4412                                  * (DYING state)
 4413                                  */
 4414                                 if (sav->lft_c->usetime != 0)
 4415                                         key_expire(sav);
 4416                         }
 4417                         /* check SOFT lifetime by bytes */
 4418                         /*
 4419                          * XXX I don't know the way to delete this SA
 4420                          * when new SA is installed.  Caution when it's
 4421                          * installed too big lifetime by time.
 4422                          */
 4423                         else if (sav->lft_s->bytes != 0 &&
 4424                             sav->lft_s->bytes < sav->lft_c->bytes) {
 4425 
 4426                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
 4427                                 /*
 4428                                  * XXX If we keep to send expire
 4429                                  * message in the status of
 4430                                  * DYING. Do remove below code.
 4431                                  */
 4432                                 key_expire(sav);
 4433                         }
 4434                 }
 4435 
 4436                 /* check DYING entry to change status to DEAD. */
 4437                 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
 4438                         /* we don't need to check. */
 4439                         if (sav->lft_h == NULL)
 4440                                 continue;
 4441 
 4442                         /* sanity check */
 4443                         if (sav->lft_c == NULL) {
 4444                                 ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
 4445                                         "time, why?\n", __func__));
 4446                                 continue;
 4447                         }
 4448 
 4449                         if (sav->lft_h->addtime != 0 &&
 4450                             now - sav->created > sav->lft_h->addtime) {
 4451                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 4452                                 KEY_FREESAV(&sav);
 4453                         }
 4454 #if 0   /* XXX Should we keep to send expire message until HARD lifetime ? */
 4455                         else if (sav->lft_s != NULL
 4456                               && sav->lft_s->addtime != 0
 4457                               && now - sav->created > sav->lft_s->addtime) {
 4458                                 /*
 4459                                  * XXX: should be checked to be
 4460                                  * installed the valid SA.
 4461                                  */
 4462 
 4463                                 /*
 4464                                  * If there is no SA then sending
 4465                                  * expire message.
 4466                                  */
 4467                                 key_expire(sav);
 4468                         }
 4469 #endif
 4470                         /* check HARD lifetime by bytes */
 4471                         else if (sav->lft_h->bytes != 0 &&
 4472                             sav->lft_h->bytes < sav->lft_c->bytes) {
 4473                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 4474                                 KEY_FREESAV(&sav);
 4475                         }
 4476                 }
 4477 
 4478                 /* delete entry in DEAD */
 4479                 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
 4480                         /* sanity check */
 4481                         if (sav->state != SADB_SASTATE_DEAD) {
 4482                                 ipseclog((LOG_DEBUG, "%s: invalid sav->state "
 4483                                         "(queue: %d SA: %d): kill it anyway\n",
 4484                                         __func__,
 4485                                         SADB_SASTATE_DEAD, sav->state));
 4486                         }
 4487                         /*
 4488                          * do not call key_freesav() here.
 4489                          * sav should already be freed, and sav->refcnt
 4490                          * shows other references to sav
 4491                          * (such as from SPD).
 4492                          */
 4493                 }
 4494         }
 4495         SAHTREE_UNLOCK();
 4496 }
 4497 
 4498 static void
 4499 key_flush_acq(time_t now)
 4500 {
 4501         struct secacq *acq, *nextacq;
 4502 
 4503         /* ACQ tree */
 4504         ACQ_LOCK();
 4505         for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
 4506                 nextacq = LIST_NEXT(acq, chain);
 4507                 if (now - acq->created > V_key_blockacq_lifetime
 4508                  && __LIST_CHAINED(acq)) {
 4509                         LIST_REMOVE(acq, chain);
 4510                         free(acq, M_IPSEC_SAQ);
 4511                 }
 4512         }
 4513         ACQ_UNLOCK();
 4514 }
 4515 
 4516 static void
 4517 key_flush_spacq(time_t now)
 4518 {
 4519         struct secspacq *acq, *nextacq;
 4520 
 4521         /* SP ACQ tree */
 4522         SPACQ_LOCK();
 4523         for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
 4524                 nextacq = LIST_NEXT(acq, chain);
 4525                 if (now - acq->created > V_key_blockacq_lifetime
 4526                  && __LIST_CHAINED(acq)) {
 4527                         LIST_REMOVE(acq, chain);
 4528                         free(acq, M_IPSEC_SAQ);
 4529                 }
 4530         }
 4531         SPACQ_UNLOCK();
 4532 }
 4533 
 4534 /*
 4535  * time handler.
 4536  * scanning SPD and SAD to check status for each entries,
 4537  * and do to remove or to expire.
 4538  * XXX: year 2038 problem may remain.
 4539  */
 4540 void
 4541 key_timehandler(void)
 4542 {
 4543         VNET_ITERATOR_DECL(vnet_iter);
 4544         time_t now = time_second;
 4545 
 4546         VNET_LIST_RLOCK_NOSLEEP();
 4547         VNET_FOREACH(vnet_iter) {
 4548                 CURVNET_SET(vnet_iter);
 4549                 key_flush_spd(now);
 4550                 key_flush_sad(now);
 4551                 key_flush_acq(now);
 4552                 key_flush_spacq(now);
 4553                 CURVNET_RESTORE();
 4554         }
 4555         VNET_LIST_RUNLOCK_NOSLEEP();
 4556 
 4557 #ifndef IPSEC_DEBUG2
 4558         /* do exchange to tick time !! */
 4559         (void)timeout((void *)key_timehandler, (void *)0, hz);
 4560 #endif /* IPSEC_DEBUG2 */
 4561 }
 4562 
 4563 u_long
 4564 key_random()
 4565 {
 4566         u_long value;
 4567 
 4568         key_randomfill(&value, sizeof(value));
 4569         return value;
 4570 }
 4571 
 4572 void
 4573 key_randomfill(p, l)
 4574         void *p;
 4575         size_t l;
 4576 {
 4577         size_t n;
 4578         u_long v;
 4579         static int warn = 1;
 4580 
 4581         n = 0;
 4582         n = (size_t)read_random(p, (u_int)l);
 4583         /* last resort */
 4584         while (n < l) {
 4585                 v = random();
 4586                 bcopy(&v, (u_int8_t *)p + n,
 4587                     l - n < sizeof(v) ? l - n : sizeof(v));
 4588                 n += sizeof(v);
 4589 
 4590                 if (warn) {
 4591                         printf("WARNING: pseudo-random number generator "
 4592                             "used for IPsec processing\n");
 4593                         warn = 0;
 4594                 }
 4595         }
 4596 }
 4597 
 4598 /*
 4599  * map SADB_SATYPE_* to IPPROTO_*.
 4600  * if satype == SADB_SATYPE then satype is mapped to ~0.
 4601  * OUT:
 4602  *      0: invalid satype.
 4603  */
 4604 static u_int16_t
 4605 key_satype2proto(u_int8_t satype)
 4606 {
 4607         switch (satype) {
 4608         case SADB_SATYPE_UNSPEC:
 4609                 return IPSEC_PROTO_ANY;
 4610         case SADB_SATYPE_AH:
 4611                 return IPPROTO_AH;
 4612         case SADB_SATYPE_ESP:
 4613                 return IPPROTO_ESP;
 4614         case SADB_X_SATYPE_IPCOMP:
 4615                 return IPPROTO_IPCOMP;
 4616         case SADB_X_SATYPE_TCPSIGNATURE:
 4617                 return IPPROTO_TCP;
 4618         default:
 4619                 return 0;
 4620         }
 4621         /* NOTREACHED */
 4622 }
 4623 
 4624 /*
 4625  * map IPPROTO_* to SADB_SATYPE_*
 4626  * OUT:
 4627  *      0: invalid protocol type.
 4628  */
 4629 static u_int8_t
 4630 key_proto2satype(u_int16_t proto)
 4631 {
 4632         switch (proto) {
 4633         case IPPROTO_AH:
 4634                 return SADB_SATYPE_AH;
 4635         case IPPROTO_ESP:
 4636                 return SADB_SATYPE_ESP;
 4637         case IPPROTO_IPCOMP:
 4638                 return SADB_X_SATYPE_IPCOMP;
 4639         case IPPROTO_TCP:
 4640                 return SADB_X_SATYPE_TCPSIGNATURE;
 4641         default:
 4642                 return 0;
 4643         }
 4644         /* NOTREACHED */
 4645 }
 4646 
 4647 /* %%% PF_KEY */
 4648 /*
 4649  * SADB_GETSPI processing is to receive
 4650  *      <base, (SA2), src address, dst address, (SPI range)>
 4651  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
 4652  * tree with the status of LARVAL, and send
 4653  *      <base, SA(*), address(SD)>
 4654  * to the IKMPd.
 4655  *
 4656  * IN:  mhp: pointer to the pointer to each header.
 4657  * OUT: NULL if fail.
 4658  *      other if success, return pointer to the message to send.
 4659  */
 4660 static int
 4661 key_getspi(so, m, mhp)
 4662         struct socket *so;
 4663         struct mbuf *m;
 4664         const struct sadb_msghdr *mhp;
 4665 {
 4666         struct sadb_address *src0, *dst0;
 4667         struct secasindex saidx;
 4668         struct secashead *newsah;
 4669         struct secasvar *newsav;
 4670         u_int8_t proto;
 4671         u_int32_t spi;
 4672         u_int8_t mode;
 4673         u_int32_t reqid;
 4674         int error;
 4675 
 4676         IPSEC_ASSERT(so != NULL, ("null socket"));
 4677         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 4678         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 4679         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 4680 
 4681         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 4682             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 4683                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 4684                         __func__));
 4685                 return key_senderror(so, m, EINVAL);
 4686         }
 4687         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 4688             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 4689                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 4690                         __func__));
 4691                 return key_senderror(so, m, EINVAL);
 4692         }
 4693         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 4694                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 4695                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 4696         } else {
 4697                 mode = IPSEC_MODE_ANY;
 4698                 reqid = 0;
 4699         }
 4700 
 4701         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 4702         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 4703 
 4704         /* map satype to proto */
 4705         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 4706                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
 4707                         __func__));
 4708                 return key_senderror(so, m, EINVAL);
 4709         }
 4710 
 4711         /*
 4712          * Make sure the port numbers are zero.
 4713          * In case of NAT-T we will update them later if needed.
 4714          */
 4715         switch (((struct sockaddr *)(src0 + 1))->sa_family) {
 4716         case AF_INET:
 4717                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
 4718                     sizeof(struct sockaddr_in))
 4719                         return key_senderror(so, m, EINVAL);
 4720                 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
 4721                 break;
 4722         case AF_INET6:
 4723                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
 4724                     sizeof(struct sockaddr_in6))
 4725                         return key_senderror(so, m, EINVAL);
 4726                 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
 4727                 break;
 4728         default:
 4729                 ; /*???*/
 4730         }
 4731         switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
 4732         case AF_INET:
 4733                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
 4734                     sizeof(struct sockaddr_in))
 4735                         return key_senderror(so, m, EINVAL);
 4736                 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
 4737                 break;
 4738         case AF_INET6:
 4739                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
 4740                     sizeof(struct sockaddr_in6))
 4741                         return key_senderror(so, m, EINVAL);
 4742                 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
 4743                 break;
 4744         default:
 4745                 ; /*???*/
 4746         }
 4747 
 4748         /* XXX boundary check against sa_len */
 4749         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 4750 
 4751 #ifdef IPSEC_NAT_T
 4752         /*
 4753          * Handle NAT-T info if present.
 4754          * We made sure the port numbers are zero above, so we do
 4755          * not have to worry in case we do not update them.
 4756          */
 4757         if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
 4758                 ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
 4759         if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
 4760                 ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
 4761 
 4762         if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
 4763             mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
 4764             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
 4765                 struct sadb_x_nat_t_type *type;
 4766                 struct sadb_x_nat_t_port *sport, *dport;
 4767 
 4768                 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
 4769                     mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
 4770                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
 4771                         ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
 4772                             "passed.\n", __func__));
 4773                         return key_senderror(so, m, EINVAL);
 4774                 }
 4775 
 4776                 sport = (struct sadb_x_nat_t_port *)
 4777                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
 4778                 dport = (struct sadb_x_nat_t_port *)
 4779                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
 4780 
 4781                 if (sport)
 4782                         KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
 4783                 if (dport)
 4784                         KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
 4785         }
 4786 #endif
 4787 
 4788         /* SPI allocation */
 4789         spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
 4790                                &saidx);
 4791         if (spi == 0)
 4792                 return key_senderror(so, m, EINVAL);
 4793 
 4794         /* get a SA index */
 4795         if ((newsah = key_getsah(&saidx)) == NULL) {
 4796                 /* create a new SA index */
 4797                 if ((newsah = key_newsah(&saidx)) == NULL) {
 4798                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
 4799                         return key_senderror(so, m, ENOBUFS);
 4800                 }
 4801         }
 4802 
 4803         /* get a new SA */
 4804         /* XXX rewrite */
 4805         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
 4806         if (newsav == NULL) {
 4807                 /* XXX don't free new SA index allocated in above. */
 4808                 return key_senderror(so, m, error);
 4809         }
 4810 
 4811         /* set spi */
 4812         newsav->spi = htonl(spi);
 4813 
 4814         /* delete the entry in acqtree */
 4815         if (mhp->msg->sadb_msg_seq != 0) {
 4816                 struct secacq *acq;
 4817                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
 4818                         /* reset counter in order to deletion by timehandler. */
 4819                         acq->created = time_second;
 4820                         acq->count = 0;
 4821                 }
 4822         }
 4823 
 4824     {
 4825         struct mbuf *n, *nn;
 4826         struct sadb_sa *m_sa;
 4827         struct sadb_msg *newmsg;
 4828         int off, len;
 4829 
 4830         /* create new sadb_msg to reply. */
 4831         len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
 4832             PFKEY_ALIGN8(sizeof(struct sadb_sa));
 4833 
 4834         MGETHDR(n, M_DONTWAIT, MT_DATA);
 4835         if (len > MHLEN) {
 4836                 MCLGET(n, M_DONTWAIT);
 4837                 if ((n->m_flags & M_EXT) == 0) {
 4838                         m_freem(n);
 4839                         n = NULL;
 4840                 }
 4841         }
 4842         if (!n)
 4843                 return key_senderror(so, m, ENOBUFS);
 4844 
 4845         n->m_len = len;
 4846         n->m_next = NULL;
 4847         off = 0;
 4848 
 4849         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
 4850         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 4851 
 4852         m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
 4853         m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
 4854         m_sa->sadb_sa_exttype = SADB_EXT_SA;
 4855         m_sa->sadb_sa_spi = htonl(spi);
 4856         off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
 4857 
 4858         IPSEC_ASSERT(off == len,
 4859                 ("length inconsistency (off %u len %u)", off, len));
 4860 
 4861         n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
 4862             SADB_EXT_ADDRESS_DST);
 4863         if (!n->m_next) {
 4864                 m_freem(n);
 4865                 return key_senderror(so, m, ENOBUFS);
 4866         }
 4867 
 4868         if (n->m_len < sizeof(struct sadb_msg)) {
 4869                 n = m_pullup(n, sizeof(struct sadb_msg));
 4870                 if (n == NULL)
 4871                         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
 4872         }
 4873 
 4874         n->m_pkthdr.len = 0;
 4875         for (nn = n; nn; nn = nn->m_next)
 4876                 n->m_pkthdr.len += nn->m_len;
 4877 
 4878         newmsg = mtod(n, struct sadb_msg *);
 4879         newmsg->sadb_msg_seq = newsav->seq;
 4880         newmsg->sadb_msg_errno = 0;
 4881         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 4882 
 4883         m_freem(m);
 4884         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 4885     }
 4886 }
 4887 
 4888 /*
 4889  * allocating new SPI
 4890  * called by key_getspi().
 4891  * OUT:
 4892  *      0:      failure.
 4893  *      others: success.
 4894  */
 4895 static u_int32_t
 4896 key_do_getnewspi(spirange, saidx)
 4897         struct sadb_spirange *spirange;
 4898         struct secasindex *saidx;
 4899 {
 4900         u_int32_t newspi;
 4901         u_int32_t min, max;
 4902         int count = V_key_spi_trycnt;
 4903 
 4904         /* set spi range to allocate */
 4905         if (spirange != NULL) {
 4906                 min = spirange->sadb_spirange_min;
 4907                 max = spirange->sadb_spirange_max;
 4908         } else {
 4909                 min = V_key_spi_minval;
 4910                 max = V_key_spi_maxval;
 4911         }
 4912         /* IPCOMP needs 2-byte SPI */
 4913         if (saidx->proto == IPPROTO_IPCOMP) {
 4914                 u_int32_t t;
 4915                 if (min >= 0x10000)
 4916                         min = 0xffff;
 4917                 if (max >= 0x10000)
 4918                         max = 0xffff;
 4919                 if (min > max) {
 4920                         t = min; min = max; max = t;
 4921                 }
 4922         }
 4923 
 4924         if (min == max) {
 4925                 if (key_checkspidup(saidx, min) != NULL) {
 4926                         ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
 4927                                 __func__, min));
 4928                         return 0;
 4929                 }
 4930 
 4931                 count--; /* taking one cost. */
 4932                 newspi = min;
 4933 
 4934         } else {
 4935 
 4936                 /* init SPI */
 4937                 newspi = 0;
 4938 
 4939                 /* when requesting to allocate spi ranged */
 4940                 while (count--) {
 4941                         /* generate pseudo-random SPI value ranged. */
 4942                         newspi = min + (key_random() % (max - min + 1));
 4943 
 4944                         if (key_checkspidup(saidx, newspi) == NULL)
 4945                                 break;
 4946                 }
 4947 
 4948                 if (count == 0 || newspi == 0) {
 4949                         ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
 4950                                 __func__));
 4951                         return 0;
 4952                 }
 4953         }
 4954 
 4955         /* statistics */
 4956         keystat.getspi_count =
 4957                 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
 4958 
 4959         return newspi;
 4960 }
 4961 
 4962 /*
 4963  * SADB_UPDATE processing
 4964  * receive
 4965  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 4966  *       key(AE), (identity(SD),) (sensitivity)>
 4967  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
 4968  * and send
 4969  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 4970  *       (identity(SD),) (sensitivity)>
 4971  * to the ikmpd.
 4972  *
 4973  * m will always be freed.
 4974  */
 4975 static int
 4976 key_update(so, m, mhp)
 4977         struct socket *so;
 4978         struct mbuf *m;
 4979         const struct sadb_msghdr *mhp;
 4980 {
 4981         struct sadb_sa *sa0;
 4982         struct sadb_address *src0, *dst0;
 4983 #ifdef IPSEC_NAT_T
 4984         struct sadb_x_nat_t_type *type;
 4985         struct sadb_x_nat_t_port *sport, *dport;
 4986         struct sadb_address *iaddr, *raddr;
 4987         struct sadb_x_nat_t_frag *frag;
 4988 #endif
 4989         struct secasindex saidx;
 4990         struct secashead *sah;
 4991         struct secasvar *sav;
 4992         u_int16_t proto;
 4993         u_int8_t mode;
 4994         u_int32_t reqid;
 4995         int error;
 4996 
 4997         IPSEC_ASSERT(so != NULL, ("null socket"));
 4998         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 4999         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 5000         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 5001 
 5002         /* map satype to proto */
 5003         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5004                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
 5005                         __func__));
 5006                 return key_senderror(so, m, EINVAL);
 5007         }
 5008 
 5009         if (mhp->ext[SADB_EXT_SA] == NULL ||
 5010             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5011             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 5012             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
 5013              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
 5014             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
 5015              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
 5016             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
 5017              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
 5018             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
 5019              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
 5020                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5021                         __func__));
 5022                 return key_senderror(so, m, EINVAL);
 5023         }
 5024         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 5025             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5026             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5027                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5028                         __func__));
 5029                 return key_senderror(so, m, EINVAL);
 5030         }
 5031         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 5032                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 5033                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 5034         } else {
 5035                 mode = IPSEC_MODE_ANY;
 5036                 reqid = 0;
 5037         }
 5038         /* XXX boundary checking for other extensions */
 5039 
 5040         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5041         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 5042         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 5043 
 5044         /* XXX boundary check against sa_len */
 5045         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 5046 
 5047         /*
 5048          * Make sure the port numbers are zero.
 5049          * In case of NAT-T we will update them later if needed.
 5050          */
 5051         KEY_PORTTOSADDR(&saidx.src, 0);
 5052         KEY_PORTTOSADDR(&saidx.dst, 0);
 5053 
 5054 #ifdef IPSEC_NAT_T
 5055         /*
 5056          * Handle NAT-T info if present.
 5057          */
 5058         if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
 5059             mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
 5060             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
 5061 
 5062                 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
 5063                     mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
 5064                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
 5065                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
 5066                             __func__));
 5067                         return key_senderror(so, m, EINVAL);
 5068                 }
 5069 
 5070                 type = (struct sadb_x_nat_t_type *)
 5071                     mhp->ext[SADB_X_EXT_NAT_T_TYPE];
 5072                 sport = (struct sadb_x_nat_t_port *)
 5073                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
 5074                 dport = (struct sadb_x_nat_t_port *)
 5075                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
 5076         } else {
 5077                 type = 0;
 5078                 sport = dport = 0;
 5079         }
 5080         if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
 5081             mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
 5082                 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
 5083                     mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
 5084                         ipseclog((LOG_DEBUG, "%s: invalid message\n",
 5085                             __func__));
 5086                         return key_senderror(so, m, EINVAL);
 5087                 }
 5088                 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
 5089                 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
 5090                 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
 5091         } else {
 5092                 iaddr = raddr = NULL;
 5093         }
 5094         if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
 5095                 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
 5096                         ipseclog((LOG_DEBUG, "%s: invalid message\n",
 5097                             __func__));
 5098                         return key_senderror(so, m, EINVAL);
 5099                 }
 5100                 frag = (struct sadb_x_nat_t_frag *)
 5101                     mhp->ext[SADB_X_EXT_NAT_T_FRAG];
 5102         } else {
 5103                 frag = 0;
 5104         }
 5105 #endif
 5106 
 5107         /* get a SA header */
 5108         if ((sah = key_getsah(&saidx)) == NULL) {
 5109                 ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
 5110                 return key_senderror(so, m, ENOENT);
 5111         }
 5112 
 5113         /* set spidx if there */
 5114         /* XXX rewrite */
 5115         error = key_setident(sah, m, mhp);
 5116         if (error)
 5117                 return key_senderror(so, m, error);
 5118 
 5119         /* find a SA with sequence number. */
 5120 #ifdef IPSEC_DOSEQCHECK
 5121         if (mhp->msg->sadb_msg_seq != 0
 5122          && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
 5123                 ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
 5124                         "exists.\n", __func__, mhp->msg->sadb_msg_seq));
 5125                 return key_senderror(so, m, ENOENT);
 5126         }
 5127 #else
 5128         SAHTREE_LOCK();
 5129         sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
 5130         SAHTREE_UNLOCK();
 5131         if (sav == NULL) {
 5132                 ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
 5133                         __func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
 5134                 return key_senderror(so, m, EINVAL);
 5135         }
 5136 #endif
 5137 
 5138         /* validity check */
 5139         if (sav->sah->saidx.proto != proto) {
 5140                 ipseclog((LOG_DEBUG, "%s: protocol mismatched "
 5141                         "(DB=%u param=%u)\n", __func__,
 5142                         sav->sah->saidx.proto, proto));
 5143                 return key_senderror(so, m, EINVAL);
 5144         }
 5145 #ifdef IPSEC_DOSEQCHECK
 5146         if (sav->spi != sa0->sadb_sa_spi) {
 5147                 ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
 5148                     __func__,
 5149                     (u_int32_t)ntohl(sav->spi),
 5150                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
 5151                 return key_senderror(so, m, EINVAL);
 5152         }
 5153 #endif
 5154         if (sav->pid != mhp->msg->sadb_msg_pid) {
 5155                 ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
 5156                     __func__, sav->pid, mhp->msg->sadb_msg_pid));
 5157                 return key_senderror(so, m, EINVAL);
 5158         }
 5159 
 5160         /* copy sav values */
 5161         error = key_setsaval(sav, m, mhp);
 5162         if (error) {
 5163                 KEY_FREESAV(&sav);
 5164                 return key_senderror(so, m, error);
 5165         }
 5166 
 5167 #ifdef IPSEC_NAT_T
 5168         /*
 5169          * Handle more NAT-T info if present,
 5170          * now that we have a sav to fill.
 5171          */
 5172         if (type)
 5173                 sav->natt_type = type->sadb_x_nat_t_type_type;
 5174 
 5175         if (sport)
 5176                 KEY_PORTTOSADDR(&sav->sah->saidx.src,
 5177                     sport->sadb_x_nat_t_port_port);
 5178         if (dport)
 5179                 KEY_PORTTOSADDR(&sav->sah->saidx.dst,
 5180                     dport->sadb_x_nat_t_port_port);
 5181 
 5182 #if 0
 5183         /*
 5184          * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
 5185          * We should actually check for a minimum MTU here, if we
 5186          * want to support it in ip_output.
 5187          */
 5188         if (frag)
 5189                 sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
 5190 #endif
 5191 #endif
 5192 
 5193         /* check SA values to be mature. */
 5194         if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
 5195                 KEY_FREESAV(&sav);
 5196                 return key_senderror(so, m, 0);
 5197         }
 5198 
 5199     {
 5200         struct mbuf *n;
 5201 
 5202         /* set msg buf from mhp */
 5203         n = key_getmsgbuf_x1(m, mhp);
 5204         if (n == NULL) {
 5205                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 5206                 return key_senderror(so, m, ENOBUFS);
 5207         }
 5208 
 5209         m_freem(m);
 5210         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5211     }
 5212 }
 5213 
 5214 /*
 5215  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
 5216  * only called by key_update().
 5217  * OUT:
 5218  *      NULL    : not found
 5219  *      others  : found, pointer to a SA.
 5220  */
 5221 #ifdef IPSEC_DOSEQCHECK
 5222 static struct secasvar *
 5223 key_getsavbyseq(sah, seq)
 5224         struct secashead *sah;
 5225         u_int32_t seq;
 5226 {
 5227         struct secasvar *sav;
 5228         u_int state;
 5229 
 5230         state = SADB_SASTATE_LARVAL;
 5231 
 5232         /* search SAD with sequence number ? */
 5233         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 5234 
 5235                 KEY_CHKSASTATE(state, sav->state, __func__);
 5236 
 5237                 if (sav->seq == seq) {
 5238                         sa_addref(sav);
 5239                         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 5240                                 printf("DP %s cause refcnt++:%d SA:%p\n",
 5241                                         __func__, sav->refcnt, sav));
 5242                         return sav;
 5243                 }
 5244         }
 5245 
 5246         return NULL;
 5247 }
 5248 #endif
 5249 
 5250 /*
 5251  * SADB_ADD processing
 5252  * add an entry to SA database, when received
 5253  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 5254  *       key(AE), (identity(SD),) (sensitivity)>
 5255  * from the ikmpd,
 5256  * and send
 5257  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 5258  *       (identity(SD),) (sensitivity)>
 5259  * to the ikmpd.
 5260  *
 5261  * IGNORE identity and sensitivity messages.
 5262  *
 5263  * m will always be freed.
 5264  */
 5265 static int
 5266 key_add(so, m, mhp)
 5267         struct socket *so;
 5268         struct mbuf *m;
 5269         const struct sadb_msghdr *mhp;
 5270 {
 5271         struct sadb_sa *sa0;
 5272         struct sadb_address *src0, *dst0;
 5273 #ifdef IPSEC_NAT_T
 5274         struct sadb_x_nat_t_type *type;
 5275         struct sadb_address *iaddr, *raddr;
 5276         struct sadb_x_nat_t_frag *frag;
 5277 #endif
 5278         struct secasindex saidx;
 5279         struct secashead *newsah;
 5280         struct secasvar *newsav;
 5281         u_int16_t proto;
 5282         u_int8_t mode;
 5283         u_int32_t reqid;
 5284         int error;
 5285 
 5286         IPSEC_ASSERT(so != NULL, ("null socket"));
 5287         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 5288         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 5289         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 5290 
 5291         /* map satype to proto */
 5292         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5293                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
 5294                         __func__));
 5295                 return key_senderror(so, m, EINVAL);
 5296         }
 5297 
 5298         if (mhp->ext[SADB_EXT_SA] == NULL ||
 5299             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5300             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 5301             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
 5302              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
 5303             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
 5304              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
 5305             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
 5306              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
 5307             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
 5308              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
 5309                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5310                         __func__));
 5311                 return key_senderror(so, m, EINVAL);
 5312         }
 5313         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 5314             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5315             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5316                 /* XXX need more */
 5317                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5318                         __func__));
 5319                 return key_senderror(so, m, EINVAL);
 5320         }
 5321         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 5322                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 5323                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 5324         } else {
 5325                 mode = IPSEC_MODE_ANY;
 5326                 reqid = 0;
 5327         }
 5328 
 5329         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5330         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 5331         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 5332 
 5333         /* XXX boundary check against sa_len */
 5334         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 5335 
 5336         /*
 5337          * Make sure the port numbers are zero.
 5338          * In case of NAT-T we will update them later if needed.
 5339          */
 5340         KEY_PORTTOSADDR(&saidx.src, 0);
 5341         KEY_PORTTOSADDR(&saidx.dst, 0);
 5342 
 5343 #ifdef IPSEC_NAT_T
 5344         /*
 5345          * Handle NAT-T info if present.
 5346          */
 5347         if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
 5348             mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
 5349             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
 5350                 struct sadb_x_nat_t_port *sport, *dport;
 5351 
 5352                 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
 5353                     mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
 5354                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
 5355                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
 5356                             __func__));
 5357                         return key_senderror(so, m, EINVAL);
 5358                 }
 5359 
 5360                 type = (struct sadb_x_nat_t_type *)
 5361                     mhp->ext[SADB_X_EXT_NAT_T_TYPE];
 5362                 sport = (struct sadb_x_nat_t_port *)
 5363                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
 5364                 dport = (struct sadb_x_nat_t_port *)
 5365                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
 5366 
 5367                 if (sport)
 5368                         KEY_PORTTOSADDR(&saidx.src,
 5369                             sport->sadb_x_nat_t_port_port);
 5370                 if (dport)
 5371                         KEY_PORTTOSADDR(&saidx.dst,
 5372                             dport->sadb_x_nat_t_port_port);
 5373         } else {
 5374                 type = 0;
 5375         }
 5376         if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
 5377             mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
 5378                 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
 5379                     mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
 5380                         ipseclog((LOG_DEBUG, "%s: invalid message\n",
 5381                             __func__));
 5382                         return key_senderror(so, m, EINVAL);
 5383                 }
 5384                 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
 5385                 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
 5386                 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
 5387         } else {
 5388                 iaddr = raddr = NULL;
 5389         }
 5390         if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
 5391                 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
 5392                         ipseclog((LOG_DEBUG, "%s: invalid message\n",
 5393                             __func__));
 5394                         return key_senderror(so, m, EINVAL);
 5395                 }
 5396                 frag = (struct sadb_x_nat_t_frag *)
 5397                     mhp->ext[SADB_X_EXT_NAT_T_FRAG];
 5398         } else {
 5399                 frag = 0;
 5400         }
 5401 #endif
 5402 
 5403         /* get a SA header */
 5404         if ((newsah = key_getsah(&saidx)) == NULL) {
 5405                 /* create a new SA header */
 5406                 if ((newsah = key_newsah(&saidx)) == NULL) {
 5407                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
 5408                         return key_senderror(so, m, ENOBUFS);
 5409                 }
 5410         }
 5411 
 5412         /* set spidx if there */
 5413         /* XXX rewrite */
 5414         error = key_setident(newsah, m, mhp);
 5415         if (error) {
 5416                 return key_senderror(so, m, error);
 5417         }
 5418 
 5419         /* create new SA entry. */
 5420         /* We can create new SA only if SPI is differenct. */
 5421         SAHTREE_LOCK();
 5422         newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
 5423         SAHTREE_UNLOCK();
 5424         if (newsav != NULL) {
 5425                 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
 5426                 return key_senderror(so, m, EEXIST);
 5427         }
 5428         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
 5429         if (newsav == NULL) {
 5430                 return key_senderror(so, m, error);
 5431         }
 5432 
 5433 #ifdef IPSEC_NAT_T
 5434         /*
 5435          * Handle more NAT-T info if present,
 5436          * now that we have a sav to fill.
 5437          */
 5438         if (type)
 5439                 newsav->natt_type = type->sadb_x_nat_t_type_type;
 5440 
 5441 #if 0
 5442         /*
 5443          * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
 5444          * We should actually check for a minimum MTU here, if we
 5445          * want to support it in ip_output.
 5446          */
 5447         if (frag)
 5448                 newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
 5449 #endif
 5450 #endif
 5451 
 5452         /* check SA values to be mature. */
 5453         if ((error = key_mature(newsav)) != 0) {
 5454                 KEY_FREESAV(&newsav);
 5455                 return key_senderror(so, m, error);
 5456         }
 5457 
 5458         /*
 5459          * don't call key_freesav() here, as we would like to keep the SA
 5460          * in the database on success.
 5461          */
 5462 
 5463     {
 5464         struct mbuf *n;
 5465 
 5466         /* set msg buf from mhp */
 5467         n = key_getmsgbuf_x1(m, mhp);
 5468         if (n == NULL) {
 5469                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 5470                 return key_senderror(so, m, ENOBUFS);
 5471         }
 5472 
 5473         m_freem(m);
 5474         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5475     }
 5476 }
 5477 
 5478 /* m is retained */
 5479 static int
 5480 key_setident(sah, m, mhp)
 5481         struct secashead *sah;
 5482         struct mbuf *m;
 5483         const struct sadb_msghdr *mhp;
 5484 {
 5485         const struct sadb_ident *idsrc, *iddst;
 5486         int idsrclen, iddstlen;
 5487 
 5488         IPSEC_ASSERT(sah != NULL, ("null secashead"));
 5489         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 5490         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 5491         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 5492 
 5493         /* don't make buffer if not there */
 5494         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
 5495             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
 5496                 sah->idents = NULL;
 5497                 sah->identd = NULL;
 5498                 return 0;
 5499         }
 5500         
 5501         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
 5502             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
 5503                 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
 5504                 return EINVAL;
 5505         }
 5506 
 5507         idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
 5508         iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
 5509         idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
 5510         iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
 5511 
 5512         /* validity check */
 5513         if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
 5514                 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
 5515                 return EINVAL;
 5516         }
 5517 
 5518         switch (idsrc->sadb_ident_type) {
 5519         case SADB_IDENTTYPE_PREFIX:
 5520         case SADB_IDENTTYPE_FQDN:
 5521         case SADB_IDENTTYPE_USERFQDN:
 5522         default:
 5523                 /* XXX do nothing */
 5524                 sah->idents = NULL;
 5525                 sah->identd = NULL;
 5526                 return 0;
 5527         }
 5528 
 5529         /* make structure */
 5530         sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
 5531         if (sah->idents == NULL) {
 5532                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 5533                 return ENOBUFS;
 5534         }
 5535         sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
 5536         if (sah->identd == NULL) {
 5537                 free(sah->idents, M_IPSEC_MISC);
 5538                 sah->idents = NULL;
 5539                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 5540                 return ENOBUFS;
 5541         }
 5542         sah->idents->type = idsrc->sadb_ident_type;
 5543         sah->idents->id = idsrc->sadb_ident_id;
 5544 
 5545         sah->identd->type = iddst->sadb_ident_type;
 5546         sah->identd->id = iddst->sadb_ident_id;
 5547 
 5548         return 0;
 5549 }
 5550 
 5551 /*
 5552  * m will not be freed on return.
 5553  * it is caller's responsibility to free the result. 
 5554  */
 5555 static struct mbuf *
 5556 key_getmsgbuf_x1(m, mhp)
 5557         struct mbuf *m;
 5558         const struct sadb_msghdr *mhp;
 5559 {
 5560         struct mbuf *n;
 5561 
 5562         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 5563         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 5564         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 5565 
 5566         /* create new sadb_msg to reply. */
 5567         n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
 5568             SADB_EXT_SA, SADB_X_EXT_SA2,
 5569             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
 5570             SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
 5571             SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
 5572         if (!n)
 5573                 return NULL;
 5574 
 5575         if (n->m_len < sizeof(struct sadb_msg)) {
 5576                 n = m_pullup(n, sizeof(struct sadb_msg));
 5577                 if (n == NULL)
 5578                         return NULL;
 5579         }
 5580         mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
 5581         mtod(n, struct sadb_msg *)->sadb_msg_len =
 5582             PFKEY_UNIT64(n->m_pkthdr.len);
 5583 
 5584         return n;
 5585 }
 5586 
 5587 static int key_delete_all __P((struct socket *, struct mbuf *,
 5588         const struct sadb_msghdr *, u_int16_t));
 5589 
 5590 /*
 5591  * SADB_DELETE processing
 5592  * receive
 5593  *   <base, SA(*), address(SD)>
 5594  * from the ikmpd, and set SADB_SASTATE_DEAD,
 5595  * and send,
 5596  *   <base, SA(*), address(SD)>
 5597  * to the ikmpd.
 5598  *
 5599  * m will always be freed.
 5600  */
 5601 static int
 5602 key_delete(so, m, mhp)
 5603         struct socket *so;
 5604         struct mbuf *m;
 5605         const struct sadb_msghdr *mhp;
 5606 {
 5607         struct sadb_sa *sa0;
 5608         struct sadb_address *src0, *dst0;
 5609         struct secasindex saidx;
 5610         struct secashead *sah;
 5611         struct secasvar *sav = NULL;
 5612         u_int16_t proto;
 5613 
 5614         IPSEC_ASSERT(so != NULL, ("null socket"));
 5615         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 5616         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 5617         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 5618 
 5619         /* map satype to proto */
 5620         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5621                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
 5622                         __func__));
 5623                 return key_senderror(so, m, EINVAL);
 5624         }
 5625 
 5626         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5627             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 5628                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5629                         __func__));
 5630                 return key_senderror(so, m, EINVAL);
 5631         }
 5632 
 5633         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5634             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5635                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5636                         __func__));
 5637                 return key_senderror(so, m, EINVAL);
 5638         }
 5639 
 5640         if (mhp->ext[SADB_EXT_SA] == NULL) {
 5641                 /*
 5642                  * Caller wants us to delete all non-LARVAL SAs
 5643                  * that match the src/dst.  This is used during
 5644                  * IKE INITIAL-CONTACT.
 5645                  */
 5646                 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
 5647                 return key_delete_all(so, m, mhp, proto);
 5648         } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
 5649                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5650                         __func__));
 5651                 return key_senderror(so, m, EINVAL);
 5652         }
 5653 
 5654         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5655         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 5656         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 5657 
 5658         /* XXX boundary check against sa_len */
 5659         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5660 
 5661         /*
 5662          * Make sure the port numbers are zero.
 5663          * In case of NAT-T we will update them later if needed.
 5664          */
 5665         KEY_PORTTOSADDR(&saidx.src, 0);
 5666         KEY_PORTTOSADDR(&saidx.dst, 0);
 5667 
 5668 #ifdef IPSEC_NAT_T
 5669         /*
 5670          * Handle NAT-T info if present.
 5671          */
 5672         if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
 5673             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
 5674                 struct sadb_x_nat_t_port *sport, *dport;
 5675 
 5676                 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
 5677                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
 5678                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
 5679                             __func__));
 5680                         return key_senderror(so, m, EINVAL);
 5681                 }
 5682 
 5683                 sport = (struct sadb_x_nat_t_port *)
 5684                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
 5685                 dport = (struct sadb_x_nat_t_port *)
 5686                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
 5687 
 5688                 if (sport)
 5689                         KEY_PORTTOSADDR(&saidx.src,
 5690                             sport->sadb_x_nat_t_port_port);
 5691                 if (dport)
 5692                         KEY_PORTTOSADDR(&saidx.dst,
 5693                             dport->sadb_x_nat_t_port_port);
 5694         }
 5695 #endif
 5696 
 5697         /* get a SA header */
 5698         SAHTREE_LOCK();
 5699         LIST_FOREACH(sah, &V_sahtree, chain) {
 5700                 if (sah->state == SADB_SASTATE_DEAD)
 5701                         continue;
 5702                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5703                         continue;
 5704 
 5705                 /* get a SA with SPI. */
 5706                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
 5707                 if (sav)
 5708                         break;
 5709         }
 5710         if (sah == NULL) {
 5711                 SAHTREE_UNLOCK();
 5712                 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
 5713                 return key_senderror(so, m, ENOENT);
 5714         }
 5715 
 5716         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 5717         KEY_FREESAV(&sav);
 5718         SAHTREE_UNLOCK();
 5719 
 5720     {
 5721         struct mbuf *n;
 5722         struct sadb_msg *newmsg;
 5723 
 5724         /* create new sadb_msg to reply. */
 5725         /* XXX-BZ NAT-T extensions? */
 5726         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
 5727             SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 5728         if (!n)
 5729                 return key_senderror(so, m, ENOBUFS);
 5730 
 5731         if (n->m_len < sizeof(struct sadb_msg)) {
 5732                 n = m_pullup(n, sizeof(struct sadb_msg));
 5733                 if (n == NULL)
 5734                         return key_senderror(so, m, ENOBUFS);
 5735         }
 5736         newmsg = mtod(n, struct sadb_msg *);
 5737         newmsg->sadb_msg_errno = 0;
 5738         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 5739 
 5740         m_freem(m);
 5741         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5742     }
 5743 }
 5744 
 5745 /*
 5746  * delete all SAs for src/dst.  Called from key_delete().
 5747  */
 5748 static int
 5749 key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
 5750     u_int16_t proto)
 5751 {
 5752         struct sadb_address *src0, *dst0;
 5753         struct secasindex saidx;
 5754         struct secashead *sah;
 5755         struct secasvar *sav, *nextsav;
 5756         u_int stateidx, state;
 5757 
 5758         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 5759         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 5760 
 5761         /* XXX boundary check against sa_len */
 5762         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5763 
 5764         /*
 5765          * Make sure the port numbers are zero.
 5766          * In case of NAT-T we will update them later if needed.
 5767          */
 5768         KEY_PORTTOSADDR(&saidx.src, 0);
 5769         KEY_PORTTOSADDR(&saidx.dst, 0);
 5770 
 5771 #ifdef IPSEC_NAT_T
 5772         /*
 5773          * Handle NAT-T info if present.
 5774          */
 5775 
 5776         if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
 5777             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
 5778                 struct sadb_x_nat_t_port *sport, *dport;
 5779 
 5780                 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
 5781                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
 5782                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
 5783                             __func__));
 5784                         return key_senderror(so, m, EINVAL);
 5785                 }
 5786 
 5787                 sport = (struct sadb_x_nat_t_port *)
 5788                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
 5789                 dport = (struct sadb_x_nat_t_port *)
 5790                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
 5791 
 5792                 if (sport)
 5793                         KEY_PORTTOSADDR(&saidx.src,
 5794                             sport->sadb_x_nat_t_port_port);
 5795                 if (dport)
 5796                         KEY_PORTTOSADDR(&saidx.dst,
 5797                             dport->sadb_x_nat_t_port_port);
 5798         }
 5799 #endif
 5800 
 5801         SAHTREE_LOCK();
 5802         LIST_FOREACH(sah, &V_sahtree, chain) {
 5803                 if (sah->state == SADB_SASTATE_DEAD)
 5804                         continue;
 5805                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5806                         continue;
 5807 
 5808                 /* Delete all non-LARVAL SAs. */
 5809                 for (stateidx = 0;
 5810                      stateidx < _ARRAYLEN(saorder_state_alive);
 5811                      stateidx++) {
 5812                         state = saorder_state_alive[stateidx];
 5813                         if (state == SADB_SASTATE_LARVAL)
 5814                                 continue;
 5815                         for (sav = LIST_FIRST(&sah->savtree[state]);
 5816                              sav != NULL; sav = nextsav) {
 5817                                 nextsav = LIST_NEXT(sav, chain);
 5818                                 /* sanity check */
 5819                                 if (sav->state != state) {
 5820                                         ipseclog((LOG_DEBUG, "%s: invalid "
 5821                                                 "sav->state (queue %d SA %d)\n",
 5822                                                 __func__, state, sav->state));
 5823                                         continue;
 5824                                 }
 5825                                 
 5826                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 5827                                 KEY_FREESAV(&sav);
 5828                         }
 5829                 }
 5830         }
 5831         SAHTREE_UNLOCK();
 5832     {
 5833         struct mbuf *n;
 5834         struct sadb_msg *newmsg;
 5835 
 5836         /* create new sadb_msg to reply. */
 5837         /* XXX-BZ NAT-T extensions? */
 5838         n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
 5839             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 5840         if (!n)
 5841                 return key_senderror(so, m, ENOBUFS);
 5842 
 5843         if (n->m_len < sizeof(struct sadb_msg)) {
 5844                 n = m_pullup(n, sizeof(struct sadb_msg));
 5845                 if (n == NULL)
 5846                         return key_senderror(so, m, ENOBUFS);
 5847         }
 5848         newmsg = mtod(n, struct sadb_msg *);
 5849         newmsg->sadb_msg_errno = 0;
 5850         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 5851 
 5852         m_freem(m);
 5853         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5854     }
 5855 }
 5856 
 5857 /*
 5858  * SADB_GET processing
 5859  * receive
 5860  *   <base, SA(*), address(SD)>
 5861  * from the ikmpd, and get a SP and a SA to respond,
 5862  * and send,
 5863  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
 5864  *       (identity(SD),) (sensitivity)>
 5865  * to the ikmpd.
 5866  *
 5867  * m will always be freed.
 5868  */
 5869 static int
 5870 key_get(so, m, mhp)
 5871         struct socket *so;
 5872         struct mbuf *m;
 5873         const struct sadb_msghdr *mhp;
 5874 {
 5875         struct sadb_sa *sa0;
 5876         struct sadb_address *src0, *dst0;
 5877         struct secasindex saidx;
 5878         struct secashead *sah;
 5879         struct secasvar *sav = NULL;
 5880         u_int16_t proto;
 5881 
 5882         IPSEC_ASSERT(so != NULL, ("null socket"));
 5883         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 5884         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 5885         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 5886 
 5887         /* map satype to proto */
 5888         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5889                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
 5890                         __func__));
 5891                 return key_senderror(so, m, EINVAL);
 5892         }
 5893 
 5894         if (mhp->ext[SADB_EXT_SA] == NULL ||
 5895             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5896             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 5897                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5898                         __func__));
 5899                 return key_senderror(so, m, EINVAL);
 5900         }
 5901         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 5902             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5903             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5904                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 5905                         __func__));
 5906                 return key_senderror(so, m, EINVAL);
 5907         }
 5908 
 5909         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5910         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 5911         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 5912 
 5913         /* XXX boundary check against sa_len */
 5914         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5915 
 5916         /*
 5917          * Make sure the port numbers are zero.
 5918          * In case of NAT-T we will update them later if needed.
 5919          */
 5920         KEY_PORTTOSADDR(&saidx.src, 0);
 5921         KEY_PORTTOSADDR(&saidx.dst, 0);
 5922 
 5923 #ifdef IPSEC_NAT_T
 5924         /*
 5925          * Handle NAT-T info if present.
 5926          */
 5927 
 5928         if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
 5929             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
 5930                 struct sadb_x_nat_t_port *sport, *dport;
 5931 
 5932                 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
 5933                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
 5934                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
 5935                             __func__));
 5936                         return key_senderror(so, m, EINVAL);
 5937                 }
 5938 
 5939                 sport = (struct sadb_x_nat_t_port *)
 5940                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
 5941                 dport = (struct sadb_x_nat_t_port *)
 5942                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
 5943 
 5944                 if (sport)
 5945                         KEY_PORTTOSADDR(&saidx.src,
 5946                             sport->sadb_x_nat_t_port_port);
 5947                 if (dport)
 5948                         KEY_PORTTOSADDR(&saidx.dst,
 5949                             dport->sadb_x_nat_t_port_port);
 5950         }
 5951 #endif
 5952 
 5953         /* get a SA header */
 5954         SAHTREE_LOCK();
 5955         LIST_FOREACH(sah, &V_sahtree, chain) {
 5956                 if (sah->state == SADB_SASTATE_DEAD)
 5957                         continue;
 5958                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5959                         continue;
 5960 
 5961                 /* get a SA with SPI. */
 5962                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
 5963                 if (sav)
 5964                         break;
 5965         }
 5966         SAHTREE_UNLOCK();
 5967         if (sah == NULL) {
 5968                 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
 5969                 return key_senderror(so, m, ENOENT);
 5970         }
 5971 
 5972     {
 5973         struct mbuf *n;
 5974         u_int8_t satype;
 5975 
 5976         /* map proto to satype */
 5977         if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
 5978                 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
 5979                         __func__));
 5980                 return key_senderror(so, m, EINVAL);
 5981         }
 5982 
 5983         /* create new sadb_msg to reply. */
 5984         n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
 5985             mhp->msg->sadb_msg_pid);
 5986         if (!n)
 5987                 return key_senderror(so, m, ENOBUFS);
 5988 
 5989         m_freem(m);
 5990         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 5991     }
 5992 }
 5993 
 5994 /* XXX make it sysctl-configurable? */
 5995 static void
 5996 key_getcomb_setlifetime(comb)
 5997         struct sadb_comb *comb;
 5998 {
 5999 
 6000         comb->sadb_comb_soft_allocations = 1;
 6001         comb->sadb_comb_hard_allocations = 1;
 6002         comb->sadb_comb_soft_bytes = 0;
 6003         comb->sadb_comb_hard_bytes = 0;
 6004         comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
 6005         comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
 6006         comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
 6007         comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
 6008 }
 6009 
 6010 /*
 6011  * XXX reorder combinations by preference
 6012  * XXX no idea if the user wants ESP authentication or not
 6013  */
 6014 static struct mbuf *
 6015 key_getcomb_esp()
 6016 {
 6017         struct sadb_comb *comb;
 6018         struct enc_xform *algo;
 6019         struct mbuf *result = NULL, *m, *n;
 6020         int encmin;
 6021         int i, off, o;
 6022         int totlen;
 6023         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
 6024 
 6025         m = NULL;
 6026         for (i = 1; i <= SADB_EALG_MAX; i++) {
 6027                 algo = esp_algorithm_lookup(i);
 6028                 if (algo == NULL)
 6029                         continue;
 6030 
 6031                 /* discard algorithms with key size smaller than system min */
 6032                 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
 6033                         continue;
 6034                 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
 6035                         encmin = V_ipsec_esp_keymin;
 6036                 else
 6037                         encmin = _BITS(algo->minkey);
 6038 
 6039                 if (V_ipsec_esp_auth)
 6040                         m = key_getcomb_ah();
 6041                 else {
 6042                         IPSEC_ASSERT(l <= MLEN,
 6043                                 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
 6044                         MGET(m, M_DONTWAIT, MT_DATA);
 6045                         if (m) {
 6046                                 M_ALIGN(m, l);
 6047                                 m->m_len = l;
 6048                                 m->m_next = NULL;
 6049                                 bzero(mtod(m, caddr_t), m->m_len);
 6050                         }
 6051                 }
 6052                 if (!m)
 6053                         goto fail;
 6054 
 6055                 totlen = 0;
 6056                 for (n = m; n; n = n->m_next)
 6057                         totlen += n->m_len;
 6058                 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
 6059 
 6060                 for (off = 0; off < totlen; off += l) {
 6061                         n = m_pulldown(m, off, l, &o);
 6062                         if (!n) {
 6063                                 /* m is already freed */
 6064                                 goto fail;
 6065                         }
 6066                         comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
 6067                         bzero(comb, sizeof(*comb));
 6068                         key_getcomb_setlifetime(comb);
 6069                         comb->sadb_comb_encrypt = i;
 6070                         comb->sadb_comb_encrypt_minbits = encmin;
 6071                         comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
 6072                 }
 6073 
 6074                 if (!result)
 6075                         result = m;
 6076                 else
 6077                         m_cat(result, m);
 6078         }
 6079 
 6080         return result;
 6081 
 6082  fail:
 6083         if (result)
 6084                 m_freem(result);
 6085         return NULL;
 6086 }
 6087 
 6088 static void
 6089 key_getsizes_ah(
 6090         const struct auth_hash *ah,
 6091         int alg,
 6092         u_int16_t* min,
 6093         u_int16_t* max)
 6094 {
 6095 
 6096         *min = *max = ah->keysize;
 6097         if (ah->keysize == 0) {
 6098                 /*
 6099                  * Transform takes arbitrary key size but algorithm
 6100                  * key size is restricted.  Enforce this here.
 6101                  */
 6102                 switch (alg) {
 6103                 case SADB_X_AALG_MD5:   *min = *max = 16; break;
 6104                 case SADB_X_AALG_SHA:   *min = *max = 20; break;
 6105                 case SADB_X_AALG_NULL:  *min = 1; *max = 256; break;
 6106                 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
 6107                 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
 6108                 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
 6109                 default:
 6110                         DPRINTF(("%s: unknown AH algorithm %u\n",
 6111                                 __func__, alg));
 6112                         break;
 6113                 }
 6114         }
 6115 }
 6116 
 6117 /*
 6118  * XXX reorder combinations by preference
 6119  */
 6120 static struct mbuf *
 6121 key_getcomb_ah()
 6122 {
 6123         struct sadb_comb *comb;
 6124         struct auth_hash *algo;
 6125         struct mbuf *m;
 6126         u_int16_t minkeysize, maxkeysize;
 6127         int i;
 6128         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
 6129 
 6130         m = NULL;
 6131         for (i = 1; i <= SADB_AALG_MAX; i++) {
 6132 #if 1
 6133                 /* we prefer HMAC algorithms, not old algorithms */
 6134                 if (i != SADB_AALG_SHA1HMAC &&
 6135                     i != SADB_AALG_MD5HMAC  &&
 6136                     i != SADB_X_AALG_SHA2_256 &&
 6137                     i != SADB_X_AALG_SHA2_384 &&
 6138                     i != SADB_X_AALG_SHA2_512)
 6139                         continue;
 6140 #endif
 6141                 algo = ah_algorithm_lookup(i);
 6142                 if (!algo)
 6143                         continue;
 6144                 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
 6145                 /* discard algorithms with key size smaller than system min */
 6146                 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
 6147                         continue;
 6148 
 6149                 if (!m) {
 6150                         IPSEC_ASSERT(l <= MLEN,
 6151                                 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
 6152                         MGET(m, M_DONTWAIT, MT_DATA);
 6153                         if (m) {
 6154                                 M_ALIGN(m, l);
 6155                                 m->m_len = l;
 6156                                 m->m_next = NULL;
 6157                         }
 6158                 } else
 6159                         M_PREPEND(m, l, M_DONTWAIT);
 6160                 if (!m)
 6161                         return NULL;
 6162 
 6163                 comb = mtod(m, struct sadb_comb *);
 6164                 bzero(comb, sizeof(*comb));
 6165                 key_getcomb_setlifetime(comb);
 6166                 comb->sadb_comb_auth = i;
 6167                 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
 6168                 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
 6169         }
 6170 
 6171         return m;
 6172 }
 6173 
 6174 /*
 6175  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
 6176  * XXX reorder combinations by preference
 6177  */
 6178 static struct mbuf *
 6179 key_getcomb_ipcomp()
 6180 {
 6181         struct sadb_comb *comb;
 6182         struct comp_algo *algo;
 6183         struct mbuf *m;
 6184         int i;
 6185         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
 6186 
 6187         m = NULL;
 6188         for (i = 1; i <= SADB_X_CALG_MAX; i++) {
 6189                 algo = ipcomp_algorithm_lookup(i);
 6190                 if (!algo)
 6191                         continue;
 6192 
 6193                 if (!m) {
 6194                         IPSEC_ASSERT(l <= MLEN,
 6195                                 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
 6196                         MGET(m, M_DONTWAIT, MT_DATA);
 6197                         if (m) {
 6198                                 M_ALIGN(m, l);
 6199                                 m->m_len = l;
 6200                                 m->m_next = NULL;
 6201                         }
 6202                 } else
 6203                         M_PREPEND(m, l, M_DONTWAIT);
 6204                 if (!m)
 6205                         return NULL;
 6206 
 6207                 comb = mtod(m, struct sadb_comb *);
 6208                 bzero(comb, sizeof(*comb));
 6209                 key_getcomb_setlifetime(comb);
 6210                 comb->sadb_comb_encrypt = i;
 6211                 /* what should we set into sadb_comb_*_{min,max}bits? */
 6212         }
 6213 
 6214         return m;
 6215 }
 6216 
 6217 /*
 6218  * XXX no way to pass mode (transport/tunnel) to userland
 6219  * XXX replay checking?
 6220  * XXX sysctl interface to ipsec_{ah,esp}_keymin
 6221  */
 6222 static struct mbuf *
 6223 key_getprop(saidx)
 6224         const struct secasindex *saidx;
 6225 {
 6226         struct sadb_prop *prop;
 6227         struct mbuf *m, *n;
 6228         const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
 6229         int totlen;
 6230 
 6231         switch (saidx->proto)  {
 6232         case IPPROTO_ESP:
 6233                 m = key_getcomb_esp();
 6234                 break;
 6235         case IPPROTO_AH:
 6236                 m = key_getcomb_ah();
 6237                 break;
 6238         case IPPROTO_IPCOMP:
 6239                 m = key_getcomb_ipcomp();
 6240                 break;
 6241         default:
 6242                 return NULL;
 6243         }
 6244 
 6245         if (!m)
 6246                 return NULL;
 6247         M_PREPEND(m, l, M_DONTWAIT);
 6248         if (!m)
 6249                 return NULL;
 6250 
 6251         totlen = 0;
 6252         for (n = m; n; n = n->m_next)
 6253                 totlen += n->m_len;
 6254 
 6255         prop = mtod(m, struct sadb_prop *);
 6256         bzero(prop, sizeof(*prop));
 6257         prop->sadb_prop_len = PFKEY_UNIT64(totlen);
 6258         prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
 6259         prop->sadb_prop_replay = 32;    /* XXX */
 6260 
 6261         return m;
 6262 }
 6263 
 6264 /*
 6265  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
 6266  * send
 6267  *   <base, SA, address(SD), (address(P)), x_policy,
 6268  *       (identity(SD),) (sensitivity,) proposal>
 6269  * to KMD, and expect to receive
 6270  *   <base> with SADB_ACQUIRE if error occured,
 6271  * or
 6272  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
 6273  * from KMD by PF_KEY.
 6274  *
 6275  * XXX x_policy is outside of RFC2367 (KAME extension).
 6276  * XXX sensitivity is not supported.
 6277  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
 6278  * see comment for key_getcomb_ipcomp().
 6279  *
 6280  * OUT:
 6281  *    0     : succeed
 6282  *    others: error number
 6283  */
 6284 static int
 6285 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
 6286 {
 6287         struct mbuf *result = NULL, *m;
 6288         struct secacq *newacq;
 6289         u_int8_t satype;
 6290         int error = -1;
 6291         u_int32_t seq;
 6292 
 6293         IPSEC_ASSERT(saidx != NULL, ("null saidx"));
 6294         satype = key_proto2satype(saidx->proto);
 6295         IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
 6296 
 6297         /*
 6298          * We never do anything about acquirng SA.  There is anather
 6299          * solution that kernel blocks to send SADB_ACQUIRE message until
 6300          * getting something message from IKEd.  In later case, to be
 6301          * managed with ACQUIRING list.
 6302          */
 6303         /* Get an entry to check whether sending message or not. */
 6304         if ((newacq = key_getacq(saidx)) != NULL) {
 6305                 if (V_key_blockacq_count < newacq->count) {
 6306                         /* reset counter and do send message. */
 6307                         newacq->count = 0;
 6308                 } else {
 6309                         /* increment counter and do nothing. */
 6310                         newacq->count++;
 6311                         return 0;
 6312                 }
 6313         } else {
 6314                 /* make new entry for blocking to send SADB_ACQUIRE. */
 6315                 if ((newacq = key_newacq(saidx)) == NULL)
 6316                         return ENOBUFS;
 6317         }
 6318 
 6319 
 6320         seq = newacq->seq;
 6321         m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
 6322         if (!m) {
 6323                 error = ENOBUFS;
 6324                 goto fail;
 6325         }
 6326         result = m;
 6327 
 6328         /*
 6329          * No SADB_X_EXT_NAT_T_* here: we do not know
 6330          * anything related to NAT-T at this time.
 6331          */
 6332 
 6333         /* set sadb_address for saidx's. */
 6334         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 6335             &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
 6336         if (!m) {
 6337                 error = ENOBUFS;
 6338                 goto fail;
 6339         }
 6340         m_cat(result, m);
 6341 
 6342         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 6343             &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
 6344         if (!m) {
 6345                 error = ENOBUFS;
 6346                 goto fail;
 6347         }
 6348         m_cat(result, m);
 6349 
 6350         /* XXX proxy address (optional) */
 6351 
 6352         /* set sadb_x_policy */
 6353         if (sp) {
 6354                 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
 6355                 if (!m) {
 6356                         error = ENOBUFS;
 6357                         goto fail;
 6358                 }
 6359                 m_cat(result, m);
 6360         }
 6361 
 6362         /* XXX identity (optional) */
 6363 #if 0
 6364         if (idexttype && fqdn) {
 6365                 /* create identity extension (FQDN) */
 6366                 struct sadb_ident *id;
 6367                 int fqdnlen;
 6368 
 6369                 fqdnlen = strlen(fqdn) + 1;     /* +1 for terminating-NUL */
 6370                 id = (struct sadb_ident *)p;
 6371                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
 6372                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
 6373                 id->sadb_ident_exttype = idexttype;
 6374                 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
 6375                 bcopy(fqdn, id + 1, fqdnlen);
 6376                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
 6377         }
 6378 
 6379         if (idexttype) {
 6380                 /* create identity extension (USERFQDN) */
 6381                 struct sadb_ident *id;
 6382                 int userfqdnlen;
 6383 
 6384                 if (userfqdn) {
 6385                         /* +1 for terminating-NUL */
 6386                         userfqdnlen = strlen(userfqdn) + 1;
 6387                 } else
 6388                         userfqdnlen = 0;
 6389                 id = (struct sadb_ident *)p;
 6390                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
 6391                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
 6392                 id->sadb_ident_exttype = idexttype;
 6393                 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
 6394                 /* XXX is it correct? */
 6395                 if (curproc && curproc->p_cred)
 6396                         id->sadb_ident_id = curproc->p_cred->p_ruid;
 6397                 if (userfqdn && userfqdnlen)
 6398                         bcopy(userfqdn, id + 1, userfqdnlen);
 6399                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
 6400         }
 6401 #endif
 6402 
 6403         /* XXX sensitivity (optional) */
 6404 
 6405         /* create proposal/combination extension */
 6406         m = key_getprop(saidx);
 6407 #if 0
 6408         /*
 6409          * spec conformant: always attach proposal/combination extension,
 6410          * the problem is that we have no way to attach it for ipcomp,
 6411          * due to the way sadb_comb is declared in RFC2367.
 6412          */
 6413         if (!m) {
 6414                 error = ENOBUFS;
 6415                 goto fail;
 6416         }
 6417         m_cat(result, m);
 6418 #else
 6419         /*
 6420          * outside of spec; make proposal/combination extension optional.
 6421          */
 6422         if (m)
 6423                 m_cat(result, m);
 6424 #endif
 6425 
 6426         if ((result->m_flags & M_PKTHDR) == 0) {
 6427                 error = EINVAL;
 6428                 goto fail;
 6429         }
 6430 
 6431         if (result->m_len < sizeof(struct sadb_msg)) {
 6432                 result = m_pullup(result, sizeof(struct sadb_msg));
 6433                 if (result == NULL) {
 6434                         error = ENOBUFS;
 6435                         goto fail;
 6436                 }
 6437         }
 6438 
 6439         result->m_pkthdr.len = 0;
 6440         for (m = result; m; m = m->m_next)
 6441                 result->m_pkthdr.len += m->m_len;
 6442 
 6443         mtod(result, struct sadb_msg *)->sadb_msg_len =
 6444             PFKEY_UNIT64(result->m_pkthdr.len);
 6445 
 6446         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
 6447 
 6448  fail:
 6449         if (result)
 6450                 m_freem(result);
 6451         return error;
 6452 }
 6453 
 6454 static struct secacq *
 6455 key_newacq(const struct secasindex *saidx)
 6456 {
 6457         struct secacq *newacq;
 6458 
 6459         /* get new entry */
 6460         newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
 6461         if (newacq == NULL) {
 6462                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 6463                 return NULL;
 6464         }
 6465 
 6466         /* copy secindex */
 6467         bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
 6468         newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
 6469         newacq->created = time_second;
 6470         newacq->count = 0;
 6471 
 6472         /* add to acqtree */
 6473         ACQ_LOCK();
 6474         LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
 6475         ACQ_UNLOCK();
 6476 
 6477         return newacq;
 6478 }
 6479 
 6480 static struct secacq *
 6481 key_getacq(const struct secasindex *saidx)
 6482 {
 6483         struct secacq *acq;
 6484 
 6485         ACQ_LOCK();
 6486         LIST_FOREACH(acq, &V_acqtree, chain) {
 6487                 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
 6488                         break;
 6489         }
 6490         ACQ_UNLOCK();
 6491 
 6492         return acq;
 6493 }
 6494 
 6495 static struct secacq *
 6496 key_getacqbyseq(seq)
 6497         u_int32_t seq;
 6498 {
 6499         struct secacq *acq;
 6500 
 6501         ACQ_LOCK();
 6502         LIST_FOREACH(acq, &V_acqtree, chain) {
 6503                 if (acq->seq == seq)
 6504                         break;
 6505         }
 6506         ACQ_UNLOCK();
 6507 
 6508         return acq;
 6509 }
 6510 
 6511 static struct secspacq *
 6512 key_newspacq(spidx)
 6513         struct secpolicyindex *spidx;
 6514 {
 6515         struct secspacq *acq;
 6516 
 6517         /* get new entry */
 6518         acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
 6519         if (acq == NULL) {
 6520                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 6521                 return NULL;
 6522         }
 6523 
 6524         /* copy secindex */
 6525         bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
 6526         acq->created = time_second;
 6527         acq->count = 0;
 6528 
 6529         /* add to spacqtree */
 6530         SPACQ_LOCK();
 6531         LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
 6532         SPACQ_UNLOCK();
 6533 
 6534         return acq;
 6535 }
 6536 
 6537 static struct secspacq *
 6538 key_getspacq(spidx)
 6539         struct secpolicyindex *spidx;
 6540 {
 6541         struct secspacq *acq;
 6542 
 6543         SPACQ_LOCK();
 6544         LIST_FOREACH(acq, &V_spacqtree, chain) {
 6545                 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
 6546                         /* NB: return holding spacq_lock */
 6547                         return acq;
 6548                 }
 6549         }
 6550         SPACQ_UNLOCK();
 6551 
 6552         return NULL;
 6553 }
 6554 
 6555 /*
 6556  * SADB_ACQUIRE processing,
 6557  * in first situation, is receiving
 6558  *   <base>
 6559  * from the ikmpd, and clear sequence of its secasvar entry.
 6560  *
 6561  * In second situation, is receiving
 6562  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
 6563  * from a user land process, and return
 6564  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
 6565  * to the socket.
 6566  *
 6567  * m will always be freed.
 6568  */
 6569 static int
 6570 key_acquire2(so, m, mhp)
 6571         struct socket *so;
 6572         struct mbuf *m;
 6573         const struct sadb_msghdr *mhp;
 6574 {
 6575         const struct sadb_address *src0, *dst0;
 6576         struct secasindex saidx;
 6577         struct secashead *sah;
 6578         u_int16_t proto;
 6579         int error;
 6580 
 6581         IPSEC_ASSERT(so != NULL, ("null socket"));
 6582         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 6583         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 6584         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 6585 
 6586         /*
 6587          * Error message from KMd.
 6588          * We assume that if error was occured in IKEd, the length of PFKEY
 6589          * message is equal to the size of sadb_msg structure.
 6590          * We do not raise error even if error occured in this function.
 6591          */
 6592         if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
 6593                 struct secacq *acq;
 6594 
 6595                 /* check sequence number */
 6596                 if (mhp->msg->sadb_msg_seq == 0) {
 6597                         ipseclog((LOG_DEBUG, "%s: must specify sequence "
 6598                                 "number.\n", __func__));
 6599                         m_freem(m);
 6600                         return 0;
 6601                 }
 6602 
 6603                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
 6604                         /*
 6605                          * the specified larval SA is already gone, or we got
 6606                          * a bogus sequence number.  we can silently ignore it.
 6607                          */
 6608                         m_freem(m);
 6609                         return 0;
 6610                 }
 6611 
 6612                 /* reset acq counter in order to deletion by timehander. */
 6613                 acq->created = time_second;
 6614                 acq->count = 0;
 6615                 m_freem(m);
 6616                 return 0;
 6617         }
 6618 
 6619         /*
 6620          * This message is from user land.
 6621          */
 6622 
 6623         /* map satype to proto */
 6624         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 6625                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
 6626                         __func__));
 6627                 return key_senderror(so, m, EINVAL);
 6628         }
 6629 
 6630         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 6631             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 6632             mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
 6633                 /* error */
 6634                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
 6635                         __func__));
 6636                 return key_senderror(so, m, EINVAL);
 6637         }
 6638         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 6639             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
 6640             mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
 6641                 /* error */
 6642                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",        
 6643                         __func__));
 6644                 return key_senderror(so, m, EINVAL);
 6645         }
 6646 
 6647         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 6648         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 6649 
 6650         /* XXX boundary check against sa_len */
 6651         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 6652 
 6653         /*
 6654          * Make sure the port numbers are zero.
 6655          * In case of NAT-T we will update them later if needed.
 6656          */
 6657         KEY_PORTTOSADDR(&saidx.src, 0);
 6658         KEY_PORTTOSADDR(&saidx.dst, 0);
 6659 
 6660 #ifndef IPSEC_NAT_T
 6661         /*
 6662          * Handle NAT-T info if present.
 6663          */
 6664 
 6665         if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
 6666             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
 6667                 struct sadb_x_nat_t_port *sport, *dport;
 6668 
 6669                 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
 6670                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
 6671                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
 6672                             __func__));
 6673                         return key_senderror(so, m, EINVAL);
 6674                 }
 6675 
 6676                 sport = (struct sadb_x_nat_t_port *)
 6677                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
 6678                 dport = (struct sadb_x_nat_t_port *)
 6679                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
 6680 
 6681                 if (sport)
 6682                         KEY_PORTTOSADDR(&saidx.src,
 6683                             sport->sadb_x_nat_t_port_port);
 6684                 if (dport)
 6685                         KEY_PORTTOSADDR(&saidx.dst,
 6686                             dport->sadb_x_nat_t_port_port);
 6687         }
 6688 #endif
 6689 
 6690         /* get a SA index */
 6691         SAHTREE_LOCK();
 6692         LIST_FOREACH(sah, &V_sahtree, chain) {
 6693                 if (sah->state == SADB_SASTATE_DEAD)
 6694                         continue;
 6695                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
 6696                         break;
 6697         }
 6698         SAHTREE_UNLOCK();
 6699         if (sah != NULL) {
 6700                 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
 6701                 return key_senderror(so, m, EEXIST);
 6702         }
 6703 
 6704         error = key_acquire(&saidx, NULL);
 6705         if (error != 0) {
 6706                 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
 6707                         __func__, mhp->msg->sadb_msg_errno));
 6708                 return key_senderror(so, m, error);
 6709         }
 6710 
 6711         return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
 6712 }
 6713 
 6714 /*
 6715  * SADB_REGISTER processing.
 6716  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
 6717  * receive
 6718  *   <base>
 6719  * from the ikmpd, and register a socket to send PF_KEY messages,
 6720  * and send
 6721  *   <base, supported>
 6722  * to KMD by PF_KEY.
 6723  * If socket is detached, must free from regnode.
 6724  *
 6725  * m will always be freed.
 6726  */
 6727 static int
 6728 key_register(so, m, mhp)
 6729         struct socket *so;
 6730         struct mbuf *m;
 6731         const struct sadb_msghdr *mhp;
 6732 {
 6733         struct secreg *reg, *newreg = 0;
 6734 
 6735         IPSEC_ASSERT(so != NULL, ("null socket"));
 6736         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 6737         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 6738         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 6739 
 6740         /* check for invalid register message */
 6741         if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
 6742                 return key_senderror(so, m, EINVAL);
 6743 
 6744         /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
 6745         if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
 6746                 goto setmsg;
 6747 
 6748         /* check whether existing or not */
 6749         REGTREE_LOCK();
 6750         LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
 6751                 if (reg->so == so) {
 6752                         REGTREE_UNLOCK();
 6753                         ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
 6754                                 __func__));
 6755                         return key_senderror(so, m, EEXIST);
 6756                 }
 6757         }
 6758 
 6759         /* create regnode */
 6760         newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
 6761         if (newreg == NULL) {
 6762                 REGTREE_UNLOCK();
 6763                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 6764                 return key_senderror(so, m, ENOBUFS);
 6765         }
 6766 
 6767         newreg->so = so;
 6768         ((struct keycb *)sotorawcb(so))->kp_registered++;
 6769 
 6770         /* add regnode to regtree. */
 6771         LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
 6772         REGTREE_UNLOCK();
 6773 
 6774   setmsg:
 6775     {
 6776         struct mbuf *n;
 6777         struct sadb_msg *newmsg;
 6778         struct sadb_supported *sup;
 6779         u_int len, alen, elen;
 6780         int off;
 6781         int i;
 6782         struct sadb_alg *alg;
 6783 
 6784         /* create new sadb_msg to reply. */
 6785         alen = 0;
 6786         for (i = 1; i <= SADB_AALG_MAX; i++) {
 6787                 if (ah_algorithm_lookup(i))
 6788                         alen += sizeof(struct sadb_alg);
 6789         }
 6790         if (alen)
 6791                 alen += sizeof(struct sadb_supported);
 6792         elen = 0;
 6793         for (i = 1; i <= SADB_EALG_MAX; i++) {
 6794                 if (esp_algorithm_lookup(i))
 6795                         elen += sizeof(struct sadb_alg);
 6796         }
 6797         if (elen)
 6798                 elen += sizeof(struct sadb_supported);
 6799 
 6800         len = sizeof(struct sadb_msg) + alen + elen;
 6801 
 6802         if (len > MCLBYTES)
 6803                 return key_senderror(so, m, ENOBUFS);
 6804 
 6805         MGETHDR(n, M_DONTWAIT, MT_DATA);
 6806         if (len > MHLEN) {
 6807                 MCLGET(n, M_DONTWAIT);
 6808                 if ((n->m_flags & M_EXT) == 0) {
 6809                         m_freem(n);
 6810                         n = NULL;
 6811                 }
 6812         }
 6813         if (!n)
 6814                 return key_senderror(so, m, ENOBUFS);
 6815 
 6816         n->m_pkthdr.len = n->m_len = len;
 6817         n->m_next = NULL;
 6818         off = 0;
 6819 
 6820         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
 6821         newmsg = mtod(n, struct sadb_msg *);
 6822         newmsg->sadb_msg_errno = 0;
 6823         newmsg->sadb_msg_len = PFKEY_UNIT64(len);
 6824         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 6825 
 6826         /* for authentication algorithm */
 6827         if (alen) {
 6828                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
 6829                 sup->sadb_supported_len = PFKEY_UNIT64(alen);
 6830                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
 6831                 off += PFKEY_ALIGN8(sizeof(*sup));
 6832 
 6833                 for (i = 1; i <= SADB_AALG_MAX; i++) {
 6834                         struct auth_hash *aalgo;
 6835                         u_int16_t minkeysize, maxkeysize;
 6836 
 6837                         aalgo = ah_algorithm_lookup(i);
 6838                         if (!aalgo)
 6839                                 continue;
 6840                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
 6841                         alg->sadb_alg_id = i;
 6842                         alg->sadb_alg_ivlen = 0;
 6843                         key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
 6844                         alg->sadb_alg_minbits = _BITS(minkeysize);
 6845                         alg->sadb_alg_maxbits = _BITS(maxkeysize);
 6846                         off += PFKEY_ALIGN8(sizeof(*alg));
 6847                 }
 6848         }
 6849 
 6850         /* for encryption algorithm */
 6851         if (elen) {
 6852                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
 6853                 sup->sadb_supported_len = PFKEY_UNIT64(elen);
 6854                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
 6855                 off += PFKEY_ALIGN8(sizeof(*sup));
 6856 
 6857                 for (i = 1; i <= SADB_EALG_MAX; i++) {
 6858                         struct enc_xform *ealgo;
 6859 
 6860                         ealgo = esp_algorithm_lookup(i);
 6861                         if (!ealgo)
 6862                                 continue;
 6863                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
 6864                         alg->sadb_alg_id = i;
 6865                         alg->sadb_alg_ivlen = ealgo->blocksize;
 6866                         alg->sadb_alg_minbits = _BITS(ealgo->minkey);
 6867                         alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
 6868                         off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
 6869                 }
 6870         }
 6871 
 6872         IPSEC_ASSERT(off == len,
 6873                 ("length assumption failed (off %u len %u)", off, len));
 6874 
 6875         m_freem(m);
 6876         return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
 6877     }
 6878 }
 6879 
 6880 /*
 6881  * free secreg entry registered.
 6882  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
 6883  */
 6884 void
 6885 key_freereg(struct socket *so)
 6886 {
 6887         struct secreg *reg;
 6888         int i;
 6889 
 6890         IPSEC_ASSERT(so != NULL, ("NULL so"));
 6891 
 6892         /*
 6893          * check whether existing or not.
 6894          * check all type of SA, because there is a potential that
 6895          * one socket is registered to multiple type of SA.
 6896          */
 6897         REGTREE_LOCK();
 6898         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
 6899                 LIST_FOREACH(reg, &V_regtree[i], chain) {
 6900                         if (reg->so == so && __LIST_CHAINED(reg)) {
 6901                                 LIST_REMOVE(reg, chain);
 6902                                 free(reg, M_IPSEC_SAR);
 6903                                 break;
 6904                         }
 6905                 }
 6906         }
 6907         REGTREE_UNLOCK();
 6908 }
 6909 
 6910 /*
 6911  * SADB_EXPIRE processing
 6912  * send
 6913  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
 6914  * to KMD by PF_KEY.
 6915  * NOTE: We send only soft lifetime extension.
 6916  *
 6917  * OUT: 0       : succeed
 6918  *      others  : error number
 6919  */
 6920 static int
 6921 key_expire(struct secasvar *sav)
 6922 {
 6923         int s;
 6924         int satype;
 6925         struct mbuf *result = NULL, *m;
 6926         int len;
 6927         int error = -1;
 6928         struct sadb_lifetime *lt;
 6929 
 6930         /* XXX: Why do we lock ? */
 6931         s = splnet();   /*called from softclock()*/
 6932 
 6933         IPSEC_ASSERT (sav != NULL, ("null sav"));
 6934         IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
 6935 
 6936         /* set msg header */
 6937         satype = key_proto2satype(sav->sah->saidx.proto);
 6938         IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
 6939         m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
 6940         if (!m) {
 6941                 error = ENOBUFS;
 6942                 goto fail;
 6943         }
 6944         result = m;
 6945 
 6946         /* create SA extension */
 6947         m = key_setsadbsa(sav);
 6948         if (!m) {
 6949                 error = ENOBUFS;
 6950                 goto fail;
 6951         }
 6952         m_cat(result, m);
 6953 
 6954         /* create SA extension */
 6955         m = key_setsadbxsa2(sav->sah->saidx.mode,
 6956                         sav->replay ? sav->replay->count : 0,
 6957                         sav->sah->saidx.reqid);
 6958         if (!m) {
 6959                 error = ENOBUFS;
 6960                 goto fail;
 6961         }
 6962         m_cat(result, m);
 6963 
 6964         /* create lifetime extension (current and soft) */
 6965         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
 6966         m = key_alloc_mbuf(len);
 6967         if (!m || m->m_next) {  /*XXX*/
 6968                 if (m)
 6969                         m_freem(m);
 6970                 error = ENOBUFS;
 6971                 goto fail;
 6972         }
 6973         bzero(mtod(m, caddr_t), len);
 6974         lt = mtod(m, struct sadb_lifetime *);
 6975         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 6976         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
 6977         lt->sadb_lifetime_allocations = sav->lft_c->allocations;
 6978         lt->sadb_lifetime_bytes = sav->lft_c->bytes;
 6979         lt->sadb_lifetime_addtime = sav->lft_c->addtime;
 6980         lt->sadb_lifetime_usetime = sav->lft_c->usetime;
 6981         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
 6982         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 6983         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
 6984         lt->sadb_lifetime_allocations = sav->lft_s->allocations;
 6985         lt->sadb_lifetime_bytes = sav->lft_s->bytes;
 6986         lt->sadb_lifetime_addtime = sav->lft_s->addtime;
 6987         lt->sadb_lifetime_usetime = sav->lft_s->usetime;
 6988         m_cat(result, m);
 6989 
 6990         /* set sadb_address for source */
 6991         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 6992             &sav->sah->saidx.src.sa,
 6993             FULLMASK, IPSEC_ULPROTO_ANY);
 6994         if (!m) {
 6995                 error = ENOBUFS;
 6996                 goto fail;
 6997         }
 6998         m_cat(result, m);
 6999 
 7000         /* set sadb_address for destination */
 7001         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 7002             &sav->sah->saidx.dst.sa,
 7003             FULLMASK, IPSEC_ULPROTO_ANY);
 7004         if (!m) {
 7005                 error = ENOBUFS;
 7006                 goto fail;
 7007         }
 7008         m_cat(result, m);
 7009 
 7010         /*
 7011          * XXX-BZ Handle NAT-T extensions here.
 7012          */
 7013 
 7014         if ((result->m_flags & M_PKTHDR) == 0) {
 7015                 error = EINVAL;
 7016                 goto fail;
 7017         }
 7018 
 7019         if (result->m_len < sizeof(struct sadb_msg)) {
 7020                 result = m_pullup(result, sizeof(struct sadb_msg));
 7021                 if (result == NULL) {
 7022                         error = ENOBUFS;
 7023                         goto fail;
 7024                 }
 7025         }
 7026 
 7027         result->m_pkthdr.len = 0;
 7028         for (m = result; m; m = m->m_next)
 7029                 result->m_pkthdr.len += m->m_len;
 7030 
 7031         mtod(result, struct sadb_msg *)->sadb_msg_len =
 7032             PFKEY_UNIT64(result->m_pkthdr.len);
 7033 
 7034         splx(s);
 7035         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
 7036 
 7037  fail:
 7038         if (result)
 7039                 m_freem(result);
 7040         splx(s);
 7041         return error;
 7042 }
 7043 
 7044 /*
 7045  * SADB_FLUSH processing
 7046  * receive
 7047  *   <base>
 7048  * from the ikmpd, and free all entries in secastree.
 7049  * and send,
 7050  *   <base>
 7051  * to the ikmpd.
 7052  * NOTE: to do is only marking SADB_SASTATE_DEAD.
 7053  *
 7054  * m will always be freed.
 7055  */
 7056 static int
 7057 key_flush(so, m, mhp)
 7058         struct socket *so;
 7059         struct mbuf *m;
 7060         const struct sadb_msghdr *mhp;
 7061 {
 7062         struct sadb_msg *newmsg;
 7063         struct secashead *sah, *nextsah;
 7064         struct secasvar *sav, *nextsav;
 7065         u_int16_t proto;
 7066         u_int8_t state;
 7067         u_int stateidx;
 7068 
 7069         IPSEC_ASSERT(so != NULL, ("null socket"));
 7070         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 7071         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 7072 
 7073         /* map satype to proto */
 7074         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 7075                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
 7076                         __func__));
 7077                 return key_senderror(so, m, EINVAL);
 7078         }
 7079 
 7080         /* no SATYPE specified, i.e. flushing all SA. */
 7081         SAHTREE_LOCK();
 7082         for (sah = LIST_FIRST(&V_sahtree);
 7083              sah != NULL;
 7084              sah = nextsah) {
 7085                 nextsah = LIST_NEXT(sah, chain);
 7086 
 7087                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
 7088                  && proto != sah->saidx.proto)
 7089                         continue;
 7090 
 7091                 for (stateidx = 0;
 7092                      stateidx < _ARRAYLEN(saorder_state_alive);
 7093                      stateidx++) {
 7094                         state = saorder_state_any[stateidx];
 7095                         for (sav = LIST_FIRST(&sah->savtree[state]);
 7096                              sav != NULL;
 7097                              sav = nextsav) {
 7098 
 7099                                 nextsav = LIST_NEXT(sav, chain);
 7100 
 7101                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 7102                                 KEY_FREESAV(&sav);
 7103                         }
 7104                 }
 7105 
 7106                 sah->state = SADB_SASTATE_DEAD;
 7107         }
 7108         SAHTREE_UNLOCK();
 7109 
 7110         if (m->m_len < sizeof(struct sadb_msg) ||
 7111             sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
 7112                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 7113                 return key_senderror(so, m, ENOBUFS);
 7114         }
 7115 
 7116         if (m->m_next)
 7117                 m_freem(m->m_next);
 7118         m->m_next = NULL;
 7119         m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
 7120         newmsg = mtod(m, struct sadb_msg *);
 7121         newmsg->sadb_msg_errno = 0;
 7122         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
 7123 
 7124         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 7125 }
 7126 
 7127 /*
 7128  * SADB_DUMP processing
 7129  * dump all entries including status of DEAD in SAD.
 7130  * receive
 7131  *   <base>
 7132  * from the ikmpd, and dump all secasvar leaves
 7133  * and send,
 7134  *   <base> .....
 7135  * to the ikmpd.
 7136  *
 7137  * m will always be freed.
 7138  */
 7139 static int
 7140 key_dump(so, m, mhp)
 7141         struct socket *so;
 7142         struct mbuf *m;
 7143         const struct sadb_msghdr *mhp;
 7144 {
 7145         struct secashead *sah;
 7146         struct secasvar *sav;
 7147         u_int16_t proto;
 7148         u_int stateidx;
 7149         u_int8_t satype;
 7150         u_int8_t state;
 7151         int cnt;
 7152         struct sadb_msg *newmsg;
 7153         struct mbuf *n;
 7154 
 7155         IPSEC_ASSERT(so != NULL, ("null socket"));
 7156         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 7157         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 7158         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 7159 
 7160         /* map satype to proto */
 7161         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 7162                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
 7163                         __func__));
 7164                 return key_senderror(so, m, EINVAL);
 7165         }
 7166 
 7167         /* count sav entries to be sent to the userland. */
 7168         cnt = 0;
 7169         SAHTREE_LOCK();
 7170         LIST_FOREACH(sah, &V_sahtree, chain) {
 7171                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
 7172                  && proto != sah->saidx.proto)
 7173                         continue;
 7174 
 7175                 for (stateidx = 0;
 7176                      stateidx < _ARRAYLEN(saorder_state_any);
 7177                      stateidx++) {
 7178                         state = saorder_state_any[stateidx];
 7179                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 7180                                 cnt++;
 7181                         }
 7182                 }
 7183         }
 7184 
 7185         if (cnt == 0) {
 7186                 SAHTREE_UNLOCK();
 7187                 return key_senderror(so, m, ENOENT);
 7188         }
 7189 
 7190         /* send this to the userland, one at a time. */
 7191         newmsg = NULL;
 7192         LIST_FOREACH(sah, &V_sahtree, chain) {
 7193                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
 7194                  && proto != sah->saidx.proto)
 7195                         continue;
 7196 
 7197                 /* map proto to satype */
 7198                 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
 7199                         SAHTREE_UNLOCK();
 7200                         ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
 7201                                 "SAD.\n", __func__));
 7202                         return key_senderror(so, m, EINVAL);
 7203                 }
 7204 
 7205                 for (stateidx = 0;
 7206                      stateidx < _ARRAYLEN(saorder_state_any);
 7207                      stateidx++) {
 7208                         state = saorder_state_any[stateidx];
 7209                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 7210                                 n = key_setdumpsa(sav, SADB_DUMP, satype,
 7211                                     --cnt, mhp->msg->sadb_msg_pid);
 7212                                 if (!n) {
 7213                                         SAHTREE_UNLOCK();
 7214                                         return key_senderror(so, m, ENOBUFS);
 7215                                 }
 7216                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 7217                         }
 7218                 }
 7219         }
 7220         SAHTREE_UNLOCK();
 7221 
 7222         m_freem(m);
 7223         return 0;
 7224 }
 7225 
 7226 /*
 7227  * SADB_X_PROMISC processing
 7228  *
 7229  * m will always be freed.
 7230  */
 7231 static int
 7232 key_promisc(so, m, mhp)
 7233         struct socket *so;
 7234         struct mbuf *m;
 7235         const struct sadb_msghdr *mhp;
 7236 {
 7237         int olen;
 7238 
 7239         IPSEC_ASSERT(so != NULL, ("null socket"));
 7240         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 7241         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 7242         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
 7243 
 7244         olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
 7245 
 7246         if (olen < sizeof(struct sadb_msg)) {
 7247 #if 1
 7248                 return key_senderror(so, m, EINVAL);
 7249 #else
 7250                 m_freem(m);
 7251                 return 0;
 7252 #endif
 7253         } else if (olen == sizeof(struct sadb_msg)) {
 7254                 /* enable/disable promisc mode */
 7255                 struct keycb *kp;
 7256 
 7257                 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
 7258                         return key_senderror(so, m, EINVAL);
 7259                 mhp->msg->sadb_msg_errno = 0;
 7260                 switch (mhp->msg->sadb_msg_satype) {
 7261                 case 0:
 7262                 case 1:
 7263                         kp->kp_promisc = mhp->msg->sadb_msg_satype;
 7264                         break;
 7265                 default:
 7266                         return key_senderror(so, m, EINVAL);
 7267                 }
 7268 
 7269                 /* send the original message back to everyone */
 7270                 mhp->msg->sadb_msg_errno = 0;
 7271                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 7272         } else {
 7273                 /* send packet as is */
 7274 
 7275                 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
 7276 
 7277                 /* TODO: if sadb_msg_seq is specified, send to specific pid */
 7278                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 7279         }
 7280 }
 7281 
 7282 static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
 7283                 const struct sadb_msghdr *)) = {
 7284         NULL,           /* SADB_RESERVED */
 7285         key_getspi,     /* SADB_GETSPI */
 7286         key_update,     /* SADB_UPDATE */
 7287         key_add,        /* SADB_ADD */
 7288         key_delete,     /* SADB_DELETE */
 7289         key_get,        /* SADB_GET */
 7290         key_acquire2,   /* SADB_ACQUIRE */
 7291         key_register,   /* SADB_REGISTER */
 7292         NULL,           /* SADB_EXPIRE */
 7293         key_flush,      /* SADB_FLUSH */
 7294         key_dump,       /* SADB_DUMP */
 7295         key_promisc,    /* SADB_X_PROMISC */
 7296         NULL,           /* SADB_X_PCHANGE */
 7297         key_spdadd,     /* SADB_X_SPDUPDATE */
 7298         key_spdadd,     /* SADB_X_SPDADD */
 7299         key_spddelete,  /* SADB_X_SPDDELETE */
 7300         key_spdget,     /* SADB_X_SPDGET */
 7301         NULL,           /* SADB_X_SPDACQUIRE */
 7302         key_spddump,    /* SADB_X_SPDDUMP */
 7303         key_spdflush,   /* SADB_X_SPDFLUSH */
 7304         key_spdadd,     /* SADB_X_SPDSETIDX */
 7305         NULL,           /* SADB_X_SPDEXPIRE */
 7306         key_spddelete2, /* SADB_X_SPDDELETE2 */
 7307 };
 7308 
 7309 /*
 7310  * parse sadb_msg buffer to process PFKEYv2,
 7311  * and create a data to response if needed.
 7312  * I think to be dealed with mbuf directly.
 7313  * IN:
 7314  *     msgp  : pointer to pointer to a received buffer pulluped.
 7315  *             This is rewrited to response.
 7316  *     so    : pointer to socket.
 7317  * OUT:
 7318  *    length for buffer to send to user process.
 7319  */
 7320 int
 7321 key_parse(m, so)
 7322         struct mbuf *m;
 7323         struct socket *so;
 7324 {
 7325         struct sadb_msg *msg;
 7326         struct sadb_msghdr mh;
 7327         u_int orglen;
 7328         int error;
 7329         int target;
 7330 
 7331         IPSEC_ASSERT(so != NULL, ("null socket"));
 7332         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 7333 
 7334 #if 0   /*kdebug_sadb assumes msg in linear buffer*/
 7335         KEYDEBUG(KEYDEBUG_KEY_DUMP,
 7336                 ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
 7337                 kdebug_sadb(msg));
 7338 #endif
 7339 
 7340         if (m->m_len < sizeof(struct sadb_msg)) {
 7341                 m = m_pullup(m, sizeof(struct sadb_msg));
 7342                 if (!m)
 7343                         return ENOBUFS;
 7344         }
 7345         msg = mtod(m, struct sadb_msg *);
 7346         orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
 7347         target = KEY_SENDUP_ONE;
 7348 
 7349         if ((m->m_flags & M_PKTHDR) == 0 ||
 7350             m->m_pkthdr.len != m->m_pkthdr.len) {
 7351                 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
 7352                 V_pfkeystat.out_invlen++;
 7353                 error = EINVAL;
 7354                 goto senderror;
 7355         }
 7356 
 7357         if (msg->sadb_msg_version != PF_KEY_V2) {
 7358                 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
 7359                     __func__, msg->sadb_msg_version));
 7360                 V_pfkeystat.out_invver++;
 7361                 error = EINVAL;
 7362                 goto senderror;
 7363         }
 7364 
 7365         if (msg->sadb_msg_type > SADB_MAX) {
 7366                 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
 7367                     __func__, msg->sadb_msg_type));
 7368                 V_pfkeystat.out_invmsgtype++;
 7369                 error = EINVAL;
 7370                 goto senderror;
 7371         }
 7372 
 7373         /* for old-fashioned code - should be nuked */
 7374         if (m->m_pkthdr.len > MCLBYTES) {
 7375                 m_freem(m);
 7376                 return ENOBUFS;
 7377         }
 7378         if (m->m_next) {
 7379                 struct mbuf *n;
 7380 
 7381                 MGETHDR(n, M_DONTWAIT, MT_DATA);
 7382                 if (n && m->m_pkthdr.len > MHLEN) {
 7383                         MCLGET(n, M_DONTWAIT);
 7384                         if ((n->m_flags & M_EXT) == 0) {
 7385                                 m_free(n);
 7386                                 n = NULL;
 7387                         }
 7388                 }
 7389                 if (!n) {
 7390                         m_freem(m);
 7391                         return ENOBUFS;
 7392                 }
 7393                 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
 7394                 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
 7395                 n->m_next = NULL;
 7396                 m_freem(m);
 7397                 m = n;
 7398         }
 7399 
 7400         /* align the mbuf chain so that extensions are in contiguous region. */
 7401         error = key_align(m, &mh);
 7402         if (error)
 7403                 return error;
 7404 
 7405         msg = mh.msg;
 7406 
 7407         /* check SA type */
 7408         switch (msg->sadb_msg_satype) {
 7409         case SADB_SATYPE_UNSPEC:
 7410                 switch (msg->sadb_msg_type) {
 7411                 case SADB_GETSPI:
 7412                 case SADB_UPDATE:
 7413                 case SADB_ADD:
 7414                 case SADB_DELETE:
 7415                 case SADB_GET:
 7416                 case SADB_ACQUIRE:
 7417                 case SADB_EXPIRE:
 7418                         ipseclog((LOG_DEBUG, "%s: must specify satype "
 7419                             "when msg type=%u.\n", __func__,
 7420                             msg->sadb_msg_type));
 7421                         V_pfkeystat.out_invsatype++;
 7422                         error = EINVAL;
 7423                         goto senderror;
 7424                 }
 7425                 break;
 7426         case SADB_SATYPE_AH:
 7427         case SADB_SATYPE_ESP:
 7428         case SADB_X_SATYPE_IPCOMP:
 7429         case SADB_X_SATYPE_TCPSIGNATURE:
 7430                 switch (msg->sadb_msg_type) {
 7431                 case SADB_X_SPDADD:
 7432                 case SADB_X_SPDDELETE:
 7433                 case SADB_X_SPDGET:
 7434                 case SADB_X_SPDDUMP:
 7435                 case SADB_X_SPDFLUSH:
 7436                 case SADB_X_SPDSETIDX:
 7437                 case SADB_X_SPDUPDATE:
 7438                 case SADB_X_SPDDELETE2:
 7439                         ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
 7440                                 __func__, msg->sadb_msg_type));
 7441                         V_pfkeystat.out_invsatype++;
 7442                         error = EINVAL;
 7443                         goto senderror;
 7444                 }
 7445                 break;
 7446         case SADB_SATYPE_RSVP:
 7447         case SADB_SATYPE_OSPFV2:
 7448         case SADB_SATYPE_RIPV2:
 7449         case SADB_SATYPE_MIP:
 7450                 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
 7451                         __func__, msg->sadb_msg_satype));
 7452                 V_pfkeystat.out_invsatype++;
 7453                 error = EOPNOTSUPP;
 7454                 goto senderror;
 7455         case 1: /* XXX: What does it do? */
 7456                 if (msg->sadb_msg_type == SADB_X_PROMISC)
 7457                         break;
 7458                 /*FALLTHROUGH*/
 7459         default:
 7460                 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
 7461                         __func__, msg->sadb_msg_satype));
 7462                 V_pfkeystat.out_invsatype++;
 7463                 error = EINVAL;
 7464                 goto senderror;
 7465         }
 7466 
 7467         /* check field of upper layer protocol and address family */
 7468         if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
 7469          && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
 7470                 struct sadb_address *src0, *dst0;
 7471                 u_int plen;
 7472 
 7473                 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
 7474                 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
 7475 
 7476                 /* check upper layer protocol */
 7477                 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
 7478                         ipseclog((LOG_DEBUG, "%s: upper layer protocol "
 7479                                 "mismatched.\n", __func__));
 7480                         V_pfkeystat.out_invaddr++;
 7481                         error = EINVAL;
 7482                         goto senderror;
 7483                 }
 7484 
 7485                 /* check family */
 7486                 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
 7487                     PFKEY_ADDR_SADDR(dst0)->sa_family) {
 7488                         ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
 7489                                 __func__));
 7490                         V_pfkeystat.out_invaddr++;
 7491                         error = EINVAL;
 7492                         goto senderror;
 7493                 }
 7494                 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
 7495                     PFKEY_ADDR_SADDR(dst0)->sa_len) {
 7496                         ipseclog((LOG_DEBUG, "%s: address struct size "
 7497                                 "mismatched.\n", __func__));
 7498                         V_pfkeystat.out_invaddr++;
 7499                         error = EINVAL;
 7500                         goto senderror;
 7501                 }
 7502 
 7503                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
 7504                 case AF_INET:
 7505                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
 7506                             sizeof(struct sockaddr_in)) {
 7507                                 V_pfkeystat.out_invaddr++;
 7508                                 error = EINVAL;
 7509                                 goto senderror;
 7510                         }
 7511                         break;
 7512                 case AF_INET6:
 7513                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
 7514                             sizeof(struct sockaddr_in6)) {
 7515                                 V_pfkeystat.out_invaddr++;
 7516                                 error = EINVAL;
 7517                                 goto senderror;
 7518                         }
 7519                         break;
 7520                 default:
 7521                         ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
 7522                                 __func__));
 7523                         V_pfkeystat.out_invaddr++;
 7524                         error = EAFNOSUPPORT;
 7525                         goto senderror;
 7526                 }
 7527 
 7528                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
 7529                 case AF_INET:
 7530                         plen = sizeof(struct in_addr) << 3;
 7531                         break;
 7532                 case AF_INET6:
 7533                         plen = sizeof(struct in6_addr) << 3;
 7534                         break;
 7535                 default:
 7536                         plen = 0;       /*fool gcc*/
 7537                         break;
 7538                 }
 7539 
 7540                 /* check max prefix length */
 7541                 if (src0->sadb_address_prefixlen > plen ||
 7542                     dst0->sadb_address_prefixlen > plen) {
 7543                         ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
 7544                                 __func__));
 7545                         V_pfkeystat.out_invaddr++;
 7546                         error = EINVAL;
 7547                         goto senderror;
 7548                 }
 7549 
 7550                 /*
 7551                  * prefixlen == 0 is valid because there can be a case when
 7552                  * all addresses are matched.
 7553                  */
 7554         }
 7555 
 7556         if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
 7557             key_typesw[msg->sadb_msg_type] == NULL) {
 7558                 V_pfkeystat.out_invmsgtype++;
 7559                 error = EINVAL;
 7560                 goto senderror;
 7561         }
 7562 
 7563         return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
 7564 
 7565 senderror:
 7566         msg->sadb_msg_errno = error;
 7567         return key_sendup_mbuf(so, m, target);
 7568 }
 7569 
 7570 static int
 7571 key_senderror(so, m, code)
 7572         struct socket *so;
 7573         struct mbuf *m;
 7574         int code;
 7575 {
 7576         struct sadb_msg *msg;
 7577 
 7578         IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
 7579                 ("mbuf too small, len %u", m->m_len));
 7580 
 7581         msg = mtod(m, struct sadb_msg *);
 7582         msg->sadb_msg_errno = code;
 7583         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
 7584 }
 7585 
 7586 /*
 7587  * set the pointer to each header into message buffer.
 7588  * m will be freed on error.
 7589  * XXX larger-than-MCLBYTES extension?
 7590  */
 7591 static int
 7592 key_align(m, mhp)
 7593         struct mbuf *m;
 7594         struct sadb_msghdr *mhp;
 7595 {
 7596         struct mbuf *n;
 7597         struct sadb_ext *ext;
 7598         size_t off, end;
 7599         int extlen;
 7600         int toff;
 7601 
 7602         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 7603         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
 7604         IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
 7605                 ("mbuf too small, len %u", m->m_len));
 7606 
 7607         /* initialize */
 7608         bzero(mhp, sizeof(*mhp));
 7609 
 7610         mhp->msg = mtod(m, struct sadb_msg *);
 7611         mhp->ext[0] = (struct sadb_ext *)mhp->msg;      /*XXX backward compat */
 7612 
 7613         end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
 7614         extlen = end;   /*just in case extlen is not updated*/
 7615         for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
 7616                 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
 7617                 if (!n) {
 7618                         /* m is already freed */
 7619                         return ENOBUFS;
 7620                 }
 7621                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
 7622 
 7623                 /* set pointer */
 7624                 switch (ext->sadb_ext_type) {
 7625                 case SADB_EXT_SA:
 7626                 case SADB_EXT_ADDRESS_SRC:
 7627                 case SADB_EXT_ADDRESS_DST:
 7628                 case SADB_EXT_ADDRESS_PROXY:
 7629                 case SADB_EXT_LIFETIME_CURRENT:
 7630                 case SADB_EXT_LIFETIME_HARD:
 7631                 case SADB_EXT_LIFETIME_SOFT:
 7632                 case SADB_EXT_KEY_AUTH:
 7633                 case SADB_EXT_KEY_ENCRYPT:
 7634                 case SADB_EXT_IDENTITY_SRC:
 7635                 case SADB_EXT_IDENTITY_DST:
 7636                 case SADB_EXT_SENSITIVITY:
 7637                 case SADB_EXT_PROPOSAL:
 7638                 case SADB_EXT_SUPPORTED_AUTH:
 7639                 case SADB_EXT_SUPPORTED_ENCRYPT:
 7640                 case SADB_EXT_SPIRANGE:
 7641                 case SADB_X_EXT_POLICY:
 7642                 case SADB_X_EXT_SA2:
 7643 #ifdef IPSEC_NAT_T
 7644                 case SADB_X_EXT_NAT_T_TYPE:
 7645                 case SADB_X_EXT_NAT_T_SPORT:
 7646                 case SADB_X_EXT_NAT_T_DPORT:
 7647                 case SADB_X_EXT_NAT_T_OAI:
 7648                 case SADB_X_EXT_NAT_T_OAR:
 7649                 case SADB_X_EXT_NAT_T_FRAG:
 7650 #endif
 7651                         /* duplicate check */
 7652                         /*
 7653                          * XXX Are there duplication payloads of either
 7654                          * KEY_AUTH or KEY_ENCRYPT ?
 7655                          */
 7656                         if (mhp->ext[ext->sadb_ext_type] != NULL) {
 7657                                 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
 7658                                         "%u\n", __func__, ext->sadb_ext_type));
 7659                                 m_freem(m);
 7660                                 V_pfkeystat.out_dupext++;
 7661                                 return EINVAL;
 7662                         }
 7663                         break;
 7664                 default:
 7665                         ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
 7666                                 __func__, ext->sadb_ext_type));
 7667                         m_freem(m);
 7668                         V_pfkeystat.out_invexttype++;
 7669                         return EINVAL;
 7670                 }
 7671 
 7672                 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
 7673 
 7674                 if (key_validate_ext(ext, extlen)) {
 7675                         m_freem(m);
 7676                         V_pfkeystat.out_invlen++;
 7677                         return EINVAL;
 7678                 }
 7679 
 7680                 n = m_pulldown(m, off, extlen, &toff);
 7681                 if (!n) {
 7682                         /* m is already freed */
 7683                         return ENOBUFS;
 7684                 }
 7685                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
 7686 
 7687                 mhp->ext[ext->sadb_ext_type] = ext;
 7688                 mhp->extoff[ext->sadb_ext_type] = off;
 7689                 mhp->extlen[ext->sadb_ext_type] = extlen;
 7690         }
 7691 
 7692         if (off != end) {
 7693                 m_freem(m);
 7694                 V_pfkeystat.out_invlen++;
 7695                 return EINVAL;
 7696         }
 7697 
 7698         return 0;
 7699 }
 7700 
 7701 static int
 7702 key_validate_ext(ext, len)
 7703         const struct sadb_ext *ext;
 7704         int len;
 7705 {
 7706         const struct sockaddr *sa;
 7707         enum { NONE, ADDR } checktype = NONE;
 7708         int baselen = 0;
 7709         const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
 7710 
 7711         if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
 7712                 return EINVAL;
 7713 
 7714         /* if it does not match minimum/maximum length, bail */
 7715         if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
 7716             ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
 7717                 return EINVAL;
 7718         if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
 7719                 return EINVAL;
 7720         if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
 7721                 return EINVAL;
 7722 
 7723         /* more checks based on sadb_ext_type XXX need more */
 7724         switch (ext->sadb_ext_type) {
 7725         case SADB_EXT_ADDRESS_SRC:
 7726         case SADB_EXT_ADDRESS_DST:
 7727         case SADB_EXT_ADDRESS_PROXY:
 7728                 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
 7729                 checktype = ADDR;
 7730                 break;
 7731         case SADB_EXT_IDENTITY_SRC:
 7732         case SADB_EXT_IDENTITY_DST:
 7733                 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
 7734                     SADB_X_IDENTTYPE_ADDR) {
 7735                         baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
 7736                         checktype = ADDR;
 7737                 } else
 7738                         checktype = NONE;
 7739                 break;
 7740         default:
 7741                 checktype = NONE;
 7742                 break;
 7743         }
 7744 
 7745         switch (checktype) {
 7746         case NONE:
 7747                 break;
 7748         case ADDR:
 7749                 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
 7750                 if (len < baselen + sal)
 7751                         return EINVAL;
 7752                 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
 7753                         return EINVAL;
 7754                 break;
 7755         }
 7756 
 7757         return 0;
 7758 }
 7759 
 7760 void
 7761 key_init(void)
 7762 {
 7763         int i;
 7764 
 7765         for (i = 0; i < IPSEC_DIR_MAX; i++)
 7766                 LIST_INIT(&V_sptree[i]);
 7767 
 7768         LIST_INIT(&V_sahtree);
 7769 
 7770         for (i = 0; i <= SADB_SATYPE_MAX; i++)
 7771                 LIST_INIT(&V_regtree[i]);
 7772 
 7773         LIST_INIT(&V_acqtree);
 7774         LIST_INIT(&V_spacqtree);
 7775 
 7776         /* system default */
 7777         V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
 7778         V_ip4_def_policy.refcnt++;      /*never reclaim this*/
 7779 
 7780         if (!IS_DEFAULT_VNET(curvnet))
 7781                 return;
 7782 
 7783         SPTREE_LOCK_INIT();
 7784         REGTREE_LOCK_INIT();
 7785         SAHTREE_LOCK_INIT();
 7786         ACQ_LOCK_INIT();
 7787         SPACQ_LOCK_INIT();
 7788 
 7789 #ifndef IPSEC_DEBUG2
 7790         timeout((void *)key_timehandler, (void *)0, hz);
 7791 #endif /*IPSEC_DEBUG2*/
 7792 
 7793         /* initialize key statistics */
 7794         keystat.getspi_count = 1;
 7795 
 7796         printf("IPsec: Initialized Security Association Processing.\n");
 7797 }
 7798 
 7799 #ifdef VIMAGE
 7800 void
 7801 key_destroy(void)
 7802 {
 7803         struct secpolicy *sp, *nextsp;
 7804         struct secacq *acq, *nextacq;
 7805         struct secspacq *spacq, *nextspacq;
 7806         struct secashead *sah, *nextsah;
 7807         struct secreg *reg;
 7808         int i;
 7809 
 7810         SPTREE_LOCK();
 7811         for (i = 0; i < IPSEC_DIR_MAX; i++) {
 7812                 for (sp = LIST_FIRST(&V_sptree[i]); 
 7813                     sp != NULL; sp = nextsp) {
 7814                         nextsp = LIST_NEXT(sp, chain);
 7815                         if (__LIST_CHAINED(sp)) {
 7816                                 LIST_REMOVE(sp, chain);
 7817                                 free(sp, M_IPSEC_SP);
 7818                         }
 7819                 }
 7820         }
 7821         SPTREE_UNLOCK();
 7822 
 7823         SAHTREE_LOCK();
 7824         for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
 7825                 nextsah = LIST_NEXT(sah, chain);
 7826                 if (__LIST_CHAINED(sah)) {
 7827                         LIST_REMOVE(sah, chain);
 7828                         free(sah, M_IPSEC_SAH);
 7829                 }
 7830         }
 7831         SAHTREE_UNLOCK();
 7832 
 7833         REGTREE_LOCK();
 7834         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
 7835                 LIST_FOREACH(reg, &V_regtree[i], chain) {
 7836                         if (__LIST_CHAINED(reg)) {
 7837                                 LIST_REMOVE(reg, chain);
 7838                                 free(reg, M_IPSEC_SAR);
 7839                                 break;
 7840                         }
 7841                 }
 7842         }
 7843         REGTREE_UNLOCK();
 7844 
 7845         ACQ_LOCK();
 7846         for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
 7847                 nextacq = LIST_NEXT(acq, chain);
 7848                 if (__LIST_CHAINED(acq)) {
 7849                         LIST_REMOVE(acq, chain);
 7850                         free(acq, M_IPSEC_SAQ);
 7851                 }
 7852         }
 7853         ACQ_UNLOCK();
 7854 
 7855         SPACQ_LOCK();
 7856         for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
 7857             spacq = nextspacq) {
 7858                 nextspacq = LIST_NEXT(spacq, chain);
 7859                 if (__LIST_CHAINED(spacq)) {
 7860                         LIST_REMOVE(spacq, chain);
 7861                         free(spacq, M_IPSEC_SAQ);
 7862                 }
 7863         }
 7864         SPACQ_UNLOCK();
 7865 }
 7866 #endif
 7867 
 7868 /*
 7869  * XXX: maybe This function is called after INBOUND IPsec processing.
 7870  *
 7871  * Special check for tunnel-mode packets.
 7872  * We must make some checks for consistency between inner and outer IP header.
 7873  *
 7874  * xxx more checks to be provided
 7875  */
 7876 int
 7877 key_checktunnelsanity(sav, family, src, dst)
 7878         struct secasvar *sav;
 7879         u_int family;
 7880         caddr_t src;
 7881         caddr_t dst;
 7882 {
 7883         IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
 7884 
 7885         /* XXX: check inner IP header */
 7886 
 7887         return 1;
 7888 }
 7889 
 7890 /* record data transfer on SA, and update timestamps */
 7891 void
 7892 key_sa_recordxfer(sav, m)
 7893         struct secasvar *sav;
 7894         struct mbuf *m;
 7895 {
 7896         IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
 7897         IPSEC_ASSERT(m != NULL, ("Null mbuf"));
 7898         if (!sav->lft_c)
 7899                 return;
 7900 
 7901         /*
 7902          * XXX Currently, there is a difference of bytes size
 7903          * between inbound and outbound processing.
 7904          */
 7905         sav->lft_c->bytes += m->m_pkthdr.len;
 7906         /* to check bytes lifetime is done in key_timehandler(). */
 7907 
 7908         /*
 7909          * We use the number of packets as the unit of
 7910          * allocations.  We increment the variable
 7911          * whenever {esp,ah}_{in,out}put is called.
 7912          */
 7913         sav->lft_c->allocations++;
 7914         /* XXX check for expires? */
 7915 
 7916         /*
 7917          * NOTE: We record CURRENT usetime by using wall clock,
 7918          * in seconds.  HARD and SOFT lifetime are measured by the time
 7919          * difference (again in seconds) from usetime.
 7920          *
 7921          *      usetime
 7922          *      v     expire   expire
 7923          * -----+-----+--------+---> t
 7924          *      <--------------> HARD
 7925          *      <-----> SOFT
 7926          */
 7927         sav->lft_c->usetime = time_second;
 7928         /* XXX check for expires? */
 7929 
 7930         return;
 7931 }
 7932 
 7933 /* dumb version */
 7934 void
 7935 key_sa_routechange(dst)
 7936         struct sockaddr *dst;
 7937 {
 7938         struct secashead *sah;
 7939         struct route *ro;
 7940 
 7941         SAHTREE_LOCK();
 7942         LIST_FOREACH(sah, &V_sahtree, chain) {
 7943                 ro = &sah->route_cache.sa_route;
 7944                 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
 7945                  && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
 7946                         RTFREE(ro->ro_rt);
 7947                         ro->ro_rt = (struct rtentry *)NULL;
 7948                 }
 7949         }
 7950         SAHTREE_UNLOCK();
 7951 }
 7952 
 7953 static void
 7954 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
 7955 {
 7956         IPSEC_ASSERT(sav != NULL, ("NULL sav"));
 7957         SAHTREE_LOCK_ASSERT();
 7958 
 7959         if (sav->state != state) {
 7960                 if (__LIST_CHAINED(sav))
 7961                         LIST_REMOVE(sav, chain);
 7962                 sav->state = state;
 7963                 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
 7964         }
 7965 }
 7966 
 7967 void
 7968 key_sa_stir_iv(sav)
 7969         struct secasvar *sav;
 7970 {
 7971 
 7972         IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
 7973         key_randomfill(sav->iv, sav->ivlen);
 7974 }
 7975 
 7976 /* XXX too much? */
 7977 static struct mbuf *
 7978 key_alloc_mbuf(l)
 7979         int l;
 7980 {
 7981         struct mbuf *m = NULL, *n;
 7982         int len, t;
 7983 
 7984         len = l;
 7985         while (len > 0) {
 7986                 MGET(n, M_DONTWAIT, MT_DATA);
 7987                 if (n && len > MLEN)
 7988                         MCLGET(n, M_DONTWAIT);
 7989                 if (!n) {
 7990                         m_freem(m);
 7991                         return NULL;
 7992                 }
 7993 
 7994                 n->m_next = NULL;
 7995                 n->m_len = 0;
 7996                 n->m_len = M_TRAILINGSPACE(n);
 7997                 /* use the bottom of mbuf, hoping we can prepend afterwards */
 7998                 if (n->m_len > len) {
 7999                         t = (n->m_len - len) & ~(sizeof(long) - 1);
 8000                         n->m_data += t;
 8001                         n->m_len = len;
 8002                 }
 8003 
 8004                 len -= n->m_len;
 8005 
 8006                 if (m)
 8007                         m_cat(m, n);
 8008                 else
 8009                         m = n;
 8010         }
 8011 
 8012         return m;
 8013 }
 8014 
 8015 /*
 8016  * Take one of the kernel's security keys and convert it into a PF_KEY
 8017  * structure within an mbuf, suitable for sending up to a waiting
 8018  * application in user land.
 8019  * 
 8020  * IN: 
 8021  *    src: A pointer to a kernel security key.
 8022  *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
 8023  * OUT:
 8024  *    a valid mbuf or NULL indicating an error
 8025  *
 8026  */
 8027 
 8028 static struct mbuf *
 8029 key_setkey(struct seckey *src, u_int16_t exttype) 
 8030 {
 8031         struct mbuf *m;
 8032         struct sadb_key *p;
 8033         int len;
 8034 
 8035         if (src == NULL)
 8036                 return NULL;
 8037 
 8038         len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
 8039         m = key_alloc_mbuf(len);
 8040         if (m == NULL)
 8041                 return NULL;
 8042         p = mtod(m, struct sadb_key *);
 8043         bzero(p, len);
 8044         p->sadb_key_len = PFKEY_UNIT64(len);
 8045         p->sadb_key_exttype = exttype;
 8046         p->sadb_key_bits = src->bits;
 8047         bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
 8048 
 8049         return m;
 8050 }
 8051 
 8052 /*
 8053  * Take one of the kernel's lifetime data structures and convert it
 8054  * into a PF_KEY structure within an mbuf, suitable for sending up to
 8055  * a waiting application in user land.
 8056  * 
 8057  * IN: 
 8058  *    src: A pointer to a kernel lifetime structure.
 8059  *    exttype: Which type of lifetime this is. Refer to the PF_KEY 
 8060  *             data structures for more information.
 8061  * OUT:
 8062  *    a valid mbuf or NULL indicating an error
 8063  *
 8064  */
 8065 
 8066 static struct mbuf *
 8067 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
 8068 {
 8069         struct mbuf *m = NULL;
 8070         struct sadb_lifetime *p;
 8071         int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
 8072 
 8073         if (src == NULL)
 8074                 return NULL;
 8075 
 8076         m = key_alloc_mbuf(len);
 8077         if (m == NULL)
 8078                 return m;
 8079         p = mtod(m, struct sadb_lifetime *);
 8080 
 8081         bzero(p, len);
 8082         p->sadb_lifetime_len = PFKEY_UNIT64(len);
 8083         p->sadb_lifetime_exttype = exttype;
 8084         p->sadb_lifetime_allocations = src->allocations;
 8085         p->sadb_lifetime_bytes = src->bytes;
 8086         p->sadb_lifetime_addtime = src->addtime;
 8087         p->sadb_lifetime_usetime = src->usetime;
 8088         
 8089         return m;
 8090 
 8091 }

Cache object: 8505282321c303ef544fd08305901686


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