The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netipsec/key.c

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

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

Cache object: c240ca9ea4e6a781c7e682c19e2eb853


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.