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