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  -  FREEBSD10  -  FREEBSD9  -  FREEBSD92  -  FREEBSD91  -  FREEBSD90  -  FREEBSD8  -  FREEBSD82  -  FREEBSD81  -  FREEBSD80  -  FREEBSD7  -  FREEBSD74  -  FREEBSD73  -  FREEBSD72  -  FREEBSD71  -  FREEBSD70  -  FREEBSD6  -  FREEBSD64  -  FREEBSD63  -  FREEBSD62  -  FREEBSD61  -  FREEBSD60  -  FREEBSD5  -  FREEBSD55  -  FREEBSD54  -  FREEBSD53  -  FREEBSD52  -  FREEBSD51  -  FREEBSD50  -  FREEBSD4  -  FREEBSD3  -  FREEBSD22  -  cheribsd  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1  -  FREEBSD-LIBC  -  FREEBSD8-LIBC  -  FREEBSD7-LIBC  -  FREEBSD6-LIBC  -  GLIBC27 
SearchContext: -  none  -  3  -  10 

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