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-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

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